#!/usr/bin/env bash
# Runs every containment/guard test in this directory. Wired into the root `test`
# script so `ship.sh land` gates on it: these tests protect PATH chains and cgroup
# ceilings, which decay silently and are only noticed during an incident.
#
# 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:-}"

pass=0
fail=0
failed=()

for path in "$TESTS"/*.test.sh "$TESTS"/*.test.mjs; do
  [[ -e "$path" ]] || continue
  t="$(basename "$path")"
  [[ -n "$filter" && "$t" != *"$filter"* ]] && continue
  case "$t" in
    *.mjs) out=$(node "$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
