#!/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 creates the home directories and principals for users
## added with gosa.  There are some tests that make sure only
## non-existent home directories are created.  Malicious execution
## cannot hurt, because either the user is missing in ldap or his home
## directory already exists. In both cases nothing should happen.

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

# test if user ID exists
set +e
LANG=C ldapsearch -x "(&(uid=$USERID)(objectClass=gosaAccount))" -b "${USEROU}" | tail -n1 | grep -q -E "^# numEntries: 1$"
ret=$?
set -e
if [ "x$ret" = "x0" ]; then
	set +e
	LANG=C ldapsearch -x "(&(uid=$USERID)(objectClass=gosaAccount)(objectClass=krbPrincipalAux))" -b "${USEROU}" | tail -n1 | grep -q -E "^# numEntries: 1$"
	ret=$?
	set -e
	if [ "x$ret" = "x0" ]; then
		set +e
		success=$(LANG=C kadmin.local -q "modify_principal -allow_tix $USERID" | grep -E "^Principal\ .*@.*\ modified.$")
		set -e
		if [ -n "$success" ]; then
			logger -t gosa-lock-user -p notice "Kerberos account of user '$USERID' (DN: $USERDN) has been locked."
		else
			OUT="Locking Kerberos account of user '$USERID' (DN: $USERDN) failed."
			echo "$OUT"
			logger -t gosa-lock-user -p warning "$OUT"
		fi
	else
		logger -t gosa-lock-user -p notice "User account '$USERID' (DN: $USERDN) is not a Kerberos-enabled account. (Thus, skipping...)."
	fi
else
	OUT="User account '$USERID' (DN: $USERDN) does not exist."
	echo "$OUT"
	logger -t gosa-lock-user -p warning "$OUT"
fi

exit 0
