#!/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.
#

# take care of UTC setting
if [ -f /etc/default/rcS ]; then
    UTC=$(egrep "^[^#]*UTC=" /etc/default/rcS | tail -n1 | cut -d= -f2)
fi

if [ "$UTC" = "yes" ]; then
    TIME_FUNCTION="gmtime"
else
    TIME_FUNCTION="localtime"
fi

export WAKEALARM="/sys/class/rtc/rtc0/wakealarm"

TIMER=$1

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

AcpiError()
{
    $LOG "No writeable $ACPI_ALARM or $WAKEALARM found. ACPI needed!!!"
    echo "ABORT_MESSAGE=\"ACPI not installed, shutdown aborted!\""
    exit 1
}


ResetWakeupTimeKernel()
{
    if [ -w $WAKEALARM ]; then
        $LOG "Writing to $WAKEALARM"
        echo 0 >$WAKEALARM
        return $?
    else
        return 1
    fi
}

SetWakeupTimeKernel()
{
    if [ -w $WAKEALARM ]; then
        if ResetWakeupTimeKernel; then
            $LOG "Writing to $WAKEALARM"
            echo "$1" >$WAKEALARM
            return $?
        fi
    fi
    return 1
}


ResetWakeupTime()
{
    $LOG "Resetting ACPI alarm time"
    ResetWakeupTimeKernel || \
    AcpiError
}

SetWakeupTime()
{
    $LOG "Setting ACPI alarm time to: `TimeToString $1`"
    SetWakeupTimeKernel "$1" || \
    AcpiError

    # remember wakeup time for stop script
    echo `TimeToString $1` >$WAKEUP_FILE
}


if [ $TIMER -eq 0 ]; then
    ResetWakeupTime
else
    SetWakeupTime "$TIMER"
fi
