#!/usr/bin/env bash
# Wake only on terminal states. Diagnostics go to the sidecar log.
set -euo pipefail
PID="${1:?pid}"
DIR="/www/wwwroot/dataset/github_clone/speed_test"
SUM="$DIR/reports/summary.json"
LOG="$DIR/logs/run.log"
WATCH_LOG="$DIR/logs/watch_${PID}.log"
STALL_S=900

note() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >>"$WATCH_LOG"; }

status_of() {
  python3 - <<'PY' 2>/dev/null || true
import json
from pathlib import Path
p = Path("/www/wwwroot/dataset/github_clone/speed_test/reports/summary.json")
if not p.exists():
    print("missing")
else:
    try:
        print(json.loads(p.read_text()).get("status") or "unknown")
    except Exception:
        print("unreadable")
PY
}

note "watching pid=$PID"
# Stale summary.json from a previous run must not count while this pid is alive.
while :; do
  alive=0
  kill -0 "$PID" 2>/dev/null && alive=1
  st="$(status_of)"
  if (( alive == 0 )); then
    sleep 2
    st="$(status_of)"
    if [[ "$st" == "complete" ]]; then
      echo "DONE: clone speed test complete"
      exit 0
    fi
    echo "FAILED: pid $PID exited without complete summary (status=$st)"
    exit 1
  fi
  # pid still running: ignore leftover complete/failed from an older run
  if [[ "$st" == "failed" ]]; then
    note "status=failed but pid $PID still alive; treating as stale"
  fi
  if [[ -f "$LOG" ]]; then
    now=$(date +%s)
    mt=$(stat -c %Y "$LOG")
    idle=$((now - mt))
    if (( idle > STALL_S )); then
      echo "FAILED: run.log idle ${idle}s (stall) pid=$PID still alive"
      exit 1
    fi
  fi
  sleep 30
done
