#!/usr/bin/env bash
# Proves a sandboxed agent can drive a dev-server + browser pair without a host
# shell, and that the pnpm store hardlinks into the workspace.
set -euo pipefail

HOST="${1:-debian1}"
ID="e2eproof"
SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
SSH=(ssh -F "$HOME/.ssh/config" -o BatchMode=yes "$HOST")

"${SSH[@]}" "rm -rf sandbox/workspaces/$ID && mkdir -p sandbox/workspaces/$ID"
rsync -a -e "ssh -F $HOME/.ssh/config -o BatchMode=yes" \
  "$SCRIPT_DIR/e2e-fixture/" "$HOST:sandbox/workspaces/$ID/"

echo "=== install + hardlink proof (inside sandbox) ==="
"${SSH[@]}" ".local/share/overdeck-sandbox/bin/sandbox-run --id $ID -- /bin/bash -lc '
  set -e
  pnpm install --silent
  target=\$(find node_modules/.pnpm -type f -name \"*.js\" | head -1)
  links=\$(stat -c %h \"\$target\")
  echo \"pnpm-store-hardlinks: \$links (\$target)\"
  test \"\$links\" -gt 1
'"

echo "=== e2e pair over the forced-command channel ==="
"${SSH[@]}" ".local/share/overdeck-sandbox/bin/sandbox-run --id $ID -- /bin/bash -lc '
  e2e-remote --server \"node server.mjs\" --wait-port 4331 \
    --env PORT=4331 --env SHOT_DIR=.shots --mkdir .shots -- node shoot.mjs
'"

echo "=== artifacts landed in the workspace ==="
"${SSH[@]}" "cat sandbox/workspaces/$ID/.shots/proof.txt && ls -l sandbox/workspaces/$ID/.shots/proof.png"

echo "=== no browser ever ran in the agent sandbox ==="
"${SSH[@]}" ".local/share/overdeck-sandbox/bin/sandbox-run --id $ID -- /bin/bash -lc '
  node -e \"import(\\\"playwright\\\").then(p=>p.chromium.launch()).then(()=>{console.log(\\\"LAUNCHED\\\");process.exit(1)}).catch(e=>{console.log(\\\"refused: \\\"+String(e.message).split(String.fromCharCode(10))[0]);process.exit(0)})\"
'"

echo "e2e offload proof complete"
