#!/usr/bin/env bash
# Runs the containment/guard tests in this directory. NOT part of `pnpm run test`, so
# `ship.sh land` does not gate on it — the individual suites package.json names do.
#
# Some suites here are exhaustion-class (they source lib/danger-guard.sh) and may run
# ONLY in the dangerlab guest. Outside it this runner REFUSES rather than skipping them:
# a bare `bash run-all.sh` on the workstation fork-bombed the machine twice, and a green
# exit with a skip line is what let that happen. A filter that selects only safe suites
# still runs normally.
#
# A `*.dangerlab.sh` suite is collected here too. The suffix keeps it out of every
# `*.test.sh` glob elsewhere in the repo; this runner is the one place that knows it
# exists, so it is also the only place that can report it as unrun.
#
# usage: run-all.sh [name-filter]
set -uo pipefail

TESTS="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Several tests resolve fixtures relative to the repo root, so run them from there.
cd "$TESTS/../../../.."
filter="${1:-}"

. "$TESTS/lib/danger-guard.sh" 2>/dev/null || true
command -v danger_lab_mismatch >/dev/null || {
  printf 'REFUSED: lib/danger-guard.sh did not load, so this runner cannot tell whether it is inside the dangerlab guest.\n' >&2
  exit 70
}
selected=()
for path in "$TESTS"/*.test.sh "$TESTS"/*.test.mjs "$TESTS"/*.test.py "$TESTS"/*.dangerlab.sh; do
  [[ -e "$path" ]] || continue
  t="$(basename "$path")"
  [[ -n "$filter" && "$t" != *"$filter"* ]] && continue
  selected+=("$path")
done

lab_only=()
for path in "${selected[@]}"; do
  grep -qF 'lib/danger-guard.sh' "$path" && lab_only+=("$(basename "$path")")
done

if (( ${#lab_only[@]} )) && [[ -n "$(danger_lab_mismatch)" ]]; then
  {
    printf 'REFUSED: this selection contains exhaustion-class suites and this host is not the dangerlab guest.\n'
    printf 'lab-only: %s\n' "${lab_only[*]}"
    sed 's/^/  /' <<<"$(danger_lab_mismatch)"
    printf '\nRun each there:\n'
    for t in "${lab_only[@]}"; do printf '    bash %s/run-in-lab.sh %s\n' "$TESTS" "$t"; done
    printf '\nOr narrow this runner to safe suites, e.g. run-all.sh cpu-guard\n'
  } >&2
  exit 70
fi

pass=0
fail=0
failed=()

for path in "${selected[@]}"; do
  t="$(basename "$path")"
  case "$t" in
    *.mjs) out=$(node "$path" 2>&1); rc=$? ;;
    *.py) out=$(python3 "$path" 2>&1); rc=$? ;;
    *) out=$(bash "$path" 2>&1); rc=$? ;;
  esac
  if (( rc == 0 )); then
    pass=$((pass + 1))
  else
    fail=$((fail + 1))
    failed+=("$t")
    printf '=== FAIL %s ===\n%s\n' "$t" "$out"
  fi
done

printf 'run-all: pass=%d fail=%d\n' "$pass" "$fail"
if (( fail )); then
  printf 'failed: %s\n' "${failed[*]}"
  exit 1
fi
