#!/bin/sh

set -ex

## This script is run by www-data using sudo. Keep that in mind!
## Make sure that malicious execution cannot hurt.
##
## This script synchronizes the kerberos password of principals to the posix password 
## whenever the password is changed in ldap by gosa. To make sure only authorized 
## changes happen, it is tested if the supplied password corresponds to the supplied 
## distinguished name in ldap.
##
## A caller not knowing the correct ldap password cannot change the principal's one.

USERDN="$1"
set +x
NEWPW="$USERPASSWORD"
set -x
USERID=`echo $USERDN | tr A-Z a-z | sed "s/^uid=\([^,]*\),.*$/\1/"`
PATH="/usr/bin:/usr/sbin:/bin:/sbin"

## check if provided password corresponds to hash saved in ldap database:
#set +e
#IAM=`ldapwhoami -x -Z -w "$NEWPW" -D "$USERDN" 2>/dev/null | perl -p00e 's/\r?\n //g' | tr [A-Z] [a-z]`
#if [ "$IAM" = "dn:$USERDN" ] ; then
#      set -e
       kadmin.local -q "change_password -pw \"$NEWPW\" \"$USERID\"" 1>/dev/null && echo "Updated Kerberos password for user '$USERID'.<br />"
       logger -t FusionDirectory-PwHook "Updated Kerberos password for user '$USERID'."
#else
#      echo "Warning: Could not verify password for '$USERID'. Nothing done.<br />"
#      logger -t FusionDirectory-PwHook "Warning: Could not verify password for '$USERID'. Nothing done."
#      exit 1
#fi

exit 0
