#!/bin/bash
# /etc/rc.d/kernelconfirm — the "this kernel booted" marker for apkg kernel
# packages (#112).
#
# `apkg install kernel` adds a limine entry and deliberately does NOT make it
# the default: Limine has no boot-once, and on a machine without remote power
# (the MacBook) a wedged default replays on every power cycle. The new kernel is
# booted once from the menu, and this script is what notices that it came up.
# `apkg kernel confirm` compares the RUNNING kernel's /proc/version (git hash +
# build number) with the identity recorded in each apkg entry and marks the
# match `state=booted` on the ESP; if the entry was armed with
# `apkg kernel promote --on-boot`, it also becomes the default.
#
# WHY IT WAITS. "Reached rc" is not yet "booted": a kernel can get here and fall
# over a minute later (a driver timer, the first network burst). The confirm
# runs after the system has stayed up for KERNELCONFIRM_DELAY seconds (default
# 90), in the background so it never delays the rest of startup.
#
# It writes NOTHING when the running kernel is not an apkg trial — the common
# case on every boot — and only reads the ESP to find that out.
case "$1" in
    start)
        APKG=$(command -v apkg 2>/dev/null)
        [ -n "$APKG" ] || { echo "rc: kernelconfirm: no apkg on PATH — not run"; exit 0; }
        mkdir -p /var/log 2>/dev/null
        (
            sleep "${KERNELCONFIRM_DELAY:-90}"
            {
                echo "kernelconfirm: $(date 2>/dev/null) uptime $(cut -d' ' -f1 /proc/uptime 2>/dev/null)s"
                "$APKG" kernel confirm
                echo "kernelconfirm: exit $?"
            } >> /var/log/kernelconfirm.log 2>&1
        ) &
        ;;
    stop)
        ;;
    *)
        echo "usage: $0 start|stop" >&2; exit 1 ;;
esac
exit 0
