#!/bin/bash
# Original Author: Tomas M <http://www.linux-live.org/>
# Author: Daniel K. <http://danielisko.net, http://git.danielisko.net>

action="${1}"
. /lib/.config
. /lib/functions
detach_loops()
{
	losetup -a | cut -d : -f 1 | xargs -r -n 1 losetup -d
}
umount_all()
{
	for i in $(tac /proc/mounts | cut -d" " -f2 | grep "^${1}"); do
		umount -fld ${i}
		detach_loops
	done
}

exec >/dev/console >&1 2>&1 <&1
[[ "${DEBUG_IS_ENABLED}" = "true" ]]&&set -x
debugShell
echo "Linux Live Framework - Shutdown Magic!"
echo "Entering to clean-up things before ${action}..."
(
	mdev -s
	sleep 1.5
	detach_loops
	umount_all /oldroot
	NR=100
	for i in $(tac /proc/mounts | cut -d" " -f2 | grep ^/oldroot/.); do
	   NR=$((${NR}+1))
	   mkdir -p /move/${NR}
	   mount --move ${i} /move/${NR}
	   umount -fld /oldroot
	done
	for i in 1 2 3 4; do
		for d in $(ls -1 /move 2>/dev/null | sort); do
			umount_all /move/${d}
		done
	done
	umount_all /memory
) >/dev/null 2>&1
case ${action} in
	reboot|poweroff|halt|shutdown) ${action} -f;;
	*) reboot -f;;
esac
emergencyShell #Last luck emergency shell after reboot doesn't work; usefull for debugging
