#!/usr/bin/env bash
# Execute inside scanner container with --network=none. HTTP target is loopback only.
set -euo pipefail
mkdir -p /tmp/zap-test-site /zap/wrk
printf '<html><head><title>Local test</title></head><body>Offline ZAP test</body></html>\n' > /tmp/zap-test-site/index.html
python3 -m http.server 8765 --bind 127.0.0.1 --directory /tmp/zap-test-site > /tmp/zap-http.log 2>&1 &
server=$!
trap 'kill "$server" 2>/dev/null || true' EXIT
python3 - <<'PY'
import time, urllib.request
for _ in range(50):
    try:
        urllib.request.urlopen('http://127.0.0.1:8765', timeout=1).close()
        break
    except OSError: time.sleep(.1)
else: raise RuntimeError('Loopback HTTP fixture did not start')
PY
status=0
zap-baseline.py -t http://127.0.0.1:8765 -r zap.html -J zap.json -z '-dir /tmp/zap-ci -config autoupdate.checkOnStart=false -config autoupdate.checkAddonUpdates=false' || status=$?
[[ "$status" == 0 || "$status" == 1 || "$status" == 2 ]] || exit "$status"
test -s /zap/wrk/zap.html
python3 - <<'PY'
import json
r=json.load(open('/zap/wrk/zap.json'))
assert r.get('site'), 'No scanned sites in ZAP report'
PY
echo "PASS: ZAP crawled loopback fixture with network disabled; baseline policy exit=$status"
