#!/bin/sh
#
# Finalize Unmount and Reboot/Halt

# Set the path.
PATH=/sbin:/bin

# See how we were called
case "$0" in
	*halt)
		message="The system is halted"
		command="/sbin/halt"
		;;
	*poweroff)
		message="The system is powered off"
		command="/sbin/poweroff"
		;;
	*reboot)
		message="Rebooting the system..."
		command="/sbin/reboot"
		;;
	*)
		echo "call me as '*halt' or '*poweroff' or '*reboot'"
		exit 1
		;;
esac

killall sdpd 2>/dev/null
 
# Write to wtmp file before unmounting /var
halt -w 2>/dev/null

# Turn off swap, then unmount file systems.
swapoff -a 2>/dev/null

if [ "`grep file /proc/swaps`" != "" ]; then
    for s in `cat /proc/swaps|grep file|/usr/bin/cut -d" " -f1`
    do
      swapoff $s 2>/dev/null
    done
fi
if [ "`grep part /proc/swaps`" != "" ]; then
    for p in `cat /proc/swaps|grep part|/usr/bin/cut -d" " -f1`
    do
      swapoff $p 2>/dev/null
    done
fi

for i in `mount|grep loop|/usr/bin/cut -d" " -f3`
do
    umount $i 2>/dev/null
done
for i in 6 5 4 3 2 1 0
do
    losetup -d /dev/loop$i 2>/dev/null
done

umount /data 2>/dev/null 
umount /mnt/user 2>/dev/null
umount /mnt/card2 2>/dev/null
umount /mnt/card 2>/dev/null
umount /mnt/cf 2>/dev/null

# Unmount
sig=
retry=3
remaining=`cat /proc/mounts | /bin/sed -e '/^rootfs/D;/^none/D;/\/dev\/root/D;/\/var/D;/\/dev/D;/\/home/D;/proc/D;/loopfs/D;s/[0-9a-zA-Z\:\/\(\)]* */\2/;s/ .*//'`
while [ -n "$remaining" -a "$retry" -gt 0 ]
do
	umount -a -f 2>/dev/null
	sleep 2
	remaining=`cat /proc/mounts | /bin/sed -e '/^rootfs/D;/^none/D;/\/dev\/root/D;/\/var/D;/\/dev/D;/\/home/D;/proc/D;/loopfs/D;s/[0-9a-zA-Z\:\/\(\)]* */\2/;s/ .*//'`
	[ -z "$remaning" ] && break
	fuser -k -m $sig $remaining >/dev/null
	sleep 3
	retry=$(($retry-1))
	sig=-9
done

#umount /data 2>/dev/null 
#umount /mnt/user 2>/dev/null
#umount /mnt/card2 2>/dev/null
#umount /mnt/card 2>/dev/null
#umount /mnt/cf 2>/dev/null
umount /media/realroot 2>/dev/null

# Remount read only anything that's left mounted
for list in `mount | egrep '(ext3 | ext2 | minix | vfat | reiserfs)' |sed -e 's/.* on //;s/ .*//'`
do
	if [ "$list" != "" ]; then 
		echo "remounting  $list"
                #cd /media/hdd
		mount -f -o ro,remount $list 2>/dev/null
        fi
done

#/etc/rc.d/init.d/pcmcia stop
umount /proc >/dev/null 2>/dev/null

# Now halt or reboot
echo "$message"
sleep 5
exec $command -nf
