#!/bin/bash

set -ex

## 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 user and create home directory and principal:
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`
                        test -n $FQDN && kadmin.local -q "add_principal -policy hosts -randkey -x \"$HOSTDN\" host/$FQDN" && logger -t gosa-create-host -p notice Krb5 principal \'host/$FQDN\' created.
                        ;;
                esac 
done

exit 0

