#!/usr/bin/env bash
# Real-app check for PR #41063: a local, isolated Simlock worker on a given version, for T3's Device panel.
# Usage: bash make-simlock-pool.sh <simlock version> <agent-device version> <port>
#   before: bash make-simlock-pool.sh 0.8.0 0.21.36 4780   (with T3 at a4d748f5b9, the commit before #37363)
#   after:  bash make-simlock-pool.sh 0.9.0 0.21.41 4791   (with T3 at main)
# Needs macOS with Xcode and an iOS simulator runtime. Simlock keeps its simulators in its own device set
# under the scratch folder, so Xcode's default set is untouched. It runs in the foreground; Ctrl-C stops it.
# Then start T3 with `DEVELOPER_DIR=<empty dir> HOME=$(mktemp -d) T3CODE_DEV_SEED=0 vp run dev` (the empty
# DEVELOPER_DIR keeps this Mac's own simulators out of the Device panel), turn on Settings > Labs > Simlock
# device hosts and Settings > Devices > Use devices, add a Simlock pool with http://127.0.0.1:<port> and the
# printed agent token, and press Start on a device in a thread's Device panel.
set -euo pipefail
SIMLOCK=$1 AGENT_DEVICE=$2 PORT=$3
# Simlock's daemon only starts when its entry path is the real path (/tmp is a symlink on macOS).
ROOT=$(cd "$(mktemp -d)" && pwd -P)
mkdir -p "$ROOT/pkg" "$ROOT/home" "$ROOT/simlock"
(cd "$ROOT/pkg" && echo '{"private":true}' >package.json &&
  npm i -s --ignore-scripts --no-audit --no-fund "simlock@$SIMLOCK" "agent-device@$AGENT_DEVICE")
export HOME="$ROOT/home" SIMLOCK_HOME="$ROOT/simlock" PATH="$ROOT/pkg/node_modules/.bin:$PATH"
unset AGENT_DEVICE_DAEMON_BASE_URL AGENT_DEVICE_DAEMON_AUTH_TOKEN
simlock --local config set http.port "$PORT" >/dev/null
simlock --local config set capabilities.stream.enabled true >/dev/null
simlock --local config set capabilities.input.enabled true >/dev/null
simlock --local config set warmPool.enabled false >/dev/null
node "$ROOT/pkg/node_modules/simlock/dist/daemon/main.js" &
DAEMON=$!
trap 'simlock nuke --delete-devices --platform ios --yes >/dev/null 2>&1 || true; kill "$DAEMON" 2>/dev/null || true; wait "$DAEMON" 2>/dev/null || true; rm -rf "$ROOT"' EXIT
trap 'exit 130' INT TERM
until curl -fs "http://127.0.0.1:$PORT/v1/healthz" >/dev/null; do sleep 1; done
TOKEN=$(simlock token create --role agent --label t3 | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log(JSON.parse(s).secret))')
HEALTH=$(curl -fs "http://127.0.0.1:$PORT/v1/agent-device/health" -H "Authorization: Bearer $TOKEN")
echo "Simlock $SIMLOCK on http://127.0.0.1:$PORT, worker agent-device $(agent-device --version)"
echo "agent-device front: $HEALTH"
echo "agent token: $TOKEN"
wait "$DAEMON"
