#!/usr/bin/env bash
# Real-server check for #34193 / PR #34202 against a running `vp run dev` server.
# Usage: relink-driver.sh <server-origin> <pairing-token> <state-dir (the server's .t3/<...> dir holding secrets/)>
# Links the environment to account-a through POST /api/connect/relay-config (the request the web and desktop
# clients send after T3 Connect returns a credential), marks the link revoked exactly as markLinkRevoked does
# (writes "true" to the cloud-link-revoked secret; a real revocation needs T3 Connect to reject the credential),
# then links account-b through the same route.
set -euo pipefail
ORIGIN=$1; TOKEN=$2; SECRETS=$3/secrets
JAR=$(mktemp)
trap 'rm -f "$JAR"' EXIT
KEY='-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----'
[ -d "$SECRETS" ] || { echo "no secrets dir at $SECRETS"; exit 2; }
code=$(curl -s -o /dev/null -w '%{http_code}' -c "$JAR" -H 'content-type: application/json' \
  -d "{\"credential\":\"$TOKEN\"}" "$ORIGIN/api/auth/browser-session")
echo "browser session: HTTP $code"
link() {
  echo "POST /api/connect/relay-config cloudUserId=$1"
  curl -s -b "$JAR" -H 'content-type: application/json' -w '\n  -> HTTP %{http_code}\n' \
    -d "{\"relayUrl\":\"https://relay.example.test\",\"cloudUserId\":\"$1\",\"environmentCredential\":\"cred-$1\",\"cloudMintPublicKey\":\"$KEY\",\"endpointRuntime\":null}" \
    "$ORIGIN/api/connect/relay-config" | sed 's/^{/  {/'
}
state() {
  echo "GET /api/connect/link-state"
  curl -s -b "$JAR" "$ORIGIN/api/connect/link-state" | node -e '
    let s = ""; process.stdin.on("data", (d) => (s += d)).on("end", () => {
      const j = JSON.parse(s);
      console.log("  " + JSON.stringify({ linked: j.linked, linkRevoked: j.linkRevoked, cloudUserId: j.cloudUserId }));
    });'
}
echo "== 1. link to account-a"; link account-a; state
echo "== 2. T3 Connect revokes the link (cloud-link-revoked = true, as markLinkRevoked writes it)"
printf 'true' > "$SECRETS/cloud-link-revoked.bin"; state
echo "== 3. link the same environment to account-b"; link account-b; state
echo "stored cloud-linked-user-id: $(cat "$SECRETS/cloud-linked-user-id.bin")"
