#!/usr/bin/env bash
# Sequential one-test-at-a-time integration run.
#
# Runs every Test* function under `galaxy/integration` in a fresh
# Docker state — preclean + single-test `go test -run` invocation —
# stopping on the first failure. Use this to:
#
#   - Diagnose which test brings the suite down on a slow or
#     overloaded Docker.
#   - Build confidence on a host that cannot run the full suite in
#     one shot.
#
# Slower than `make integration` (every test pays the bootstrap cost
# of its own backend/gateway/postgres) but each iteration is
# self-contained, so a flaky test cannot silently poison its
# successors.
#
# Environment:
#   STEP_TIMEOUT     per-test timeout (default 5m).
#   STEP_PRECLEAN    set to 0 to skip the preclean step before each
#                    test. Default is 1; only disable on a hand-cleaned
#                    Docker that you are sure has no leftover state.
#   STEP_VERBOSE     set to 0 to suppress `-v`. Default 1.
#
# Ryuk: this runner exports TESTCONTAINERS_RYUK_DISABLED=true. Ryuk
# does not start cleanly on the local colima setup; the per-step
# preclean handles leftover state by label. Override by setting
# TESTCONTAINERS_RYUK_DISABLED=false in the calling shell.

set -euo pipefail
export TESTCONTAINERS_RYUK_DISABLED="${TESTCONTAINERS_RYUK_DISABLED:-true}"

cd "$(dirname "$0")/.."

readonly STEP_TIMEOUT="${STEP_TIMEOUT:-5m}"
readonly STEP_PRECLEAN="${STEP_PRECLEAN:-1}"
readonly STEP_VERBOSE="${STEP_VERBOSE:-1}"

go_test_flags=(-count=1 -timeout="$STEP_TIMEOUT" -p=1 -parallel=1)
if [ "$STEP_VERBOSE" = "1" ]; then
    go_test_flags+=(-v)
fi

# Discover every top-level Test in the integration module. `go test
# -list` honours build tags and filters; `^Test` picks up the standard
# Go test convention.
mapfile -t tests < <(go test -list '^Test' ./... 2>/dev/null | grep -E '^Test' | sort -u)
if [ "${#tests[@]}" -eq 0 ]; then
    echo "runstep: no tests found under ./..." >&2
    exit 1
fi

echo "runstep: discovered ${#tests[@]} tests; per-test timeout $STEP_TIMEOUT"

passed=0
failed=""
for name in "${tests[@]}"; do
    if [ "$STEP_PRECLEAN" = "1" ]; then
        bash scripts/preclean.sh
    fi
    echo
    echo "============================================================"
    echo "runstep: $name"
    echo "============================================================"
    if go test "${go_test_flags[@]}" -run "^${name}$" ./...; then
        passed=$((passed + 1))
        continue
    fi
    failed="$name"
    break
done

if [ -n "$failed" ]; then
    echo
    echo "runstep: FAILED at $failed (after $passed passes)"
    echo "         drill down with: go test -run '^${failed}$' -v ./..."
    exit 1
fi

echo
echo "runstep: all ${#tests[@]} tests passed"
