#!/bin/sh

CFGLOC="/.cfg"
COPYTORAMLOC="/.cfg/copytoram"
FIRMWARELOC="/.cfg/firmware"
ISOLOC="/.iso"
MOUNTLOC="/rootfs"
NEWLOC="/.newroot"
OLDLOC="/.oldroot"
SCANLOC="/.cfg/scan"
UNIONLOC="/.cfg/union"
OVERLAY_UPPERLOC="/.cfg/overlay_upper"
OVERLAY_WORKLOC="/.cfg/overlay_work"
PARAM_FILE="$CFGLOC/.bootparam"

# Cleanup scripts for CD-boot.
# To eject CD drive after finish CD Linux session, some cleanup and ummount
# is needed on this part. 

echo "--- reverse pivot ---"

# reverse pivot (to unmount)
pivot_root $OLDLOC $OLDLOC/$NEWLOC


# Read .bootparam again
if [ -e $PARAM_FILE ];
then
  . $PARAM_FILE
fi

# kill processs
PID="pidof clean"
for pid in $( ps | grep -v "PID" | egrep -v "\[.*\]" | grep -F -v mount | sed -r "s/^[[:space:]]*([0-9]+).*/\\1/" );
do
  declare -i cpid=`$PID`
  if test $pid -lt $cpid;
  then
    if test $pid -ne 1;
    then
      LIST="$LIST $pid"
    fi
  fi
done

kill -s TERM $LIST >/dev/null 2>&1
sleep 2
kill -s KILL $LIST >/dev/null 2>&1
sync
sync
sync

# unmount file system
umount -lf $NEWLOC/proc >/dev/null 2>&1
umount -lf $NEWLOC/sys >/dev/null 2>&1
umount -lf $NEWLOC/tmp >/dev/null 2>&1
umount -lf $NEWLOC/dev/pts >/dev/null 2>&1
umount -lf $NEWLOC/dev >/dev/null 2>&1
umount -lf $NEWLOC >/dev/null 2>&1
umount -lf $UNIONLOC >/dev/null 2>&1

if test -n "$cocon_fromiso_enabled";
then
	umount -lf $ISOLOC >/dev/null 2>&1
fi

umount -lf $COPYTORAMLOC >/dev/null 2>&1
umount -lf $CFGLOC >/dev/null 2>&1

# Eject CD drive
if test -n "$cocon_need_eject_on_clean" -a -z "$bootparam_noeject" -a -z "$cocon_copyonram_enabled";
then
  echo "--- Eject CD device. ($cocon_need_eject_on_clean) ---"
  echo "Press [Enter] key (or wait 2min) to turn off computer."
  fuser -k /dev/$cocon_need_eject_on_clean
  sync
  eject -s /dev/$cocon_need_eject_on_clean >/dev/null 2>&1
  eject /dev/$cocon_need_eject_on_clean >/dev/null 2>&1
  read -t 120
fi

# unmount /dev
umount -lf /dev >/dev/null 2>&1

# and poweroff or reboot
#case $1 in
#	"off")
#		poweroff
#		;;
#	"reboot")
#		reboot
#		;;
#esac
