#!/bin/sh
# Guarded reboot for a host that runs vq daemons (#272).
#
# Run as root by vq-planned-reboot.service (see vq-planned-reboot.timer).
# Reboots only when the OS asks for it (/run/reboot-required) and every
# configured vq daemon reports `safe to reboot` after
# `vq host prepare-reboot --apply`. Otherwise it cancels the plans it made
# with `vq host finish-reboot`, logs why, and exits non-zero, so the timer's
# next run tries again. After the boot each daemon resubmits its marked jobs
# and lifts its own hold (docs/operations.md, #249).
#
# /etc/vq-planned-reboot.conf lists one daemon per line:
#   USER  VQ-EXECUTABLE  HOST|-  ENV-FILE|-
# ENV-FILE holds KEY=VALUE lines (VQ_CONFIG_DIR, VQ_STATE_DIR, ...) for that
# daemon. Use HOST `localhost` for a daemon on this host: a configured host
# name whose ssh is localhost is still reached over SSH. HOST "-" uses the
# config's default host. The daemon's vq must have `vq host prepare-reboot`
# (#249). Example:
#   USER  /home/USER/.config/vq-lane-g1/vq  localhost  -
#   USER  /home/USER/releases/CURRENT/env/bin/vq  localhost  /etc/vq-planned-reboot.d/lane-g1.env
#
# Options:
#   --dry-run       prepare-reboot preview only; never applies or reboots.
#   --prepare-only  apply and check every daemon, but leave the reboot to the
#                   caller (another update tool). Exit 0 means safe to reboot.
#   --force         do not require /run/reboot-required.
#   --reboot-now    allow the reboot when not started by systemd. A manual or
#                   test run never reboots without it (exit 3 instead).
# The timer path stands down (exit 0) while another update tool runs: its lock
# is held or one of its units is active (default: full-update).
# VQ_PLANNED_REBOOT_COMMAND replaces the final `systemctl reboot`, for testing.
set -u

CONF=${VQ_PLANNED_REBOOT_CONF:-/etc/vq-planned-reboot.conf}
REASON=${VQ_PLANNED_REBOOT_REASON:-"scheduled reboot for pending system updates"}
DRY=0
FORCE=0
PREPARE_ONLY=0
REBOOT_NOW=0
for arg in "$@"; do
    case "$arg" in
        --dry-run) DRY=1 ;;
        --force) FORCE=1 ;;
        --prepare-only) PREPARE_ONLY=1 ;;
        --reboot-now) REBOOT_NOW=1 ;;
        *) echo "vq-planned-reboot: unknown option $arg" >&2; exit 2 ;;
    esac
done

log() { echo "vq-planned-reboot: $*"; }

# Another update tool that reboots the host must not be interrupted. Only look
# at its lock (lslocks); never take it, because such a tool may refuse to start
# while its lock is held. VQ_PLANNED_REBOOT_DEFER_LOCKS (space-separated paths)
# and VQ_PLANNED_REBOOT_DEFER_UNITS (systemctl patterns) name what to wait for.
DEFER_LOCKS=${VQ_PLANNED_REBOOT_DEFER_LOCKS-/run/full-update.lock}
DEFER_UNITS=${VQ_PLANNED_REBOOT_DEFER_UNITS-full-update*.service}
if [ "$PREPARE_ONLY" -eq 0 ] && [ "$DRY" -eq 0 ]; then
    for lock in $DEFER_LOCKS; do
        if lslocks -n -o PATH 2>/dev/null | grep -qxF "$lock"; then
            echo "vq-planned-reboot: $lock is held; another update is running, standing down"
            exit 0
        fi
    done
    for pattern in $DEFER_UNITS; do
        if [ -n "$(systemctl list-units --state=activating,active,reloading --no-legend --plain "$pattern" 2>/dev/null)" ]; then
            echo "vq-planned-reboot: $pattern is running; standing down"
            exit 0
        fi
    done
fi

if [ "$FORCE" -eq 0 ] && [ ! -e /run/reboot-required ]; then
    log "no reboot required"
    exit 0
fi
[ -r "$CONF" ] || { log "cannot read $CONF"; exit 1; }

# run_vq USER EXE ENVFILE ARGS... -- runs vq as USER in a clean login-like
# environment (runuser keeps root's HOME otherwise) plus the daemon's settings.
run_vq() {
    user=$1; exe=$2; envfile=$3; shift 3
    home=$(getent passwd "$user" | cut -d: -f6)
    extra=""
    if [ "$envfile" != "-" ]; then
        # KEY=VALUE words without spaces, by contract.
        extra=$(grep -E '^[A-Z_][A-Z0-9_]*=[^ ]*$' "$envfile")
    fi
    # shellcheck disable=SC2086
    runuser -u "$user" -- env -i -C "$home" HOME="$home" USER="$user" LOGNAME="$user" \
        PATH=/usr/local/bin:/usr/bin:/bin LANG=C.UTF-8 $extra "$exe" "$@"
}

verdict_of() {
    python3 -I -c 'import json,sys
try:
    print(json.load(sys.stdin).get("verdict", "unknown"))
except Exception:
    print("unreadable")'
}

applied=""
safe=1
mode="--apply"
[ "$DRY" -eq 1 ] && mode=""
while read -r user exe host envfile rest; do
    case "$user" in ''|'#'*) continue ;; esac
    [ "$host" = "-" ] && host=""
    # $host and $mode are empty or one word.
    # shellcheck disable=SC2086
    verdict=$(run_vq "$user" "$exe" "$envfile" host prepare-reboot $host \
        --reason "$REASON" $mode --json </dev/null | verdict_of)
    log "${user} ${host:-default}: $verdict"
    [ "$DRY" -eq 0 ] && applied="$applied
$user $exe ${host:--} $envfile"
    case "$verdict" in
        "safe to reboot") ;;
        "ready to apply") [ "$DRY" -eq 1 ] || safe=0 ;;
        *) safe=0 ;;
    esac
done < "$CONF"

if [ "$DRY" -eq 1 ]; then
    log "dry run; not rebooting"
    [ "$safe" -eq 1 ]
    exit $?
fi

if [ "$safe" -ne 1 ]; then
    log "not every daemon is safe to reboot; cancelling the plans"
    echo "$applied" | while read -r user exe host envfile; do
        [ -n "$user" ] || continue
        [ "$host" = "-" ] && host=""
        # shellcheck disable=SC2086
        if run_vq "$user" "$exe" "$envfile" host finish-reboot $host </dev/null >/dev/null 2>&1; then
            log "cancelled ${user} ${host:-default}"
        else
            log "could not cancel ${user} ${host:-default}; run vq host finish-reboot by hand"
        fi
    done
    exit 1
fi

if [ "$PREPARE_ONLY" -eq 1 ]; then
    log "every daemon is safe to reboot; leaving the reboot to the caller"
    exit 0
fi
# Outside its systemd service (no INVOCATION_ID), rebooting needs --reboot-now,
# so a manual or test run whose overrides were lost cannot reboot the host.
if [ -z "${INVOCATION_ID:-}" ] && [ "$REBOOT_NOW" -eq 0 ] \
        && [ -z "${VQ_PLANNED_REBOOT_COMMAND:-}" ]; then
    log "every daemon is safe to reboot, but not started by systemd; pass --reboot-now to reboot"
    exit 3
fi
log "every daemon is safe to reboot; rebooting"
# shellcheck disable=SC2086
exec ${VQ_PLANNED_REBOOT_COMMAND:-systemctl reboot}
