#!/usr/bin/env bash
# Build the harness seat image ON the buildboxes. Never builds locally — the laptop is not an
# execution host for agent workloads.
#
#   modules/harness/seat/build-image.sh [host ...]     (default: the registry build order)
#
# Idempotent: skips a host that already has the tag unless --force.
set -euo pipefail

SEAT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
IMAGE="$(node -e 'process.stdout.write(require(process.argv[1]).image)' "$SEAT_DIR/seat-remote.json")"
REGISTRY="$SEAT_DIR/../../workstation/claude/lib/buildbox-registry.mjs"
reg() { CPU_GUARD_ACTIVE=1 node "$REGISTRY" "$@"; }

FORCE=0
HOSTS=()
for arg in "$@"; do
  case "$arg" in
    --force) FORCE=1;;
    *) HOSTS+=("$arg");;
  esac
done
if [[ ${#HOSTS[@]} -gt 0 ]]; then
  if ! hosts_csv="$(reg check "$(IFS=,; echo "${HOSTS[*]}")")"; then
    echo "build-image: buildbox registry unusable — refusing to contact any host" >&2
    exit 2
  fi
else
  if ! hosts_csv="$(reg hosts --order build)"; then
    echo "build-image: buildbox registry unusable — refusing to contact any host" >&2
    exit 2
  fi
fi
IFS=',' read -r -a HOSTS <<<"$hosts_csv"
[[ ${#HOSTS[@]} -gt 0 ]] || { echo "build-image: no usable buildbox host in the registry" >&2; exit 2; }

for host in "${HOSTS[@]}"; do
  echo "=== $host: $IMAGE"
  if ! access="$(reg access "$host" --path tailscale_ip)"; then
    echo "build-image: no tailscale_ip access for $host" >&2
    exit 2
  fi
  read -r target port ident <<<"$access"
  [[ $ident == - ]] && ident=""
  SSH=(ssh -F /dev/null ${ident:+-i "${ident/#\~/$HOME}"} -p "$port")
  if [[ $FORCE -eq 0 ]] && "${SSH[@]}" "$target" "podman image exists $IMAGE" 2>/dev/null; then
    echo "--- present, skipping (use --force to rebuild)"
    continue
  fi
  "${SSH[@]}" "$target" 'rm -rf ~/.harness-seat-build && mkdir -p ~/.harness-seat-build'
  tar -C "$SEAT_DIR" -czf - Containerfile seat-entrypoint.sh \
    | "${SSH[@]}" "$target" 'tar -C ~/.harness-seat-build -xzf -'
  "${SSH[@]}" "$target" "cd ~/.harness-seat-build && podman build --pull=newer -t $IMAGE -f Containerfile ."
  "${SSH[@]}" "$target" "rm -rf ~/.harness-seat-build && podman image inspect $IMAGE --format '{{.Id}} {{.Size}}'"
done
