#!/usr/bin/env bash
# End-to-end operator workflow:
#  1. reset server back into Hetzner rescue
#  2. probe hardware/network facts
#  3. create an N-disk RAID0 rootfs staged at /mnt
#  4. kexec into the canonical builder rootfs
#  5. register the rebuilt host locally
#  6. run a fresh remote-build proof through builder@host using ssh-ng

set -euo pipefail

REPO_ROOT="$(git rev-parse --show-toplevel)"
source "$REPO_ROOT/tools/lib/builder-common.sh"
cd "$TOTALLY_SPIES_REPO_ROOT"

STATE_FILE="${STATE_FILE:-$TOTALLY_SPIES_BUILDER_HOST_STATE_FILE}"
SSH_KEY="${SSH_KEY:-$HOME/.ssh/id_ed25519}"
NIX_BIN="${NIX_BIN:-nix}"

builder_require_file "$SSH_KEY"

build_tool() {
  local attr="$1"
  "$NIX_BIN" build -f nix/tools.nix "$attr" --no-link --print-out-paths
}

run_tool() {
  local attr="$1"
  local bin="$2"
  shift 2
  local out
  out="$(build_tool "$attr")"
  "$out/bin/$bin" "$@"
}

current_host() {
  builder_current_host
}

fresh_remote_proof() {
  local out proof_path
  out="$(build_tool remoteProofFresh)"
  proof_path="$($out/bin/spies-builder-remote-proof-fresh -L)"
  echo "Fresh remote proof path: $proof_path"
  echo "Fresh remote proof contents:"
  cat "$proof_path"
}

host_before="$(current_host)"
echo "=== Revalidate builder from rescue ==="
echo "Initial host: ${host_before:-<unset>}"

echo "[1/6] Resetting back into rescue"
run_tool hetznerMarket spies-hetzner-market rescue --execute --power-cycle

host_after_reset="$(current_host)"
if [ -z "$host_after_reset" ]; then
  host_after_reset="$host_before"
fi
if [ -z "$host_after_reset" ]; then
  echo "Could not determine server host from state after rescue reset" >&2
  exit 1
fi

echo "Waiting for rescue SSH on $host_after_reset"
builder_wait_for_ssh "$host_after_reset" root 40 5

echo "[2/6] Probing rescue host"
run_tool rescueProbe spies-builder-rescue-probe

echo "[3/6] Preparing RAID0 rootfs"
run_tool rescueStripePrepare spies-builder-rescue-stripe-prepare

echo "[4/6] Kexec into builder rootfs"
run_tool builderKexec spies-builder-kexec --execute

echo "[5/6] Registering rebuilt builder"
run_tool hetznerMarket spies-hetzner-market register

echo "[6/6] Running fresh remote-build proof"
fresh_remote_proof

echo "Revalidation complete."
