#!/usr/bin/env bash
set -uo pipefail
# Takeover after the fc-orchestrator restart collision (2026-07-04 06:16Z):
# wait for the still-running fc-control-2 on the runner, sync it, write the
# DONE marker, then relaunch the long-extension orchestrator.

RUNNER_IP="172.31.44.229"
KEY="/home/ubuntu/.ssh/controller-worker-aws-20260702"
SSH="ssh -i $KEY -o ConnectTimeout=15 ubuntu@$RUNNER_IP"
ROOT="/srv/controller-data"
RESULTS="$ROOT/results/focuschain-ab"
LOGDIR="$ROOT/logs/focuschain-ab"
exec >>"$LOGDIR/orchestrator.log" 2>&1
log() { echo "[$(date -u +%FT%TZ)] [finalize] $*"; }

log "takeover: waiting for fc-control-2 on runner"
FAILS=0
while true; do
  STATE=$($SSH "systemctl is-active fc-control-2" 2>/dev/null </dev/null)
  if [[ "$STATE" == "active" ]]; then FAILS=0; sleep 120; continue; fi
  if [[ -z "$STATE" ]]; then
    FAILS=$((FAILS+1)); log "ssh poll failed ($FAILS)"; (( FAILS >= 5 )) && { log "giving up polling; proceeding to sync"; break; }
    sleep 60; continue
  fi
  log "fc-control-2 state: $STATE"; break
done

rsync -a -e "ssh -i $KEY" "ubuntu@$RUNNER_IP:$ROOT/results/focuschain-ab/control-2/" "$RESULTS/control-2/" </dev/null
rsync -a -e "ssh -i $KEY" "ubuntu@$RUNNER_IP:$ROOT/logs/focuschain-ab/control-2.log" "$LOGDIR/" </dev/null
N=$(find "$RESULTS/control-2" -name result.txt 2>/dev/null | wc -l)
echo "block=control-2 policy=keep_all finished_utc=$(date -u +%FT%TZ) results=$N/40" > "$RESULTS/DONE-control-2"
log "wrote DONE-control-2 ($N/40)"
log "takeover complete"
