#!/bin/bash
set -euo pipefail

rm -rf target/coverage
mkdir -p target/coverage

cargo clean

export RUSTFLAGS="-C instrument-coverage"
export RUSTDOCFLAGS="-C instrument-coverage"
export LLVM_PROFILE_FILE="$(pwd)/target/coverage/coverage-%p-%m.profraw"

TEST_BINARIES=$(cargo test --all-targets --no-run --message-format=json \
  | jq -r 'select(.profile.test == true) | .executable' \
  | grep -v null)

cargo test --all-targets

cd target/coverage
llvm-profdata merge -sparse coverage-*.profraw -o coverage.profdata

llvm-cov export $TEST_BINARIES \
  -instr-profile=coverage.profdata \
  -format=lcov \
  -ignore-filename-regex='/.cargo/registry' \
  > coverage.lcov

llvm-cov show $TEST_BINARIES \
  -instr-profile=coverage.profdata \
  -format=html \
  -output-dir=html \
  -ignore-filename-regex='/.cargo/registry'

rm -f coverage-*.profraw coverage.profdata

echo ""
echo "Coverage reports generated:"
echo "  SonarQube: target/coverage/coverage.lcov"
echo "  HTML: target/coverage/html/index.html"
