#!/usr/bin/env bash
# Wait for an edge package that actually contains the subconscious fixes,
# upgrade to it, then restart the server.
#
# A bare restart would have been wrong: r477 (aa6cd4e) predates 877cad0 and
# 837e024, so restarting on it picks up config only and leaves her rescue on
# the shelf. This waits for a package whose git hash is a DESCENDANT of NEED.
#
# Disarm: systemctl --user stop sv-upgrade-restart.service

set -uo pipefail

REPO=/home/casey/Projects/souveraine
NEED=${NEED:-837e024}
LOG=${LOG:-/tmp/sv-upgrade-restart.log}
DEADLINE_MIN=${DEADLINE_MIN:-60}
POLL_SEC=${POLL_SEC:-60}

exec >>"$LOG" 2>&1

say() { echo "$(date -Is) $*"; }

pkg_hash() {
    # "0.1.r477.gaa6cd4e219bf-1" -> "aa6cd4e219bf"
    local ver=$1 h
    h=${ver##*.g}
    h=${h%%-*}
    printf '%s' "$h"
}

say "=== armed; waiting for a package containing $NEED ==="
say "installed now: $(pacman -Q souveraine 2>/dev/null || echo none)"

end=$(( $(date +%s) + DEADLINE_MIN * 60 ))

while [ "$(date +%s)" -lt "$end" ]; do
    sudo -n pacman -Sy --noconfirm >/dev/null 2>&1

    ver=$(pacman -Si souveraine 2>/dev/null | awk -F': +' '/^Version/{print $2; exit}')
    if [ -z "${ver:-}" ]; then
        say "repo did not answer a version — retrying"
        sleep "$POLL_SEC"
        continue
    fi

    hash=$(pkg_hash "$ver")
    if [ -n "$hash" ] && git -C "$REPO" merge-base --is-ancestor "$NEED" "$hash" 2>/dev/null; then
        say "package $ver contains $NEED — upgrading"
        if sudo -n pacman -S --noconfirm souveraine; then
            say "upgraded to $(pacman -Q souveraine)"
            say "restarting souveraine.service"
            systemctl --user restart souveraine.service
            say "restart issued (rc=$?)"
            say "running: $(systemctl --user show souveraine.service -p MainPID --value)"
        else
            say "UPGRADE FAILED — not restarting; the old server keeps running"
            exit 1
        fi
        exit 0
    fi

    say "available $ver does not contain $NEED yet — waiting ${POLL_SEC}s"
    sleep "$POLL_SEC"
done

say "TIMED OUT after ${DEADLINE_MIN}m — no package containing $NEED. Nothing restarted."
exit 2
