#!/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

git -C "$tmp" init -q
git -C "$tmp" config user.email t@t.t
git -C "$tmp" config user.name t
printf '%s\n' '{"scripts":{"test":"node --version"}}' >"$tmp/package.json"
git -C "$tmp" add package.json
git -C "$tmp" commit -qm seed

set +e
"$root/lib/gates.sh" gate0 strict "$tmp" "$tmp" semantic >"$tmp/stdout" 2>"$tmp/stderr"
rc=$?
set -e
[[ $rc -eq 0 ]]
grep '^{' "$tmp/stderr" >"$tmp/events"

jq -e '
  select(.protocol == "runplan.gate/v1")
  | select(.event == "check.start" or .event == "item.start" or .event == "item.complete" or .event == "check.complete" or .event == "gate.complete")
  | (.check | type == "string")
    and (.item | type == "string")
    and (.pid | type == "number")
    and (.elapsed_ms | type == "number")
    and (.output_path | type == "string")
    and (if .event == "gate.complete" then true else (.check | length > 0) and (.output_path | length > 0) end)
' "$tmp/events" >/dev/null

for event in check.start item.start item.complete check.complete gate.complete; do
  jq -e --arg event "$event" 'select(.protocol == "runplan.gate/v1" and .event == $event)' "$tmp/events" >/dev/null
done

printf '%s\n' '{"scripts":{"test":"node -e '\''process.exit(7)'\''"}}' >"$tmp/package.json"
set +e
"$root/lib/gates.sh" gate0 strict "$tmp" "$tmp" semantic-fail >"$tmp/stdout" 2>"$tmp/stderr"
rc=$?
set -e
[[ $rc -ne 0 ]]
grep '^{' "$tmp/stderr" >"$tmp/events"
jq -e 'select(.protocol == "runplan.gate/v1" and .event == "check.fail" and .rc == 7)' "$tmp/events" >/dev/null
