#!/bin/sh
#
# dRock Linux: /etc/init.d/down
#
# This is the shutdown and reboot script.
#
# (C) JAN 2001 by V Ziegler <ziegler@informatik.hu-berlin.de> 
#

exec 2>&1

export PATH=/bin:/sbin:/usr/bin:/usr/sbin

. /etc/init.d/master.sh

touch /var/log/init.msg /var/log/boot.msg
mv /var/log/init.msg /var/log/init.old
mv /var/log/boot.msg /var/log/boot.old

c_writeln "*** running shutdown script ***"

case "$1" in
	*halt)   command=halt   ;;
	*reboot) command=reboot ;;
	*)       echo "Never call this script directly !" ; exit 1 ;;
esac

. /etc/conf/bootdown
[ -f /fastdown ] && FASTDOWN=1
[ $FASTDOWN = 1 ] && echo "Fast shutdown mode enabled."

c_writeln "writing a wtmp record"
sub_exec ${command}" -w" 

c_writeln "Saving kernel random seed ..."
dd if=/dev/urandom of=/var/state/random-seed count=1 2> /dev/null

if [ $FASTDOWN = 1 ]
then
	c_writeln "sending all processes a SIGTERM (15)"
	sub_exec "killall5 -15" ; sleep 3
	c_writeln "sending all processes a SIGKILL (9)"
	sub_exec "killall5 -9" ; sleep 2
else
	c_writeln "sending all processes a SIGTERM (15)"
	sub_exec "killall5 -15" ; sleep 3
	c_writeln "sending all processes a 2nd SIGTERM (15)"
	sub_exec "killall5 -15" ; sleep 1
	c_writeln "sending all processes a SIGKILL (9)"
	sub_exec "killall5 -9" ; sleep 2
fi

c_writeln "turning off swap"
sub_exec "swapoff -a"  
sync
sleep 1

if [ $FASTDOWN = 1 ]
then
	c_writeln "unmounting file systems"
	sub_exec "umount -vnra -t noproc,nodevfs"
	c_writeln "remounting root file system ro" 
	sub_exec "mount -vn -o remount,ro /"
	sync ; sleep 1
else
	for x in sync ro
	do
		c_writeln "remounting disks $x"
		grep '^/dev/' /proc/mounts | \
		grep -v iso9660 | \
		cut -f2 -d' ' | sort -ru | \
		while read fs; do
			mount -vn -o remount,$x $fs
		done
		sync ; sleep 1
	done

	c_writeln "unmounting file systems ..."
	grep -Ev '^none /(dev|proc)' /proc/mounts | \
	cut -f2 -d' ' | sort -ru | \
	while read fs; do
		umount -vn $fs
	done
	sync ; sleep 1
	umount -vnra -t noproc,devfs
	mount -vn -o remount,ro /
	sync ; sleep 1
fi

c_writeln "going to $command the system ..."
exec $command -d -f -i -p
