#!/usr/bin/env bash
# Usage: ./run.sh <run-name> <seconds> [extra wuppiefuzz args...]
# Starts a fresh target on wf-net (AGENT=1 turns on the coverage agent on :3001),
# fuzzes it from a second container, then saves the target's log next to the reports.
set -euo pipefail
name=$1; secs=$2; shift 2
out="$PWD/runs/$name"; rm -rf "$out"; mkdir -p "$out"
cp target/openapi*.yaml auth-wfc.yaml admin-header.yaml "$out/"

docker rm -f wf-target >/dev/null 2>&1 || true
docker run -d --name wf-target --network wf-net \
  ${AGENT:+-e COVERAGE_PROCESS_START=/app/coveragerc} \
  wf-target:lab >/dev/null
sleep 3

docker run --rm --network wf-net \
  -v "$out:/fuzzing-folder" -w /fuzzing-folder \
  -v "$PWD/target/app.py:/app/app.py:ro" \
  wuppiefuzz:local fuzz --timeout "$secs" --report "$@" "${SPEC:-openapi.yaml}" \
  > "$out/fuzz.log" 2>&1 || echo "fuzzer exit $?"

sleep 2   # let the async export worker finish printing
docker logs wf-target > "$out/target.log" 2>&1
docker rm -f wf-target >/dev/null
echo "done: $out"
