#!/usr/bin/env bash
# CrashMire release gate: crash-test one agent again and block the release on a regression.
#
#   CRASHMIRE_KEY=…  ./crashmire-gate.sh <agent id> ["note, e.g. the commit"] [fail_on]
#
#   fail_on: new (default: a flaw the previous test did not have), critical, high, any
#   The key is created in your client space (contract → release gate). Needs curl and jq.
#   Exit code: 0 pass, 1 fail, 2 error or still running after the time limit.
set -euo pipefail
AGENT="${1:?agent id (GET /api/gate/v1/agents lists them)}"
NOTE="${2:-}"
FAIL_ON="${3:-new}"
API="${CRASHMIRE_API:-https://crashmire.com}/api/gate/v1"
AUTH="Authorization: Bearer ${CRASHMIRE_KEY:?CRASHMIRE_KEY is not set}"
WAIT_MAX="${CRASHMIRE_WAIT_MINUTES:-120}"

start=$(curl -sS -X POST "$API/runs" -H "$AUTH" -H 'Content-Type: application/json' \
    -d "$(jq -n --argjson a "$AGENT" --arg n "$NOTE" '{agent: $a, note: $n}')")
run=$(jq -r '.run // empty' <<<"$start")
[ -n "$run" ] || { echo "CrashMire: could not start: $start" >&2; exit 2; }
echo "CrashMire: crash test #$run started"

for _ in $(seq 1 $((WAIT_MAX / 2))); do
    sleep 120
    out=$(curl -sS "$API/runs/$run?fail_on=$FAIL_ON" -H "$AUTH")
    case "$(jq -r '.status' <<<"$out")" in
        done)
            echo "$out" | jq '{verdict, fail_on, new, report_url}'
            [ "$(jq -r '.verdict' <<<"$out")" = pass ] && exit 0 || exit 1 ;;
        failed) echo "CrashMire: the crash test failed: $out" >&2; exit 2 ;;
    esac
done
echo "CrashMire: still running after $WAIT_MAX minutes (run #$run)" >&2
exit 2
