# NOTE: On some systems, you may need:
#   export LD_PRELOAD=/usr/lib64/libtinfo.so.5
# before running this script.

# xsim_run.tcl - Vivado xsim compilation and simulation script
#
# Compiles all SHA3 RTL sources plus testbenches and runs simulation.
# Run from the project root: ~/Dev/mlkem/
#
# Prerequisites:
#   source /opt/Xilinx/Vivado/2019.2/settings64.sh
#
# Usage examples:
#   # Run simple self-checking test on sha3_top (G mode)
#   xsim sha3_simple_sim -R
#
#   # Run keccak_core self-checking test
#   xsim keccak_core_sim -R
#
#   # Run file-based vector test on sha3_top (requires vectors/g_basic_input.hex)
#   xsim tb_sha3_xsim -R
#
#   # Full batch: compile + elaborate + run (via Tcl)
#   xsim -runall xsim_run.tcl
#
#   # Or step-by-step:
#   vivado -mode batch -source xsim_run.tcl

# ================================================================
# Configuration
# ================================================================
set SRC_DIR  sync_rtl/sha3
set TB_DIR   sync_rtl/sha3/TB

# ================================================================
# Step 1: Compile all source files (xvlog)
# ================================================================
puts "=== Compiling RTL sources ==="

# Core Keccak module (combinational round)
xvlog -sv ${SRC_DIR}/keccak_round.v

# Keccak core (24-round sequential core)
xvlog -sv ${SRC_DIR}/keccak_core.v

# SHA3 top wrapper (G/H/J modes)
xvlog -sv ${SRC_DIR}/sha3_top.v

# ================================================================
# Step 2: Compile testbenches
# ================================================================
puts "=== Compiling testbenches ==="

# Simple self-checking testbench (recommended for quick validation)
xvlog -sv ${TB_DIR}/tb_sha3_xsim_simple.v

# Keccak core self-checking testbench
xvlog -sv ${TB_DIR}/tb_keccak_core_xsim.v

# File-based vector testbench
xvlog -sv ${TB_DIR}/tb_sha3_xsim.v

# ================================================================
# Step 3: Elaborate each snapshot (xelab)
# ================================================================
puts "=== Elaborating snapshots ==="

# Simple sha3_top testbench (G mode, hardcoded vector)
xelab tb_sha3_xsim_simple -s sha3_simple_sim --timescale 1ns/1ps

# Keccak core testbench (all-zero input)
xelab tb_keccak_core_xsim -s keccak_core_sim --timescale 1ns/1ps

# File-based sha3_top testbench (reads vectors/g_basic_input.hex)
xelab tb_sha3_xsim -s tb_sha3_xsim --timescale 1ns/1ps

# ================================================================
# Step 4: Run simulations
# ================================================================
puts "=== Running simple SHA3 test ==="
xsim sha3_simple_sim -R

puts ""
puts "=== Running Keccak core test ==="
xsim keccak_core_sim -R

puts ""
puts "=== Running file-based SHA3 test ==="
xsim tb_sha3_xsim -R

puts ""
puts "=== All simulations complete ==="
