#!/usr/bin/env bash
set -euo pipefail

# The fixture repo below carries no modules/harness, so a reachable buildbox receives a
# tree that cannot run gates.sh. These assert gate0 running locally.
export GATE0_REMOTE=0

root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

printf 'test:\n\t@sleep 3\n' >"$tmp/Makefile"
printf 'fail:\n\t@echo sentinel failure >&2\n\t@exit 7\n' >>"$tmp/Makefile"

git -C "$tmp" init -q
git -C "$tmp" config user.email t@t.t
git -C "$tmp" config user.name t
git -C "$tmp" add Makefile
git -C "$tmp" commit -qm seed

GATE0_HEARTBEAT_INTERVAL_SECONDS=1 bash -c '
  source <(awk '\''1; /^capture_check_record\(\)/ { in_function=1 } in_function && /^}$/ { exit }'\'' "$1/lib/gates.sh")
  capture_check_record $'"'"'MAKE_TARGET\ttest'"'"' "$2"
' _ "$root" "$tmp" 2>"$tmp/stderr" &
capture_pid=$!

sleep 2
grep -F 'gate0: heartbeat: check still running: MAKE_TARGET' "$tmp/stderr"
wait "$capture_pid"

bash -c '
  source <(awk '\''1; /^capture_check_record\(\)/ { in_function=1 } in_function && /^}$/ { exit }'\'' "$1/lib/gates.sh")
  rc=0
  capture_check_record $'"'"'MAKE_TARGET\tfail'"'"' "$2" || rc=$?
  [[ $rc -ne 0 ]]
  [[ $_CAPTURE_OUTPUT == *"sentinel failure"* ]]
' _ "$root" "$tmp"

printf 'test:\n\t@sleep 2\n' >"$tmp/Makefile"
set +e
RUNPLAN_GATE_STALL_MS=250 GATE0_HEARTBEAT_INTERVAL_SECONDS=1 \
  "$root/lib/gates.sh" gate0 strict "$tmp" "$tmp" stalled >"$tmp/stdout" 2>"$tmp/stderr"
rc=$?
set -e
[[ $rc -ne 0 ]]
grep -F 'gate0: heartbeat: check still running: MAKE_TARGET' "$tmp/stderr"
grep -F 'FAILCLASS=gate-stalled' "$tmp/stderr"
grep -F 'MAKE_TARGET' "$tmp/stderr"
grep '^{' "$tmp/stderr" >"$tmp/events"
jq -e 'select(.protocol == "runplan.gate/v1" and .event == "check.fail" and .check == "test")' "$tmp/events" >/dev/null

GATE0_HEARTBEAT_INTERVAL_SECONDS=invalid bash -c '
  source <(awk '\''1; /^capture_check_record\(\)/ { in_function=1 } in_function && /^}$/ { exit }'\'' "$1/lib/gates.sh")
  rc=0
  capture_check_record $'"'"'MAKE_TARGET\ttest'"'"' "$2" || rc=$?
  [[ $rc -eq 2 ]]
  [[ $_CAPTURE_OUTPUT == *"fail-closed"* ]]
' _ "$root" "$tmp"
