#!/exec/ash
# Optional script to be called instead of final reboot/shutdown
# To safely switch back to initrd root and unmount everything possible
#
# Call it this way: exec /mnt/live/exec/halt-mol

export PATH="/sbin:/bin:/usr/sbin:/usr/bin:/exec:."
. /exec/libmol

header "starting Linux Live shutdown procedures..."
CD=$(awk '($3=="iso9660")&&($2=="/mnt/live/mnt/iso") {print $1}' /proc/mounts)
checkbootparam "noeject" && CD=""

cd $INITRAM
pivot_root . $UNION <dev/console >dev/console 2>&1

fumount $UNION/proc
fumount $UNION/sys
fumount $UNION/dev
fumount $UNION/boot
fumount $UNION

fumount $IMAGES/*

fumount $COPYTO
fumount $ISOMOUNT
fumount $MEMORY

fumount $MOUNTDIR/*

# eject cdrom devices
#MNT=$(ls -1 $MOUNTDIR 2>/dev/null | head -n 1)
#CD=$(cat /proc/sys/dev/cdrom/info 2>/dev/null | grep name | grep "$MNT")
if [ "$CD" ]; then
   # mtab and fstab is necessary for eject
   [ -f "/etc/mtab" ] || :>/etc/mtab
   [ -f "/etc/fstab" ] || :>/etc/fstab
   # disable kernel messages
   echo "0" >/proc/sys/kernel/printk
   echo "Ejecting CD-ROM..."
   #/exec/eject -m /dev/$MNT >/dev/null 2>&1
   /exec/eject $CD >/dev/null 2>&1
   read a
   /exec/eject -t $CD >/dev/null 2>&1
   # enable kernel messages
   echo "6">/proc/sys/kernel/printk
fi

echo "Remount read only anything..."
mount | awk '{ print $3 }' | while read line; do
    mount -n -o ro,remount $line 2>/dev/null
done


# $1 = action, eg. poweroff, halt or reboot
# Seems to me like 'halt' doesn't work as expected, replaced by poweroff
case "$1" in
	*halt*)
	exec /exec/poweroff
	;;
	*reboot*)
	exec /exec/reboot
	;;
	*)
	echo "unknown halt option: ${HALT}"
	echo "starting ash"
	exec /exec/ash
	;;
esac

