#!/usr/bin/env bash
# All tests possible without ESP32/CC1101/RTL-SDR/car.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
mkdir -p artifacts/validation

if [ -n "${PIO:-}" ]; then
    PIO_BIN="$PIO"
elif [ -x "$ROOT/.venv/bin/pio" ]; then
    PIO_BIN="$ROOT/.venv/bin/pio"
elif command -v pio >/dev/null 2>&1; then
    PIO_BIN="$(command -v pio)"
else
    python3 -m venv "$ROOT/.venv"
    "$ROOT/.venv/bin/pip" install --disable-pip-version-check -r tools/requirements.txt
    PIO_BIN="$ROOT/.venv/bin/pio"
fi

run() {
    local name="$1"
    shift
    echo "== $name =="
    "$@" 2>&1 | tee "artifacts/validation/$name.log"
}

run python-self-test python3 tools/tpms_frame.py --self-test
run native-tests "$PIO_BIN" test -e native
run esp32-build "$PIO_BIN" run -e esp32s2mini
run cppcheck "$PIO_BIN" check -e native \
    --flags='--enable=warning,performance,portability --inline-suppr' \
    --fail-on-defect=low

if [ ! -x "${RTL433:-$ROOT/.cache/rtl_433/build/src/rtl_433}" ] \
        || [ ! -f "${REFERENCE_DIR:-$ROOT/.cache/rtl_433_tests/tests/Schrader_EG53MA4_TPMS/01}/gfile001.cu8" ]; then
    run fetch-references bash ./tools/fetch_references.sh
fi
run rtl433 bash ./tools/verify_rtl433.sh

echo "PASS: all hardware-free tests completed successfully"
