#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SCRIPT="$ROOT/bin/buildbox-scratch-bind"
PAYLOAD="$ROOT/host-config/scratch-bind.sh"

for forbidden in ' harden ' 'systemctl reboot' 'buildbox-deadman'; do
  if grep -q "$forbidden" "$SCRIPT" "$PAYLOAD"; then
    echo "FAIL forbidden mount-only operation: $forbidden" >&2
    exit 1
  fi
done
grep -q 'CPU_GUARD_ACTIVE=1 /usr/bin/node "$REGISTRY_CLI"' "$SCRIPT"
grep -q 'for host in "${hosts\[@\]}"; do' "$SCRIPT"
grep -q 'findmnt --verify --tab-file "$new"' "$PAYLOAD"
if grep -q "trap .* RETURN" "$PAYLOAD"; then
  echo 'FAIL function-scoped RETURN trap survives after local variables are unset' >&2
  exit 1
fi
grep -q "trap 'resume' EXIT" "$PAYLOAD"
grep -q 'SCRATCH already converged' "$PAYLOAD"
grep -q '/usr/local/sbin/buildbox-scratch-bind-apply' "$SCRIPT"
if grep -q '/tmp/buildbox-scratch-bind\.\$\$' "$SCRIPT"; then
  echo 'FAIL remote payload uses a predictable temporary path' >&2
  exit 1
fi
grep -q 'mktemp /tmp/buildbox-scratch-bind\.XXXXXX' "$SCRIPT"
grep -q 'trap cleanup EXIT' "$SCRIPT"
grep -q 'install -m 0755 -- "$tmp"' "$SCRIPT"

bash -n "$SCRIPT" "$PAYLOAD"
output=$(SCRATCH_RUNNER_HOME=/nonexistent bash "$PAYLOAD" --scratch-fstab)
grep -q '/var/lib/buildbox/runs.* /home/user/runs' <<<"$output"
grep -q '/var/lib/buildbox/playwright.* /home/user/.cache/ms-playwright' <<<"$output"

unsafe_home=$(mktemp -d)
trap 'rm -rf "$unsafe_home"' EXIT
mkdir -p "$unsafe_home/actions-runner-safe" "$unsafe_home/actions-runner-bad name"
if SCRATCH_RUNNER_HOME="$unsafe_home" bash "$PAYLOAD" --scratch-fstab >/dev/null 2>"$unsafe_home/err"; then
  echo 'FAIL dedicated payload accepted a runner name with whitespace' >&2
  exit 1
fi
grep -q 'invalid runner name' "$unsafe_home/err"

echo 'ok   dedicated payload has no harden, deadman, or reboot path'
echo 'ok   fleet wrapper preflights then applies hosts sequentially'
echo 'ok   payload validates fstab, restores writers, and is idempotent'
