#!/bin/sh

PATH=/bin:/usr/bin

test ! "$*" || test "$*" = "-h" || test "$*" = "-r" || test "$*" = "-p" || {
    echo "Syntax: $0 [-h/-r/-p]"
    exit 1
}
test ! "$*" && test "${0##*/}" = "halt" && exec "$0" -h
test ! "$*" && test "${0##*/}" = "reboot" && exec "$0" -r
test ! "$*" && test "${0##*/}" = "poweroff" && exec "$0" -p

cd /app/shutdown-0.0.7/script || exit 1

i=`ulimit -n`
echo -n "Closing file descriptors $i-3... "
while test "$i" -ge 3; do
    eval "exec $i>&-"
    i=$(($i-1))
done
echo "done."
	
echo "System is going down. Please stand by..."

# setsid & /dev/null
# make it a process leader & detach it from current tty
# Why /dev/null?
# I have seen a system which locked up while opening /dev/console
# due to the bug (?) in keyboard driver.
#
# Horror story (aka 'why SHELL="/bin/sh"?'):
# without it, bash reads /etc/passwd to learn it.
# do_shutdown was keeping /usr busy because
# bash needed to resolve uids to users via external lib
# specified in /etc/nsswitch.conf.
setsid env - PATH="$PATH" SHELL="/bin/sh" ./do_shutdown "$@" </dev/null >/dev/null 2>&1 &

# FIXME: what if we can't read sleep binary anymore?
# (not a problem really, we got killed by that time)
while true; do sleep 32000; done
