#! /bin/bash -e

# = = = = = = = = = = = = = = = = = = = = = = =
# =     Copyright (C) 2015-2025 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

case "$1" in
	configure)
		TFTPROOT="/tftpboot/opsi/opsi-linux-bootimage"
		cfg="/etc/opsi/opsi.conf"
		if [ ! -e $cfg -a -e "${cfg}.dpkg-new" ]; then
		    cfg="${cfg}.dpkg-new"
		fi
		if [ -e $cfg ]; then
			fileadmingroup=$(grep "^fileadmingroup" $cfg | cut -d "=" -f 2 | sed 's/ //g;s/"//g')
		else
			fileadmingroup=pcpatch
		fi

		chown -R opsiconfd:$fileadmingroup /tftpboot/opsi/opsi-linux-bootimage
		chmod 2775 /tftpboot/opsi/opsi-linux-bootimage
		chmod 2775 /tftpboot/opsi/opsi-linux-bootimage/cfg
		chmod 2775 /tftpboot/opsi/opsi-linux-bootimage/loader
		find /tftpboot/opsi/opsi-linux-bootimage -type f -exec chmod 664 {} \;

		opsi-setup --set-rights /tftpboot >/dev/null 2>/dev/null || true
		opsipxeconfd setup >/dev/null 2>/dev/null || true

		if [ -e $TFTPROOT/cfg/grub-custom.cfg.old ]; then
			if grep -Fq "background_image" $TFTPROOT/cfg/grub-custom.cfg.old; then
				$VERBOSE && echo "grub-custom.cfg needed an update. If you made some changes in this file a backup exists as grub-custom.cfg.old from where you can take over your menu entries"
			else
				mv $TFTPROOT/cfg/grub-custom.cfg $TFTPROOT/cfg/grub-custom.cfg.opsi
				mv $TFTPROOT/cfg/grub-custom.cfg.old $TFTPROOT/cfg/grub-custom.cfg
			fi
		fi
        if [ -e $TFTPROOT/cfg/grub-settings.cfg.old ]; then
			mv $TFTPROOT/cfg/grub-settings.cfg $TFTPROOT/cfg/grub-settings.cfg.opsi
			mv $TFTPROOT/cfg/grub-settings.cfg.old $TFTPROOT/cfg/grub-settings.cfg
		fi

		if which ucr >/dev/null 2>/dev/null; then
			$VERBOSE && echo "Detected UCS System - moving tftpboot files into /tftpboot/"
			rm -rf /tftpboot/miniroot*
			rm -rf /tftpboot/vmlinuz*
			cp -r $TFTPROOT/* /tftpboot/ || true
			if [ ! -L  /tftpboot/cfg ]; then
				rm -rf /tftpboot/cfg
				cd /tftpboot/
				ln -sf ./opsi/opsi-linux-bootimage/cfg ./cfg
			fi
		fi

	;;

	abort-upgrade|abort-remove|abort-deconfigure)

	;;

	*)
		echo "postinst called with unknown argument \`$1'" >&2
		exit 1
	;;
esac

exit 0

