#!/bin/sh
#
# rtc-offset load|save -- keep the wall clock across reboots on a PMIC RTC
# that Linux cannot set.  The RTC of the Qualcomm PMIC (rtc-pm8xxx, rtc0)
# counts on, but is read-only without the driver's allow-set-time, and
# Android keeps the difference to the real time elsewhere; Linux therefore
# starts in 1970.  This keeps that difference in a file:
#
#   save  writes (system time - RTC) to OFFSET, if the system time is set
#         (after 2026-01-01; the RTC alone reads 1970)
#   load  sets the system time to RTC + OFFSET
#
# The first correct time comes from outside (date -s, then save; the host
# does it with tools/phone-time.sh).  Stage 1 loads
# (core-services/04-rtc-offset.sh), stage 3 saves (shutdown.d/45-rtc-offset.sh).

OFFSET=/var/lib/makronix/rtc-offset
RTC=/sys/class/rtc/rtc0/since_epoch
SET_AFTER=1767225600	# 2026-01-01 00:00:00 UTC

[ -r "$RTC" ] || { echo "rtc-offset: no $RTC" >&2; exit 1; }
rtc=$(cat "$RTC") || exit 1

case ${1:-} in
save)
	now=$(date +%s)
	[ "$now" -gt "$SET_AFTER" ] ||
		{ echo "rtc-offset: system time not set, nothing saved" >&2; exit 1; }
	mkdir -p "${OFFSET%/*}" &&
	echo $((now - rtc)) > "$OFFSET.new" && mv "$OFFSET.new" "$OFFSET"
	;;
load)
	[ -s "$OFFSET" ] || { echo "rtc-offset: no $OFFSET" >&2; exit 1; }
	off=$(cat "$OFFSET")
	case $off in ''|*[!0-9-]*) echo "rtc-offset: bad $OFFSET" >&2; exit 1 ;; esac
	date -u -s "@$((rtc + off))" >/dev/null
	;;
*)
	echo "usage: rtc-offset load|save" >&2
	exit 2
	;;
esac
