#!/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 principals for hosts added with FusionDirectory.

HOSTNAME=$1
DOMAIN=informatik.uni-kiel.de
FQDN=$1.$DOMAIN

## lookup user and create home directory and principal:
ldapsearch -xLLL "(&(|(cn=$HOSTNAME)(cn=$FQDN))(|(objectClass=GOHard)(objectClass=ipHost)))" \
           cn ipHostNumber macAddress 2>/dev/null  | perl -p00e 's/\r?\n //g' | \
while read KEY VALUE ; do 
       case "$KEY" in 
               dn:) HOSTNAME= ; IP= ; HOSTDN="dn=$VALUE" ;;
               cn:) HOSTNAME="$VALUE" ;;
               ipHostNumber:) IP="$VALUE" ;;
               macAddress:) MAC="$VALUE"  ;;
               "")
                       FQDN=$HOSTNAME.$DOMAIN
                       kadmin.local -q "add_principal -policy hosts -randkey -x $HOSTDN host/$FQDN" && logger -p notice Krb5 principal \'host/$FQDN\' created.
                       kadmin.local -q "add_principal -policy service -randkey -x $HOSTDN nfs/$FQDN" && logger -p notice Krb5 principal \'nfs/$FQDN\' created.
                       ;;
               esac 
done

exit 0
