#!/usr/bin/env bash
# Usage: ./fanout.sh <run-name> <front|pricing>   (which service carries the coverage agent)
# The fuzzer only ever talks to wf-front, which calls wf-pricing for every quote.
set -euo pipefail
name=$1; agent_on=$2
out="$PWD/runs/$name"; rm -rf "$out"; mkdir -p "$out/pricing-cov"; cp openapi.yaml "$out/"
docker rm -f wf-front wf-pricing >/dev/null 2>&1 || true
agent=(-e COVERAGE_PROCESS_START=/app/coveragerc)
if [ "$agent_on" = pricing ]; then
  docker run -d --name wf-pricing --network wf-net "${agent[@]}" wf-fanout:lab python -u pricing.py >/dev/null
else
  # Not the fuzzer's agent: plain coverage.py, so we can see pricing's real coverage afterwards.
  docker run -d --name wf-pricing --network wf-net -v "$out/pricing-cov:/cov" -e COVERAGE_FILE=/cov/.coverage \
    wf-fanout:lab python -m coverage run pricing.py >/dev/null
fi
front_env=(); [ "$agent_on" = front ] && front_env=("${agent[@]}")
docker run -d --name wf-front --network wf-net ${front_env[@]+"${front_env[@]}"} wf-fanout:lab python -u front.py >/dev/null
sleep 3
src=front.py; [ "$agent_on" = pricing ] && src=pricing.py
host=wf-front:3001; [ "$agent_on" = pricing ] && host=wf-pricing:3001
docker run --rm --network wf-net -v "$out:/fuzzing-folder" -w /fuzzing-folder \
  -v "$PWD/$src:/app/$src:ro" wuppiefuzz:local fuzz --timeout 120 --report \
  --crash-criteria Status5xxNotSpecified --crash-criteria OtherStatusNotSpecified \
  --coverage-format lcov --coverage-host "$host" --source-dir /app openapi.yaml > "$out/fuzz.log" 2>&1 || true
docker logs wf-front > "$out/front.log" 2>&1; docker logs wf-pricing > "$out/pricing.log" 2>&1
if [ "$agent_on" = front ]; then
  docker kill -s INT wf-pricing >/dev/null; sleep 3   # SIGINT lets coverage.py save .coverage
  docker run --rm -v "$out/pricing-cov:/cov" -w /app -e COVERAGE_FILE=/cov/.coverage wf-fanout:lab \
    python -m coverage report -m pricing.py > "$out/pricing-coverage.txt" 2>&1 || true
fi
docker rm -f wf-front wf-pricing >/dev/null 2>&1 || true
echo "done: $out"
