#!/usr/bin/env bash
# DV-5, inside the sandbox: serve_and_run.sh's form (DV-1 §6, the DV-3 PID fix kept). The fence's proof first
# (a failed fence stops here), then the card's reading before any server (GPU arms), then the model's OWN server
# from its own CLI on 127.0.0.1, then the speed runner (which waits for /health), then the server is stopped.
#   usage (inside sandbox_speed.sh): serve_speed.sh <arm> <dry|timed>
set -euo pipefail
ARM=$1; MODE=$2; shift 2
D=$(cd "$(dirname "$0")" && pwd)                 # instrument/speed
I=$(dirname "$D")                                # instrument
R=$DV_DIR/receipts-speed
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
FENCE="$R/fence-$ARM-$MODE-$STAMP.json"
python -B "$I/fence_probe.py" > "$FENCE"
python -B -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if d['fence_holds'] else 3)" "$FENCE" \
  || { echo "STOP: the fence does not hold ($FENCE)"; exit 3; }
echo "FENCE holds ($(basename "$FENCE"))"
CB="$R/card-before-$ARM-$MODE-$STAMP.json"
python -B "$D/speed_deciders.py" --arm "$ARM" --card-before-only > "$CB"
LOG="$R/serve-$ARM-$MODE-$STAMP.log"
# `exec` inside the subshell, so $! is the server's own PID (the runner reads its VmRSS and VmHWM)
case "$ARM" in
  speed-von-cpu)  ( cd "$HOME" && exec von serve --host 127.0.0.1 --port 8031 --device cpu ) > "$LOG" 2>&1 & ;;
  speed-von-gpu)  ( cd "$HOME" && exec von serve --host 127.0.0.1 --port 8031 --device cuda ) > "$LOG" 2>&1 & ;;
  speed-laya-cpu|speed-laya-gpu) ( cd "$HOME" && LAYA_HOST=127.0.0.1 LAYA_PORT=8032 exec laya-serve ) > "$LOG" 2>&1 & ;;
  *) echo "STOP: unknown arm $ARM"; exit 2 ;;
esac
SP=$!
trap 'kill $SP 2>/dev/null || true' EXIT
python -B "$D/speed_deciders.py" --arm "$ARM" --mode "$MODE" --server-pid "$SP" --card-before "$CB" \
  --stamp "$STAMP" --server-log "$LOG" "$@"
kill "$SP" 2>/dev/null || true
wait "$SP" 2>/dev/null || true
echo "SERVER stopped; log $(basename "$LOG")"
