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

PREFIX=/net
HOSTNAME=$(hostname -s)
USERID="$1"

if which nscd 1>/dev/null; then
       nscd -i passwd
       nscd -i group
fi

## lookup user and create home directory and principal:
ldapsearch -xLLL "(&(uid=$USERID)(objectClass=posixAccount))" \
           cn homeDirectory gidNumber 2>/dev/null | perl -p00e 's/\r?\n //g' | \
while read KEY VALUE; do
       case "$KEY" in
               dn:) USERNAME= ; HOMEDIR= ; GROUPID= ; USERDN="dn=$VALUE" ;;
               cn:) USERNAME="$VALUE" ;;
               homeDirectory:) HOMEDIR="$VALUE" ;;
               gidNumber:) GROUPID="$VALUE"  ;;
               "")
                       test "$HOMEDIR" || continue
                       echo "$HOMEDIR" | grep -q "^$PREFIX/$HOSTNAME" && HOMEDIR=/home/$USERID || continue
                       test -e "$HOMEDIR" || {
                               cp -r /etc/skel $HOMEDIR
                               chown -R $USERID:$GROUPID $HOMEDIR
                               echo "Home directory '$HOMEDIR' created.<br />"
                       }
                       kadmin.local -q "add_principal -policy users -randkey -x \"$USERDN\" $USERID" 1>/dev/null 2>/dev/null && echo "Krb5 principal '$USERID' created.<br />"
                       x2godbadmin --adduser "$USERID" 1>/dev/null 2>/dev/null && echo "Enabled X2Go for user '$USERID'.<br />"
               ;;
       esac
done

exit 0
