#!/bin/bash
# /etc/rc.d/apkgrecover — finish or roll back a package install that a power
# cut or a crash interrupted (#112).
#
# apkg writes a journal entry (State/lib/apkg/journal/<name>) and syncs it
# before it changes anything on disk, and removes it after the last step.
# `apkg recover` reads what is left: a version tree that is complete on disk
# is activated, one that is not is reinstalled from its archive, and failing
# both the previous version is put back. Every step is idempotent, so a cut
# during recovery is recovered by the next boot the same way.
#
# It runs in the FOREGROUND and first: the name sorts before every other rc.d
# script, and the rest of startup — including the desktop, which comes from
# `coresystem` — should see a finished install, not a half-linked one. With
# nothing pending it reads one empty directory and exits.
case "$1" in
    start)
        APKG=$(command -v apkg 2>/dev/null)
        [ -n "$APKG" ] || { echo "rc: apkgrecover: no apkg on PATH — not run"; exit 0; }
        [ -d /State/lib/apkg/journal ] || exit 0
        ls /State/lib/apkg/journal 2>/dev/null | grep -q . || exit 0
        mkdir -p /var/log 2>/dev/null
        {
            echo "apkgrecover: $(date 2>/dev/null) uptime $(cut -d' ' -f1 /proc/uptime 2>/dev/null)s"
            "$APKG" recover
            echo "apkgrecover: exit $?"
        } 2>&1 | tee -a /var/log/apkgrecover.log
        ;;
    stop)
        ;;
    *)
        echo "usage: $0 start|stop" >&2; exit 1 ;;
esac
exit 0
