#!/bin/sh
# We are called with stdin/out/err = /dev/null

resetgracetime=300

logfile=/var/log/reboot/`date '+%Y%m%d%H%M%S'`.log
mkdir -p /var/log/reboot

PATH=/bin

function say() {
    printf "\r%s\n\r" "$*"
}

# Since there is a potential for various fuckups during umount,
# we start delayed hard reboot here which will forcibly
# reboot hung box in a remote datacenter a thousand miles away ;)
if test "$1" = "-r"; then
    ./hardshutdown -r "$resetgracetime" &
fi

# Now, (try to) open a console. I've seen reboots hung on
# open(/dev/console), therefore we do it _after_ hardshutdown
exec >/dev/console
exec 2>&1

if test "$1" = "-r"; then
    say "* `date '+%H:%M:%S'` Scheduled hard reboot in $resetgracetime seconds"
fi

say "* `date '+%H:%M:%S'` Stopping tasks (see /var/log/reboot/* files)"
# log reboot event to file. %Y%m%d%H%M%S: YYYYMMDDHHMMSS
./stop_tasks >"$logfile" 2>&1

say "* `date '+%H:%M:%S'` Setting Ctrl-Alt-<Del> to 'hard'"
# shamelessly stolen from util-linux-2.11h
./ctrlaltdel hard

say "* `date '+%H:%M:%S'` Stopping storage devices"
# we can't log this: we are about to unmount everything!
./stop_storage "$@"

# If we have cmdline params, start hardshutdown with them
test "$*" && ./hardshutdown "$@"

# Just sleep endlessly...
say "* `date '+%H:%M:%S'` You may now power off or press Ctrl-Alt-<Del> to reboot"
while true; do
    sleep 32000
done
