#!/usr/bin/env bash
# usage: tools/gpu/lighter_compare.sh <spec.json> <local_out> <glb>...   (spec files are the GLB basenames, original first)
# Stages the library studio (browse/compare.html, stage.mjs, garage/, vendor/: cached between runs) + the GLBs on gex44,
# serves them on 127.0.0.1, runs compare_probe.py on the GPU, copies the result back. Stops ONLY the server it started.
set -euo pipefail
ROOT=$(cd "$(dirname "$0")/../.." && pwd); SPEC=$(readlink -f "$1"); OUT=$2; shift 2
HOST=root@5.9.10.114; SITE=/tmp/fal-gpu/lighter-site; RUN=$SITE/run-$(date +%s%N); PORT=${FAL_LIGHTER_PORT:-8964}
mkdir -p "$OUT"
ssh "$HOST" "mkdir -p $RUN/out"
rsync -a "$ROOT/browse/compare.html" "$ROOT/browse/stage.mjs" "$ROOT/browse/garage" "$ROOT/browse/vendor" "$HOST:$SITE/"
rsync -a "$@" "$HOST:$RUN/"
python3 - "$SPEC" "$(basename "$RUN")" > "$OUT/.spec.json" <<'PY'
import json, sys
s = json.load(open(sys.argv[1])); s['files'] = [f'{sys.argv[2]}/{f}' for f in s['files']]; print(json.dumps(s))
PY
scp -q "$ROOT/tools/gpu/compare_probe.py" "$OUT/.spec.json" "$HOST:$RUN/"
ssh "$HOST" "cd $SITE && (python3 -m http.server $PORT --bind 127.0.0.1 >/dev/null 2>&1 & echo \$! > $RUN/server.pid) && sleep 1 &&
  python3 $RUN/compare_probe.py http://127.0.0.1:$PORT/ $RUN/out $RUN/.spec.json; rc=\$?; kill \$(cat $RUN/server.pid) 2>/dev/null; exit \$rc"
rsync -a "$HOST:$RUN/out/" "$OUT/"
ssh "$HOST" "find $RUN -delete"
rm -f "$OUT/.spec.json"
