#!/bin/bash

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 GOsa²

HOSTNAME="$1"

find_fqdn() {
	RELATIVE_HOSTNAME="$1"
	IPADDRESS="$2"
	host $IPADDRESS &>/dev/null && {
		# ask DNS first
		fqdn=`LANG=C host $IPADDRESS 2>/dev/null | cut -d" " -f5`
		echo "${fqdn/%./}"
	} || {
		ldapsearch -xLLL "(&(objectClass=dNSZone)(relativeDomainName=$RELATIVE_HOSTNAME))" \
		           zoneName aRecord | tr [A-Z] [a-z] | \
		while read KEY VALUE ; do
			case "$KEY" in
				dn:) ARECORD= ; ZONENAME= ;;
				zonename:) ZONENAME="$VALUE" ;;
				arecord:) ARECORD="$VALUE" ;;
				"")
					fqdn="${RELATIVE_HOSTNAME}.${ZONENAME}"
					[ "x$ARECORD" == "x$IPADDRESS" ] && { echo "$fqdn"; }
					;;
			esac
		done
	}
}

## lookup host and create host/<host> and nfs/<host> Krb5 principals:
ldapsearch -xLLL "(&(cn=$HOSTNAME)(|(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=`find_fqdn $HOSTNAME $IP`
			if ! [ "$FQDN" == "" ] ; then
			    kadmin.local -q "add_principal -policy hosts -randkey -x \"$HOSTDN\" host/$FQDN"
			    logger -t gosa-create-host -p notice Krb5 principal \'host/$FQDN\' created.
			    kadmin.local -q "add_principal -policy hosts -randkey nfs/$FQDN"
			    logger -t gosa-create-host -p notice Krb5 principal \'nfs/$FQDN\' created.
			    kadmin.local -q "ktadd -k /var/lib/debian-edu/host-keytabs/$FQDN.keytab host/$FQDN"
			    kadmin.local -q "ktadd -k /var/lib/debian-edu/host-keytabs/$FQDN.keytab nfs/$FQDN"
			    logger -t gosa-create-host -p notice Krb5 keytab file for \'$FQDN\' created.
			fi
			;;
	esac
done

# During creation of a host, we should ideally call update-dlw-krb5-keytabs
# here already. However, it is not possible to add a NIS netgroup tab to a
# GOsa² system before the system object (and the additional DNS bits) has/have
# been created. So, calling the update-dlw-krb5-keytabs script
# makes no sense here...

# FIXME: And: it would be really helpful to have POST-action hooks available for
# NIS netgroups... In case people don't edit hosts individually, but prefer
# mass-adding hosts to the diskless-workstation-hosts NIS netgroup.

/usr/share/debian-edu-config/tools/gosa-sync-dns-nfs

exit 0
