#!/usr/bin/env bash
# PR #41063 (fix(devices): pin agent-device back to 0.21.36 for Simlock 0.8.0 pools)
# Claim: already-fixed. The PR was a stopgap "until a Simlock release accepts protocol 3". Simlock 0.9.0 is that
# release, and #37363 (6e2164ac88) made T3's devices guide require it. With 0.9.0, T3's 0.21.41 pin connects;
# the PR's 0.21.36 pin would be refused. This script runs the real agent-device client that each T3 commit pins
# against the real @agent-device/proxy that each Simlock release ships, fronting a stub worker daemon.
# Needs: a pingdotgg/t3code checkout (run from its root), node >= 22.12, npm with registry access, gh authenticated.
# No `vp i` and no checkout changes; everything is unpacked into a temporary directory that is removed on exit.
set -euo pipefail

TMP=""
PROXY_PID=""
cleanup() {
  if [ -n "$PROXY_PID" ]; then kill "$PROXY_PID" 2>/dev/null || true; fi
  if [ -n "$TMP" ]; then rm -rf "$TMP"; fi
}
trap 'rc=$?; cleanup; [ "${PROOF_DONE:-0}" = 1 ] && exit 0; [ "$rc" -ne 0 ] && exit "$rc"; exit 1' EXIT

REPO=pingdotgg/t3code
FIX=6e2164ac8855eeb5b171173a90c6d874788cbdb2 # #37363: devices guide requires Simlock 0.9.0 or later
ok=1
pass() { echo "PASS  $*"; }
fail() { echo "FAIL  $*"; ok=0; }

git fetch -q origin main
MAIN=$(git rev-parse FETCH_HEAD)
git fetch -q origin pull/41063/head
PR_HEAD=$(git rev-parse FETCH_HEAD)
git cat-file -e "$FIX^{commit}"
FIX_PARENT=$(git rev-parse "$FIX^")
echo "main=$MAIN pr_head=$PR_HEAD fix=$FIX fix_parent=$FIX_PARENT"

if git merge-base --is-ancestor "$FIX" "$MAIN"; then
  pass "#37363 ($FIX) is on main"
else
  fail "#37363 ($FIX) is not on main"
fi

# 1. What each commit tells users to run, and which agent-device client it pins.
GUIDE=docs/user/devices.md
PINS=apps/server/src/device/deviceToolVersions.json
if git show "$FIX:$GUIDE" | grep -q 'requires Simlock 0.9.0 or later'; then
  pass "at $FIX the devices guide requires Simlock 0.9.0 or later"
else
  fail "at $FIX the devices guide does not require Simlock 0.9.0"
fi
if git show "$FIX_PARENT:$GUIDE" | grep -q 'requires Simlock `main` at commit `6316e10`+'; then
  pass "at $FIX_PARENT the guide accepted any Simlock from commit 6316e10 on (which includes 0.8.0)"
else
  fail "at $FIX_PARENT the guide does not name the 6316e10 minimum"
fi
pin_at() { git show "$1:$PINS" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log(JSON.parse(s)["agent-device"]))'; }
PIN_FIX=$(pin_at "$FIX")
PIN_FIX_PARENT=$(pin_at "$FIX_PARENT")
PIN_PR=$(pin_at "$PR_HEAD")
echo "      agent-device pinned by T3: fix=$PIN_FIX fix_parent=$PIN_FIX_PARENT pr_head=$PIN_PR"
if [ "$PIN_PR" = "0.21.36" ] && [ "$PIN_FIX" != "0.21.36" ]; then
  pass "the PR pins agent-device $PIN_PR; #37363's tree pins $PIN_FIX"
else
  fail "unexpected pins: pr_head=$PIN_PR fix=$PIN_FIX"
fi

# 2. Unpack the published packages (no install scripts run; agent-device and the proxy have no dependencies).
TMP=$(mktemp -d)
PKGS="$TMP/pkgs"
HARNESS="$TMP/harness"
mkdir -p "$PKGS" "$HARNESS" "$TMP/home"
unpack() { # unpack <spec> <dir>
  mkdir -p "$PKGS/$2"
  (cd "$PKGS/$2" && npm pack -q --silent "$1" >/dev/null && tar xzf ./*.tgz)
}
simlock_proxy_version() {
  node -e 'console.log(require(process.argv[1]).dependencies["@agent-device/proxy"])' "$PKGS/simlock-$1/package/package.json"
}
simlock_worker_protocol() {
  sed -n 's/^export const AGENT_DEVICE_RPC_PROTOCOL_VERSION = \([0-9][0-9]*\);$/\1/p' \
    "$PKGS/simlock-$1/package/dist/agent-device/shared/compatibility.js"
}
for v in 0.8.0 0.9.0; do unpack "simlock@$v" "simlock-$v"; done
SL080_PROXY=$(simlock_proxy_version 0.8.0)
SL090_PROXY=$(simlock_proxy_version 0.9.0)
SL080_WORKER=$(simlock_worker_protocol 0.8.0)
SL090_WORKER=$(simlock_worker_protocol 0.9.0)
echo "      simlock 0.8.0 ships @agent-device/proxy $SL080_PROXY and requires worker daemons on RPC protocol $SL080_WORKER"
echo "      simlock 0.9.0 ships @agent-device/proxy $SL090_PROXY and requires worker daemons on RPC protocol $SL090_WORKER"
for p in "$SL080_PROXY" "$SL090_PROXY"; do
  [ -d "$PKGS/proxy-$p" ] || unpack "@agent-device/proxy@$p" "proxy-$p"
done
for c in "$PIN_FIX" "$PIN_FIX_PARENT" "$PIN_PR"; do
  [ -d "$PKGS/client-$c" ] || unpack "agent-device@$c" "client-$c"
done

# A Simlock-style remote: the real proxy in front of a stub worker daemon that answers /health with the
# protocol Simlock enforces on its workers, and records any RPC the proxy forwards.
cat >"$HARNESS/remote.mjs" <<'EOF'
import { pathToFileURL } from "node:url";
const [proxyIndex, workerProtocol] = process.argv.slice(2);
const { createDaemonProxyServer } = await import(pathToFileURL(proxyIndex).href);
const upstreamFetch = async (request) => {
  const route = new URL(request.url).pathname;
  if (route.endsWith("/health")) {
    return Response.json({ ok: true, service: "agent-device-daemon", version: "stub-worker", rpcProtocolVersion: Number(workerProtocol) });
  }
  process.stderr.write(`FORWARDED ${request.method} ${route}\n`);
  return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32000, message: "stub worker answers health only" } });
};
const server = createDaemonProxyServer({
  upstreamBaseUrl: "http://127.0.0.1:9",
  upstreamToken: "proof-upstream",
  clientToken: "proof-client",
  upstreamFetch,
});
server.listen(0, "127.0.0.1", () => console.log(server.address().port));
EOF

# run_client <client version> <simlock version>: sets RESULT to INCOMPATIBLE, CONNECTED or UNKNOWN.
# It runs in this shell (not a subshell) so the EXIT trap can always stop the proxy it starts.
run_client() {
  local client=$1 simlock=$2 proxy worker port out log rc=0 i
  RESULT=UNKNOWN
  proxy=$(simlock_proxy_version "$simlock")
  worker=$(simlock_worker_protocol "$simlock")
  log="$TMP/remote-$client-$simlock.log"
  node "$HARNESS/remote.mjs" "$PKGS/proxy-$proxy/package/dist/index.mjs" "$worker" >"$log.port" 2>"$log" &
  PROXY_PID=$!
  port=""
  for i in $(seq 1 100); do
    port=$(head -n1 "$log.port" 2>/dev/null || true)
    [ -n "$port" ] && break
    sleep 0.1
  done
  [ -n "$port" ] || return 0
  out=$(cd "$TMP/home" && env -i PATH="$PATH" HOME="$TMP/home" AGENT_DEVICE_STATE_DIR="$TMP/state-$client-$simlock" \
    AGENT_DEVICE_NO_UPDATE_NOTIFIER=1 node "$PKGS/client-$client/package/bin/agent-device.mjs" devices \
    --daemon-base-url "http://127.0.0.1:$port" --daemon-auth-token proof-client 2>&1) || rc=$?
  kill "$PROXY_PID" 2>/dev/null || true
  wait "$PROXY_PID" 2>/dev/null || true
  PROXY_PID=""
  if grep -q 'Remote daemon RPC protocol is incompatible' <<<"$out"; then
    RESULT=INCOMPATIBLE
  elif [ "$rc" -ne 0 ] && grep -q '^FORWARDED POST /rpc' "$log"; then
    # The client passed the protocol handshake and sent its command, which the stub worker then refused.
    RESULT=CONNECTED
  fi
}

# 3. Behavior. Before #37363 the guide allowed Simlock 0.8.0, which T3's client refused (#41057).
run_client "$PIN_FIX_PARENT" 0.8.0; r=$RESULT
if [ "$r" = INCOMPATIBLE ]; then
  pass "before the fix: T3's agent-device $PIN_FIX_PARENT is refused by a Simlock 0.8.0 remote ('Remote daemon RPC protocol is incompatible', the #41057 bug)"
else
  fail "before the fix: agent-device $PIN_FIX_PARENT against Simlock 0.8.0 gave $r"
fi
# With #37363, the required Simlock 0.9.0 accepts T3's client.
run_client "$PIN_FIX" 0.9.0; r=$RESULT
if [ "$r" = CONNECTED ]; then
  pass "after the fix: T3's agent-device $PIN_FIX passes the handshake with a Simlock 0.9.0 remote and its command reaches the worker"
else
  fail "after the fix: agent-device $PIN_FIX against Simlock 0.9.0 gave $r"
fi
# The PR's pin is refused by the Simlock version T3 now requires.
run_client "$PIN_PR" 0.9.0; r=$RESULT
if [ "$r" = INCOMPATIBLE ]; then
  pass "the PR's agent-device $PIN_PR is refused by a Simlock 0.9.0 remote ('Remote daemon RPC protocol is incompatible')"
else
  fail "the PR's agent-device $PIN_PR against Simlock 0.9.0 gave $r"
fi
# Control: the PR's pin did work with Simlock 0.8.0, so the harness distinguishes the two cases.
run_client "$PIN_PR" 0.8.0; r=$RESULT
if [ "$r" = CONNECTED ]; then
  pass "control: the PR's agent-device $PIN_PR passes the handshake with a Simlock 0.8.0 remote"
else
  fail "control: agent-device $PIN_PR against Simlock 0.8.0 gave $r"
fi

# 4. The linked issue and the competing rollback were closed for this reason.
issue=$(gh api "repos/$REPO/issues/41057" --jq '"\(.state) \(.state_reason)"')
if [ "$issue" = "closed completed" ]; then
  pass "issue #41057 is closed as completed"
else
  fail "issue #41057 is '$issue'"
fi
note=$(gh api "repos/$REPO/issues/41057/comments" --jq '[.[] | select((.body | contains("Simlock 0.9.0 fixes this")) and (.body | contains("rollback to 0.21.36 would now break Simlock 0.9.0")))] | length')
if [ "$note" -ge 1 ]; then
  pass "#41057's closing comment says Simlock 0.9.0 fixes it and a rollback to 0.21.36 would break 0.9.0"
else
  fail "#41057 has no comment citing Simlock 0.9.0"
fi
other=$(gh api "repos/$REPO/pulls/41064" --jq '"\(.state) merged=\(.merged)"')
if [ "$other" = "closed merged=false" ]; then
  pass "the competing rollback #41064 was closed without merging"
else
  fail "#41064 is '$other'"
fi

if [ "$ok" = 1 ]; then
  echo "VERDICT: CLOSE (already-fixed). Simlock 0.9.0 accepts T3's agent-device pin and #37363 requires it; the PR's 0.21.36 pin would break those pools."
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: NOT PROVEN"
exit 1
