#!/usr/bin/bash
# vdr-set-wakeup - set the RTC alarm for VDR's next timer or plugin wakeup.
# Runs as root: as ExecStop of vdr.service, and through sudo from
# vdr-shutdown.sh before a suspend or hibernation.
#
# The time comes from vdr-shutdown.sh in /run/vdr/next-timer, or from
# SVDRP if VDR is stopped some other way (systemctl, reboot).  The box wakes
# up WAKEUP_BEFORE_RECORDING minutes (/etc/sysconfig/vdr) before it.
# Without a next event the alarm is cleared; if VDR cannot be asked, the
# alarm stays as it is.  Under systemd the output goes to the journal (the
# unit's stdout may be a VT: StandardInput=tty), when run by hand to the
# terminal.

shopt -s extglob

[[ -r /etc/sysconfig/vdr ]] && . /etc/sysconfig/vdr
[[ $INVOCATION_ID ]] && exec > >(logger -t "${0##*/}") 2>&1

handoff=/run/vdr/next-timer
now=$(date +%s)
next=

if [[ -r $handoff ]] ; then
    next=$(< "$handoff")
    rm -f "$handoff"
fi

if [[ $next != +([0-9]) ]] ; then
    reply=$(svdrpsend NEXT abs 2>/dev/null)
    if [[ $reply =~ (^|$'\n')250\ +[0-9]+\ +([0-9]+) ]] ; then
        next=${BASH_REMATCH[2]}
        # A timer that is recording right now started in the past.  Like
        # VDR's own forced shutdown, come back after MinEventTimeout.
        if (( next <= now )) ; then
            mins=$(sed -nEe 's/^MinEventTimeout *= *([0-9]+).*/\1/p' /etc/vdr/setup.conf 2>/dev/null)
            next=$(( now + ${mins:-30} * 60 ))
        fi
    elif [[ $reply =~ (^|$'\n')550\  ]] ; then
        next=0
    else
        echo "VDR does not answer on SVDRP, RTC alarm unchanged"
        exit 0
    fi
fi

if (( next == 0 )) ; then
    echo "no timer or plugin wakeup, clearing the RTC alarm"
    exec /usr/bin/rtcwake -m disable >/dev/null
fi

when=$(( next - ${WAKEUP_BEFORE_RECORDING:-10} * 60 ))
# rtcwake refuses the past, and the machine has to be off before the alarm
(( when < now + 120 )) && when=$(( now + 120 ))
echo "next event $(date -d "@$next" '+%F %R'), RTC alarm $(date -d "@$when" '+%F %R')"
exec /usr/bin/rtcwake -m no -t "$when" >/dev/null
