#!/bin/sh
# postinst script for systemd-init-diversity init

case "$1" in
    configure|triggered)
    	# convert /sbin/init-systemd to a relative symlink
		if test -L /usr/sbin/init-systemd; then
		echo "Converting init-dinit symlink to relative"
			ln --force --symbolic --relative "$(readlink --canonicalize /usr/sbin/init-systemd)" /usr/sbin/init-systemd
		fi
		# Provide /sbin/init if missing
		if [ ! -e /usr/sbin/init ]; then
		echo "Reinstating systemd as default init"
			rm -rf /sbin/init && ln -sf /usr/lib/systemd/systemd /usr/sbin/init
			ln --force --symbolic --relative "$(readlink --canonicalize /usr/sbin/init)" /usr/sbin/init
		fi
		# postinst script to replace poweroff
		if test -e /usr/lib/init-diversity/poweroff.sh; then
		echo "Reinstating multi-init poweroff function"
			ln -sf /usr/lib/init-diversity/poweroff.sh /usr/sbin/poweroff
		fi
		# postinst script to replace reboot
		if test -e /usr/lib/init-diversity/reboot.sh; then
		echo "Reinstating multi-init reboot function"
			ln -sf /usr/lib/init-diversity/reboot.sh /usr/sbin/reboot
		fi
		# postinst script to replace shutdown
		if test -e /usr/lib/init-diversity/shutdown.sh; then
		echo "Reinstating multi-init shutdown function"
			ln -sf /usr/lib/init-diversity/shutdown.sh /usr/sbin/shutdown
		fi
		# postinst script to replace runlevel
		if test -e /usr/lib/init-diversity/runlevel.sh; then
		echo "Reinstating multi-init shutdown function"
			ln -sf /usr/lib/init-diversity/runlevel.sh /usr/sbin/runlevel
		fi
		# postinst script to replace rc - mainly for sysvinit & OpenRC
		if [ -e /usr/lib/init-diversity/rc.sh ] && [ -d /etc/init.d/ ]; then
		echo "Reinstating multi-init rc function"
			ln -sf /usr/lib/init-diversity/rc.sh /etc/init.d/rc
		fi
		# postinst script to replace rcS - mainly for sysvinit & OpenRC
		if [ -e /usr/lib/init-diversity/rcS.sh ] && [ -d /etc/init.d/ ]; then
		echo "Reinstating multi-init rcS function"
			ln -sf /usr/lib/init-diversity/rcS.sh /etc/init.d/rcS
		fi
		# new init will need to be added to the GRUB menu
		if mountpoint -q /live/aufs; then
			echo "Live/Frugal system detected - Not updating GRUB"
			exit 0
        elif [ "$(stat -c %d/%i /)" != "$(stat -Lc %d/%i /proc/1/root 2>/dev/null)" ]; then
			echo "A chroot environment has been detected - Not updating GRUB"
			exit 0		
		else
			echo "Updating GRUB to reveal the updated init entry"
			update-grub
		fi
    ;;

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

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

#DEBHELPER#

exit 0
