#!/usr/bin/env bash
set -uo pipefail
RUNNER_IP="172.31.42.154"
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-v2"
LOGDIR="$ROOT/logs/focuschain-v2"
mkdir -p "$RESULTS" "$LOGDIR"
exec >>"$LOGDIR/orchestrator.log" 2>&1
log() { echo "[$(date -u +%FT%TZ)] $*"; }
for BLOCK in v2-1 v2-2; do
  [[ -f "$RESULTS/DONE-$BLOCK" ]] && { log "$BLOCK done, skip"; continue; }
  log "=== starting $BLOCK (focus_chain_v2) ==="
  $SSH "sudo systemd-run --unit=fcv2-$BLOCK --collect --property=User=ubuntu \
    --property=WorkingDirectory=/srv/controller-data \
    --setenv=POLICY=focus_chain_v2 --setenv=BLOCK=$BLOCK --setenv=NUM_ENVS=12 \
    --setenv=EXPERIMENT=focuschain-v2 --setenv=TEST_META_PATH=/srv/controller-data/pack.json \
    /srv/controller-data/run_block.sh" || { log "FAILED to start $BLOCK"; break; }
  START=$(date -u +%s)
  while true; do
    sleep 120
    STATE=$($SSH "systemctl is-active fcv2-$BLOCK" 2>/dev/null </dev/null)
    [[ "$STATE" != "active" ]] && { log "$BLOCK state: $STATE"; break; }
    (( $(date -u +%s) - START > 14400 )) && { log "$BLOCK 4h cap, stopping"; $SSH "sudo systemctl stop fcv2-$BLOCK" </dev/null; break; }
  done
  rsync -a -e "ssh -i $KEY" "ubuntu@$RUNNER_IP:$ROOT/results/focuschain-v2/$BLOCK/" "$RESULTS/$BLOCK/" </dev/null
  rsync -a -e "ssh -i $KEY" "ubuntu@$RUNNER_IP:$ROOT/logs/focuschain-v2/$BLOCK.log" "$LOGDIR/" </dev/null
  N=$(find "$RESULTS/$BLOCK" -name result.txt 2>/dev/null | wc -l)
  echo "block=$BLOCK policy=focus_chain_v2 finished_utc=$(date -u +%FT%TZ) results=$N/40" > "$RESULTS/DONE-$BLOCK"
  log "DONE-$BLOCK ($N/40)"
done
log "v2 orchestrator finished"
