#!/bin/sh
# SPDX-License-Identifier: MIT

# OpenATV's rc passes "stop" to S scripts in runlevel 0.
[ "$1" = stop ] && [ -e /etc/enigma2/.deep ] || exit 0
settings=/etc/enigma2/settings
rtc=/sys/class/rtc/rtc0
[ -r "$settings" ] && [ -w "$rtc/wakealarm" ] || exit 0

# Enigma2 saves the shutdown and wake times in Unix seconds. The SM1 RTC
# can use a different epoch, so pass the remaining time to the kernel.
delay=$(awk -F '[=,]' -v now="$(date +%s)" '
	$1 == "config.misc.nextWakeup" {
		if ($2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/ && $2 <= now &&
		    $3 > now && $3 - now <= 4294967295)
			printf "%.0f", $3 - now
		exit
	}' "$settings") || exit 1
[ -n "$delay" ] || exit 0

# Keep an earlier alarm set by another application. Linux requires
# clearing an active alarm before it accepts an earlier one.
previous=$(cat "$rtc/wakealarm") || exit 1
if [ -n "$previous" ]; then
	rtc_now=$(cat "$rtc/since_epoch") || exit 1
	if [ "$previous" -gt "$rtc_now" ] && [ "$previous" -le "$((rtc_now + delay))" ]; then
		exit 0
	fi
	echo 0 > "$rtc/wakealarm" || exit 1
fi
if ! echo "+$delay" > "$rtc/wakealarm"; then
	[ -z "$previous" ] || echo "$previous" > "$rtc/wakealarm"
	exit 1
fi
