#!/usr/bin/env bash
set -euo pipefail
# Set TOOL_BIN to a directory containing the exact versions documented in the article.
: "${TOOL_BIN:?set TOOL_BIN to the directory containing k6, wrk, ghz}"
OUT=${OUT:-./load-results}
mkdir -p "$OUT"
go build -o "$OUT/target" ./cmd/target
TOKEN=$(python3 -c 'import secrets; print(secrets.token_hex(16))')
FIXTURE_TOKEN="$TOKEN" "$OUT/target" > "$OUT/target.log" 2>&1 &
PID=$!
cleanup() { kill -TERM "$PID" 2>/dev/null || true; wait "$PID" || true; }
trap cleanup EXIT
ready=0
for _ in $(seq 1 100); do
  kill -0 "$PID" 2>/dev/null || { echo "fixture process exited before readiness"; exit 1; }
  ACTUAL=$(curl --silent --fail --max-time 0.2 http://127.0.0.1:18888/ready || true)
  if [[ "$ACTUAL" == "$TOKEN" ]]; then ready=1; break; fi
  sleep 0.05
done
[[ "$ready" == 1 ]] || { echo 'local target not ready'; exit 1; }
K6_NO_USAGE_REPORT=true "$TOOL_BIN/k6" run --quiet k6.js > "$OUT/k6-ok.log" 2>&1
set +e
FAIL=1 K6_NO_USAGE_REPORT=true "$TOOL_BIN/k6" run --quiet k6.js > "$OUT/k6-fail.log" 2>&1
RC=$?
set -e
printf 'k6 negative fixture exit=%s\n' "$RC" | tee "$OUT/k6-exit.log"
[[ "$RC" == 99 ]] || { echo 'expected threshold-failure exit 99'; exit 1; }
"$TOOL_BIN/wrk" -t1 -c1 -d2s --timeout 1s --latency http://127.0.0.1:18888/ok > "$OUT/wrk.log" 2>&1
timeout 5s "$TOOL_BIN/ghz" --insecure --call grpc.health.v1.Health.Check -d '{"service":""}' --total 4 --concurrency 1 --rps 2 --timeout 500ms --connect-timeout 500ms --format json --output "$OUT/ghz-ok.json" 127.0.0.1:18889
timeout 5s "$TOOL_BIN/ghz" --insecure --call grpc.health.v1.Health.Check -d '{"service":"missing-fixture"}' --total 2 --concurrency 1 --rps 2 --timeout 500ms --connect-timeout 500ms --format json --output "$OUT/ghz-fail.json" 127.0.0.1:18889

python3 - "$OUT" <<'PY_VERIFY'
import json, sys
from pathlib import Path
p = Path(sys.argv[1])
a = json.loads((p / 'ghz-ok.json').read_text())
b = json.loads((p / 'ghz-fail.json').read_text())
assert a['count'] == 4 and a['statusCodeDistribution'] == {'OK': 4}, a
assert b['count'] == 2 and b['statusCodeDistribution'] == {'NotFound': 2}, b
print('ghz success: count=4 OK=4; negative: count=2 NotFound=2')
PY_VERIFY
