#!/usr/bin/env bash
# Runs every tests/os suite and every module's own suite. Discovery is a glob, never a list:
# a suite added in either place is gated from the moment it lands, and no one has to remember
# to register it.
set -uo pipefail
# Suites assert released-bundle resolution; an ambient developer hatch would
# silently repoint them at a checkout.
unset HARNESS_ENGINE_DEV
cd "$(dirname "${BASH_SOURCE[0]}")"
ROOT="$(cd ../.. && pwd)"
BUILDBOX_RUNNER="$ROOT/modules/buildbox/test/run-all.sh"

declare -A buildbox_owned=()
while IFS=$'\t' read -r name kind; do
  [ "$kind" = local ] || continue
  buildbox_owned["modules/buildbox/test/$name"]=1
done < <(bash "$BUILDBOX_RUNNER" --list)

suites=()
for suite in *.test.sh "$ROOT"/modules/*/test/*.test.sh; do
  [ -f "$suite" ] || continue
  suites+=("$suite")
done

if [ "${1:-}" = --list ]; then
  for suite in "${suites[@]}"; do
    if [[ "$suite" = "$ROOT/"* ]]; then rel="${suite#$ROOT/}"; else rel="tests/os/$suite"; fi
    owner=os-discovery
    [ -n "${buildbox_owned[$rel]:-}" ] && owner=workspace-buildbox
    printf '%s\t%s\n' "$rel" "$owner"
  done
  exit 0
fi
if [ "$#" -ne 0 ]; then
  echo "usage: $0 [--list]" >&2
  exit 64
fi

failed=()
for suite in "${suites[@]}"; do
  if [[ "$suite" = "$ROOT/"* ]]; then rel="${suite#$ROOT/}"; else rel="tests/os/$suite"; fi
  if [ -n "${buildbox_owned[$rel]:-}" ]; then
    continue
  fi
  echo "=== $rel"
  if bash "$suite"; then :; else failed+=("$rel"); fi
done

if ((${#failed[@]} > 0)); then
  printf 'tests/os: FAILED: %s\n' "${failed[*]}" >&2
  exit 1
fi
echo "tests/os: all suites green"
