#!/usr/bin/env bash
# Exact runner revival only. Any unexpected state exits non-zero for escalation.
# Runner units live ON THE BUILDBOXES: the GH runner name encodes its box
# (…-debianN[-M]), and every action here goes over the operator ssh door (2222).
set -euo pipefail
signature=${1:?signature required}
if [[ "$signature" =~ ^gh-runner:([A-Za-z0-9][A-Za-z0-9._-]*):offline$ ]]; then name=${BASH_REMATCH[1]}; else echo "invalid runner signature: $signature" >&2; exit 2; fi
[[ "$name" =~ (debian[0-9]+) ]] || { echo "runner name $name does not encode a buildbox; not scriptable from here" >&2; exit 1; }
box=${BASH_REMATCH[1]}
repo=${OVERDECK_FIRE_RUNNER_REPO:-alexcodeplace/multideal}
run_box() { ssh -o ConnectTimeout=10 -o BatchMode=yes -p 2222 "$box" "$1"; }

# The unit is discovered, never guessed: user units whose definition names an
# actions-runner directory. Multiple or zero matches = escalate.
unit=$(run_box 'for u in $(systemctl --user list-unit-files --type=service --no-legend --plain | cut -d" " -f1); do
  systemctl --user show "$u" -p FragmentPath -p ExecStart 2>/dev/null | grep -q "actions-runner" || continue
  systemctl --user show "$u" -p ExecStart 2>/dev/null | grep -q "'"$name"'\|actions-runner-'"${name%-*}"'" && echo "$u"
done' | sort -u)
[[ -n "$unit" && $(wc -l <<<"$unit") -eq 1 ]] || { printf 'cannot identify exactly one unit for %s on %s (got: %s)\n' "$name" "$box" "${unit:-none}" >&2; exit 1; }
run_box "systemctl --user start $unit" || { echo "cannot start $unit on $box" >&2; exit 1; }
run_box 'pgrep -c -f Runner.Listener >/dev/null' || { echo "no live Runner.Listener on $box after start" >&2; exit 1; }
status=$(gh api "/repos/$repo/actions/runners" --jq ".runners[] | select(.name == \"$name\") | .status" 2>/dev/null || true)
[[ "$status" == "online" ]] || { echo "GitHub does not report runner $name online" >&2; exit 1; }
printf '{"outcome":"shipped","detail":"Started %s on %s; Runner.Listener live and GitHub reports %s online.","proof":"ssh %s systemctl --user start %s; pgrep Runner.Listener; gh api runners=%s"}\n' "$unit" "$box" "$name" "$box" "$unit" "$status"
