#!/bin/bash

# Conforms to the nvram-wakeup semantics for setting the time
usage() {
	cat 1>&2  <<-EOF
		Usage: $0 [OPTIONS]
		  -s, --settime     Set the given wakeup date/time (given as a time_t value).
		  -d, --disable     Disable WakeUp. Equivalent to --settime=0.
		  -C, --configfile  Read board configuration from specified configuration file.
		  -I, --iwname      Specify the IW (infowriter) name.
		  -A, --directisa   Use direct ISA access to read/write nvram instead of /dev/nvram.
		  -N, --nowrite     Don't write any values (in /dev/nvram or /dev/rtc). For testing.
		  -D, --debug       Enable printing debug messages.
		  -l, --syslog      Log all output via syslogd instead of stdout/stderr.
		  -v, --version     Print version information.
		  -h, --help        Print this message (always to stderr, regardless of --syslog).

		  All specified wakeup times are times at which the PC should be up and running.
	EOF
}

WAKEUP_BEFORE=120	# seconds required for machine to start
DEBUG=0
STARTTIME=0
WRITE=1
SYSLOG=0

while [ $# -gt 0 ]
do
    case "$1" in
	-s|--settime)  STARTTIME=$2; shift;;
	-d|--disable)  STARTTIME=0;;
	-C|--configfile)  shift;;
	-I|--iwname)  shift;;
	-N|--nowrite)  WRITE=0;;
	-D|--debug)  DEBUG=1;;
	-l|--syslog)  SYSLOG=1;;
        -v|--version) ;;
        -h|--help) usage; exit 0 ;;
	--)	shift; break;;
	-*) usage; exit 1;;
	*)  break;;	# terminate while loop
    esac
    shift
done
# all command line switches are processed,
# "$@" contains all file names


# If start time is 0 then we should disable the wakeup
#
if [ $STARTTIME -eq 0 ]
then
	echo "00-00-00 00:00:00" > /proc/acpi/alarm
	exit 0
fi

# Calculate the desired wake up time in seconds from now 
# allowing for boot time
#
echo "Requested machine up by "  $(date -d "1970-01-01 UTC + $STARTTIME sec" "+%F %T %z")
WAKETIME=$(( STARTTIME - WAKEUP_BEFORE ))
NOW=$( date +%s )
if [ $(date +%s) -ge $WAKETIME ] 
then
	echo >&2 "Requested start time is in the past"
	exit 1
fi
echo "Will wake up at "  $(date -d "1970-01-01 UTC + $WAKETIME sec" "+%F %T %z")

SLEEPSECS=$(( WAKETIME - $(date +%s) ))
SECS=$(( SLEEPSECS % 60 ))
MINS=$(( SLEEPSECS/60  % 60 ))
HOURS=$(( SLEEPSECS/3600  % 24 ))
DAYS=$(( SLEEPSECS/86400 % 31 ))
echo "Sleep for $DAYS days $HOURS:$MINS:$SECS"


if [ $WRITE -eq 1 ]
then
	printf "+00-00-%02d %02d:%02d:%02d"  $DAYS $HOURS $MINS $SECS > /proc/acpi/alarm
fi
