#!/usr/bin/env bash
# DV-1 §6: inside the sandbox. The fence's proof first, then the model's OWN server from its own CLI on
# 127.0.0.1, then the runner (which waits for /health), then the server is stopped. A failed fence stops here.
#   usage (inside sandbox_deciders.sh): serve_and_run.sh <von-cpu|laya-cpu> <leg-name> <runner args...>
set -euo pipefail
ARM=$1; LEG=$2; shift 2
D=$(cd "$(dirname "$0")" && pwd)
R=$(dirname "$D")/receipts
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
python -B "$D/fence_probe.py" > "$R/fence-$ARM-$LEG-$STAMP.json"
python -B -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if d['fence_holds'] else 3)" \
  "$R/fence-$ARM-$LEG-$STAMP.json" || { echo "STOP: the fence does not hold"; exit 3; }
echo "FENCE holds ($R/fence-$ARM-$LEG-$STAMP.json)"
LOG="$R/serve-$ARM-$LEG-$STAMP.log"
# `exec` inside the subshell, so $! is the server's own PID (the runner reads its VmRSS and VmHWM)
# von-cpu-nochains (DV-4): the same server with the vendor's own switch for its chain-of-options engine
case "$ARM" in
  von-cpu)  ( cd "$HOME" && exec von serve --host 127.0.0.1 --port 8031 --device cpu ) > "$LOG" 2>&1 & ;;
  von-cpu-nochains) ( cd "$HOME" && exec von serve --host 127.0.0.1 --port 8031 --device cpu --no-chains ) > "$LOG" 2>&1 & ;;
  laya-cpu) ( 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/run_deciders.py" --arm "$ARM" --server-pid "$SP" "$@"
kill "$SP" 2>/dev/null || true
wait "$SP" 2>/dev/null || true
echo "SERVER stopped; log $LOG"
