#!/bin/bash
# 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/cleanup

export PATH=.:/mnt/live:/usr/sbin:/usr/bin:/sbin:/bin
. liblinuxlive

header "starting Linux Live shutdown procedures..."

cd $INITRAMDISK
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 $COPY2RAM
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
   echo "Ejecting CD-ROM..."
   /bin/eject -m /dev/$MNT >/dev/null 2>&1
   sleep 3
   /bin/eject -t /dev/$MNT >/dev/null 2>&1
fi

# $1 = action, eg. poweroff, halt or reboot
# Seems to me like 'halt' doesn't work as expected, replaced by poweroff
if [ "$1" = "" ]; then reboot; fi
if [ "$1" = "halt" ]; then poweroff; else $1; fi
