#!/bin/sh

set -e

## 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.

RETVAL=0

USERDN=$1
USERID=`echo $USERDN | sed "s/^uid=\([^,]*\),.*$/\1/"`

# The new user password is in environment, $USERPASSWORD

## check if provided password corresponds to hash saved in ldap database:

TMPFILE=$(tempfile)
cat <<EOF | tr -d "\n" > $TMPFILE
$USERPASSWORD
EOF
IAM=`ldapwhoami -x -Z -y $TMPFILE -D $USERDN 2>/dev/null || true`
if [ "$IAM" = "dn:$USERDN" ] ; then
    cat > $TMPFILE <<EOF
change_password -pw $USERPASSWORD $USERID
EOF
    cat $TMPFILE  | kadmin.local 2>&1 | logger -t gosa-sync -p notice
    logger -t gosa-sync -p notice Kerberos password for \'$USERID\' changed.
else
    RETVAL=1
    logger -t gosa-sync -p warning Could not verify password for \'$USERID\'. Nothing done. 
fi 

rm $TMPFILE
exit $RETVAL
