#!/usr/bin/env bash
# Run the engine binary directly (no lelu-mcp wrapper) so stdout, which carries
# the signed audit events, lands in its own file. Usage: direct-run.sh <name> <block:true|false>
set -eu
NAME="$1"; BLOCK="$2"
H=/tmp/lelu-$NAME; rm -rf "$H"; mkdir -p "$H"
# Reuse the engine binary and starter policy that lelu-mcp already downloaded and wrote.
[ -x /lab/lelu-engine ] || cp ~/.lelu/bin/lelu-engine-linux-* /lab/lelu-engine
cp ~/.lelu/policy.yaml "$H/policy.yaml"
echo '{"actor":"lab-agent","action":"read_record","resource":{"customer":"42"},"confidence":0.99}' > /lab/read.json
export LISTEN_ADDR=127.0.0.1:8082 POLICY_PATH=$H/policy.yaml API_KEY=lab-key-$NAME \
       DATABASE_PATH=$H/lelu.db LELU_RSA_KEY_PATH=$H/signing.key.pem \
       CONFIDENCE_ALLOW_UNVERIFIED=true CONFIDENCE_MISSING_MODE=review \
       TENANT_AUTH_RATE_LIMIT=${RATE:-100000000} \
       LELU_AUDIT_BLOCK_ON_FULL=$BLOCK
/lab/lelu-engine > /lab/audit-$NAME.jsonl 2> /lab/engine-$NAME.err &
PID=$!
for i in $(seq 1 30); do curl -sf http://127.0.0.1:8082/healthz >/dev/null && break; sleep 0.5; done
ab -q -n 20000 -c 50 -p /lab/read.json -T application/json \
   -H "Authorization: Bearer $API_KEY" http://127.0.0.1:8082/v1/agent/authorize \
   | grep -E 'Complete|Non-2xx|Requests per second|50%|95%|99%|100%'
sleep 3
curl -s http://127.0.0.1:8082/.well-known/jwks.json > /lab/jwks-$NAME.json
kill -INT $PID; wait $PID 2>/dev/null || true
cp "$H/audit-chain.json" /lab/audit-chain-$NAME.json
echo "audit lines: $(wc -l < /lab/audit-$NAME.jsonl)   chain state: $(cat /lab/audit-chain-$NAME.json)"
/lab/verifychain -log /lab/audit-$NAME.jsonl -jwks /lab/jwks-$NAME.json -state /lab/audit-chain-$NAME.json \
  | jq -c '{events, first_invalid_index, missing, truncated, gaps: ((.gaps // []) | length), complete}' || true
# Independent count: sort the sequence numbers and see how many are really absent.
jq -r .seq /lab/audit-$NAME.jsonl | sort -n | awk 'NR==1{min=$1} {max=$1; n++} END{print "independent count: seq " min ".." max ", lines=" n ", absent=" (max-min+1-n)}'
grep -h 'audit log is incomplete' /lab/engine-$NAME.err | sed 's/^[0-9/]* [0-9:]* //' || true
ls -la "$H" | awk '{print $5, $9}' | grep lelu.db
