#! /bin/bash -e

# = = = = = = = = = = = = = = = = = = = = = = =
# =        Copyright (C) 2015 uib GmbH        =
# =           http://www.uib.de               =
# =          All rights reserved.             =
# = = = = = = = = = = = = = = = = = = = = = = =

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

VERBOSE=true
TFTPROOT="/var/lib/univention-client-boot"

case "$1" in
	configure)
		if [ -e "/etc/opsi/opsi.conf" ]; then
			fileadmingroup=$(grep "fileadmingroup" /etc/opsi/opsi.conf | cut -d "=" -f 2 | sed 's/ //g')
		else
			fileadmingroup=pcpatch
		fi

		chown -R opsiconfd:$fileadmingroup /tftpboot/linux
		chmod 2775 /tftpboot/linux
		chmod 2775 /tftpboot/linux/pxelinux.cfg
		find /tftpboot/linux -type f -exec chmod 664 {} \;
		if [ ! -e /tftpboot/linux/pxelinux.cfg/default ]; then
			cd /tftpboot/linux/pxelinux.cfg/
			ln -sf default.menu default
			cd - >/dev/null
		fi
		serviceentry=$(opsi-admin --no-depot -Sd method config_getObjects '[]' '{"id":"clientconfig.configserver.url"}' | grep defaultValues | cut -d "'" -f2)
		if [ "$serviceentry" != "" ]; then
			sed -i "s,append.*$,& service=$serviceentry,g" /tftpboot/linux/pxelinux.cfg/default.menu
		fi
		opsi-setup --set-rights /tftpboot >/dev/null 2>/dev/null || true

		# check for Univention Corporate Server and link to directory
		if which ucr; then
			$VERBOSE && echo "Detected UCS System - linking tftpboot files into $TFTPROOT"
			if [ ! -d "$TFTPROOT" ]; then
                		$VERBOSE && echo "Creating $TFTPROOT"
                		mkdir $TFTPROOT
                		ln -sf /tftpboot/linux/pxelinux.0 $TFTPROOT/
                		$VERBOSE && echo "Setting rights for $TFTPROOT"
                		chmod 755 $TFTPROOT
                		if [ -d $TFTPROOT/pxelinux.cfg ]; then
                    			rm -rf $TFTPROOT/pxelinux.cfg
                		fi
				ln -sf /tftpboot/linux/pxelinux.cfg $TFTPROOT/
			fi
			ln -sf /tftpboot/linux/install $TFTPROOT/
			ln -sf /tftpboot/linux/install-x64 $TFTPROOT/
			ln -sf /tftpboot/linux/menu.c32 $TFTPROOT/
			ln -sf /tftpboot/linux/chain.c32 $TFTPROOT/
			ln -sf /tftpboot/linux/pxelinux.0 $TFTPROOT/
			ln -sf /tftpboot/linux/miniroot.bz2 $TFTPROOT/
			ln -sf /tftpboot/linux/miniroot-x64.bz2 $TFTPROOT/
			
		else
                        exit 0	
		fi
	;;
	
	abort-upgrade|abort-remove|abort-deconfigure)
	
	;;
	
	*)
		echo "postinst called with unknown argument \`$1'" >&2
		exit 1
	;;
esac

exit 0

