#!/bin/sh
#
# VDR shutdown hook for ACPI - Tobias Grimm <vdr@e-tobi.net>
# --------------------------
#
# This shutdown hook sets the wakeup time for the next timer using
# ACPI. 
#

# read arguments for acpi-wakeup from conf-file
. /etc/vdr/vdr-addon-acpiwakeup.conf

# Defaults:
[ -z "$ACPI_ENABLED" ]        && export ACPI_ENABLED="yes"
[ -z "$ACPI_ALARM" ]          && export ACPI_ALARM="/proc/acpi/alarm"
[ -z "$ACPI_REGULAR_DAYS" ]   && export ACPI_REGULAR_DAYS="0"
[ -z "$ACPI_REGULAR_TIME" ]   && export ACPI_REGULAR_TIME="00:00"
[ -z "$ACPI_START_AHEAD" ]    && export ACPI_START_AHEAD="5"

LOG="logger -t vdr-addon-acpiwakeup "
TIMER=$1

TimeToString ()
{
    echo $(perl -e "(\$s,\$mi,\$h,\$d,\$mo,\$y,\$t,\$t,\$t)=\
	localtime($1); printf(\"%04d-%02d-%02d %02d:%02d:%02d\",\
	\$y+1900,\$mo+1,\$d,\$h,\$mi,\$s);")
}

if [ $ACPI_ENABLED = "yes" ]; then
    # check if we should wake up before the next timer:
    if [ $ACPI_REGULAR_DAYS -gt 0 ]; then
	NOW=$((`date +%s`))
	REGULAR_TIMER=$((`date -d "$ACPI_REGULAR_TIME" +%s`))
#	echo NOW: $NOW
#	echo REGULAR $REGULAR_TIMER
	if [ $REGULAR_TIMER -lt $NOW ] ; then
#	    echo later than REGULAR_TIME
	    REGULAR_TIMER=$((`date -d "$ACPI_REGULAR_TIME" +%s` + 24 * 60 * 60))
	fi
	echo $REGULAR_TIMER
	if [ $TIMER -eq 0 ] || [ $TIMER -gt 0 -a $REGULAR_TIMER -lt $TIMER ] ; then
	    TIMER=$REGULAR_TIMER
	fi
    fi
    if [ $TIMER -gt 0 ]; then
	TIMER=$(($TIMER - 60 * $ACPI_START_AHEAD))
    fi
    if [ $TIMER -gt 0 ] && [ $TIMER -lt $((`date +%s` + 5 * 60)) ]; then
	$LOG "Can not set wakeup time less than 5 minutes ahead."
	echo "ABORT_MESSAGE=\"Wakeup in less than 5 minutes, aborting!\""
        exit 1
    else
        # set the wakeup time
	if [ -e $ACPI_ALARM ]; then
	    if [ $TIMER -eq 0 ]; then
		# no wakeup - I don't really now right now, how to disable
		# the wakeup !!!!
		TIMER=$((`date +%s` - 5 * 60))
		TIME_TO_SET=`TimeToString $TIMER`
	    else
		# convert time_t to YYYY-MM-DD HH:MM:SS
		TIME_TO_SET=`TimeToString $TIMER`
	    fi
	    # now set the wakeup time:
	    $LOG "Current ACPI alarm time: `cat $ACPI_ALARM`"
	    $LOG "Setting ACPI alarm time to: $TIME_TO_SET"
	    echo $TIME_TO_SET >$ACPI_ALARM
	    # repeat some time to get shure it's realy written
	    sleep 1
	    echo $TIME_TO_SET >$ACPI_ALARM
	    sleep 1
	    echo $TIME_TO_SET >$ACPI_ALARM
#	    echo $TIME_TO_SET
	    $LOG "New ACPI alarm time: `cat $ACPI_ALARM`"
	else
	    $LOG "$ACPI_ALARM not found. ACPI needed!!!"
	    echo "ABORT_MESSAGE=\"ACPI not installed, shutdown aborted!\""
            exit 1
	fi
    fi
else
    $LOG "ACPIWakeup functionality is disabled"
fi
