#!/usr/bin/env bash
# Live box receipt for every git deny-gate rule. Run once per buildbox.
set -uo pipefail

HOST="${1:-debian1}"
SSH=(ssh -F "$HOME/.ssh/config" -o BatchMode=yes "$HOST")
ID="deny-gate-proof"
FAIL=0 PASS=0

run() {
  "${SSH[@]}" ".local/share/overdeck-sandbox/bin/sandbox-run --id $ID -- /bin/bash -c $(printf '%q' "$1")" 2>&1
}
expect_deny() {
  local name=$1 command=$2 output rc
  output="$(run "$command")"; rc=$?
  if [[ $rc -eq 86 && "$output" == *2026-08-16-remote-deny-gate-design.md* ]]; then
    PASS=$((PASS + 1)); printf 'PROVEN %s\n' "$name"
  else
    FAIL=$((FAIL + 1)); printf 'PROVE-FAIL %s rc=%s %s\n' "$name" "$rc" "$output"
  fi
}
expect_allow() {
  local name=$1 command=$2 output rc
  output="$(run "$command")"; rc=$?
  if [[ $rc -ne 86 ]]; then PASS=$((PASS + 1)); printf 'PROVEN %s\n' "$name";
  else FAIL=$((FAIL + 1)); printf 'PROVE-FAIL %s %s\n' "$name" "$output"; fi
}

expect_deny "force" 'git push --force origin HEAD:refs/cdx/x/out'
expect_deny "no-verify" 'git push --no-verify origin HEAD:refs/cdx/x/out'
expect_deny "main" 'git push origin HEAD:refs/heads/main'
expect_deny "master" 'git push mirror HEAD:refs/heads/master'
expect_deny "non-result" 'git push origin HEAD:refs/heads/topic'
expect_allow "cdx" 'git push mirror sha:refs/cdx/x/out'
expect_allow "seat" 'git push origin HEAD:refs/harness-seat/x'
expect_allow "factory" 'git push origin HEAD:refs/heads/factory-result/x'
expect_allow "wip" 'git push origin HEAD:refs/heads/wip/x'
expect_allow "inside reset" 'mkdir -p /sandbox/workspaces/deny-gate-proof/in; git -C /sandbox/workspaces/deny-gate-proof/in init -q; git -C /sandbox/workspaces/deny-gate-proof/in reset --hard'
expect_deny "outside reset" 'mkdir -p /tmp/deny-gate-proof/out; git -C /tmp/deny-gate-proof/out init -q; cd /tmp/deny-gate-proof/out; git reset --hard'
# Each sandbox-run container is ephemeral: state from one invocation never survives
# into the next, so every destructive-verb case builds its own outside-workspace
# repo in the same invocation it tests.
for command in 'clean -fd' 'checkout --' 'checkout .' 'restore file' 'stash drop' 'stash clear' 'gc --prune=now' 'update-ref -d refs/x' 'branch -D x'; do
  expect_deny "$command" "mkdir -p /tmp/deny-gate-proof/out; git -C /tmp/deny-gate-proof/out init -q; cd /tmp/deny-gate-proof/out; git $command"
done

if [[ $FAIL -eq 0 ]]; then status=pass; else status=fail; fi
printf '{"box":"%s","kind":"deny-gate-proof","status":"%s","passed":%s,"failed":%s}\n' "$HOST" "$status" "$PASS" "$FAIL"
exit "$FAIL"
