#!/usr/bin/env bash
set -euo pipefail
exercise_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
simulator=${1:-icarus}
build_dir="$exercise_dir/build/$simulator"
mkdir -p "$build_dir"
cd "$build_dir"
sources=("$exercise_dir"/rtl/*.sv "$exercise_dir"/models/*.sv "$exercise_dir"/integration/*.sv "$exercise_dir"/integration/bgm_lab/*.sv "$exercise_dir"/integration/bgm_hackathon/*.sv "$exercise_dir"/integration/tinytapeout/project.v)
for bench in "$exercise_dir"/tb/*.sv; do
    top=$(basename "$bench" .sv)
    case "$simulator" in
        icarus)
            "${IVERILOG:-iverilog}" -g2012 -Wall -s "$top" -o "$top.vvp" "${sources[@]}" "$bench" > "$top.compile.log" 2>&1 || { cat "$top.compile.log"; exit 1; }
            "${VVP:-vvp}" "$top.vvp" | tee "$top.log"
            ;;
        questa)
            [[ -f modelsim.ini ]] || "${VMAP:-vmap}" -c > /dev/null
            [[ -d work ]] || "${VLIB:-vlib}" work
            "${VLOG:-vlog}" -sv -timescale 1ns/1ps -work work "${sources[@]}" "$bench" > "$top.compile.log" 2>&1 || { cat "$top.compile.log"; exit 1; }
            "${VSIM:-vsim}" -batch -onfinish exit "work.$top" -do "onerror {quit -code 1}; onbreak {quit -code 1}; run -all; quit -code 0" 2>&1 | tee "$top.log"
            ;;
        verilator)
            "${VERILATOR:-verilator}" --binary --timing --trace --timescale 1ns/1ps --top-module "$top" --Mdir "obj_$top" -Wno-PINCONNECTEMPTY -Wno-DECLFILENAME -j 2 "${sources[@]}" "$bench" > "$top.compile.log" 2>&1 || { cat "$top.compile.log"; exit 1; }
            "./obj_$top/V$top" | tee "$top.log"
            ;;
        *) echo "Usage: $0 {icarus|questa|verilator}" >&2; exit 2 ;;
    esac
    grep -q 'PASS ' "$top.log" || { echo "Missing PASS: $top" >&2; exit 1; }
done
