#!/usr/bin/env bash
# scripts/run-tests-all.sh [filter]
#
# The harness gauntlet: discovers and runs every tests/*/run-tests.sh, one
# summary line each, worst exit wins. This is the TOOLING gate -- run it after
# any script/harness change (the change-delivery loop) and before trusting the
# gate scripts in a deploy. Deliberately NOT folded into preflight.sh:
# preflight gates the DEPLOY TARGET, this gates the TOOLS -- different cadence,
# different failure meaning.
#
# [filter] runs only harnesses whose directory name contains the substring
# (e.g. `bash scripts/run-tests-all.sh phase-06`).
# Mutates NOTHING (harnesses confine themselves to mktemp dirs).
# Exit: 0 all green | 1 any harness failed | 2 no harnesses matched.
# ASCII + LF.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO="$(cd "$HERE/.." && pwd)"
FILTER="${1:-}"
FAILED=(); RAN=0
shopt -s nullglob
for t in "$REPO"/tests/*/run-tests.sh; do
  name="$(basename "$(dirname "$t")")"
  [ -n "$FILTER" ] && case "$name" in *"$FILTER"*) ;; *) continue ;; esac
  RAN=$((RAN+1))
  OUT="$(bash "$t" 2>&1)"; RC=$?
  TAIL="$(printf '%s\n' "$OUT" | tail -1)"
  printf '  %-38s %s\n' "$name" "$TAIL"
  if [ "$RC" -ne 0 ]; then
    FAILED+=("$name")
    printf '%s\n' "$OUT" | grep -E '^\s*(FAIL|\[XX\]|MISS|LEAK|COUNT)' | head -4 | sed 's/^/      /'
  fi
done
echo
if [ "$RAN" -eq 0 ]; then echo "GAUNTLET: no harnesses matched '${FILTER}'"; exit 2; fi
if [ "${#FAILED[@]}" -eq 0 ]; then
  echo "GAUNTLET: ALL GREEN ($RAN harnesses)"; exit 0
fi
echo "GAUNTLET: ${#FAILED[@]}/$RAN FAILED -- ${FAILED[*]}"
exit 1
