#! /bin/sh

argv0=$0

function error {
    echo "$argv0: $@" >&2
}
function show_help {

    # HERE documents are implemented by using temporary files which
    # may not be available, if the system is a bit screwed up

    echo "Shutdown syntax -- see shutdown(8)"
    echo "	shutdown -h [time]	halt system"
    echo "	shutdown -p [time]	halt system and power off"
    echo "	shutdown -r [time]	reboot system"
    echo "	shutdown -s [time]	bring system down then up without rebooting"
    echo
    echo "[time] can be one of \"now\", or time hhmm to wait until, or"
    echo "+number of minutes to wait"
}

case $1 in
	-h) 
	    sig=USR1
	;;
	
	-p)
	    sig=USR2
	;;

	-r)
	   sig=INT
	 ;;

	 --help)
	    show_help
	    exit 0
	;;

	--version)
	    echo "shutdown from jinit: \$Id: shutdown,v 1.2 2001/01/08 20:35:32 john Exp $"
	    exit 0
	;;

	 *) 
	    error bad syntax
	    show_help
	    exit 1
	 ;;
esac

case $2 in
	now)
	    ;;
	+*)
	    sleep ${2#+}m
	    ;;
	*)
	    # Requires GNU date

	    cur=`date +%s`
	    after=`date --date=$2 +%s`
	    if test "x$after" = "x"; then
		error "unable to parse time string (note that you need GNU date)"
		exit 1
	    fi

	    if test $cur -gt $after; then
		after=$(($after+24*60*60))
	    fi

	    sleep $(($after - $cur))
	 ;;
esac

kill -$sig 1
