#!/bin/bash
# Build all benchmark binaries on the HPC login node.
#
# Usage: bash slurm/build.sh [--papi] [--rapl]
#
# Run this once after rsyncing, before submitting jobs.
# Binaries are written to harness/build-hpc/.

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BUILD_DIR="${REPO_ROOT}/harness/build-hpc"
WITH_PAPI=OFF
WITH_RAPL=OFF

for arg in "$@"; do
  case "$arg" in
    --papi) WITH_PAPI=ON ;;
    --rapl) WITH_RAPL=ON ;;
    *) echo "unknown flag: $arg" >&2; exit 1 ;;
  esac
done

echo "=== pqc-bench build ==="
echo "REPO_ROOT  : $REPO_ROOT"
echo "BUILD_DIR  : $BUILD_DIR"
echo "WITH_PAPI  : $WITH_PAPI"
echo "WITH_RAPL  : $WITH_RAPL"
echo "CC         : ${CC:-default}"
echo "DATE       : $(date -Iseconds)"

# Ensure submodule is populated.
if [[ ! -f "${REPO_ROOT}/algorithms/kyber/ref/kem.c" ]]; then
  echo "Populating git submodules..."
  git -C "$REPO_ROOT" submodule update --init --recursive
fi

cmake \
  -B "$BUILD_DIR" \
  -S "${REPO_ROOT}/harness" \
  -DCMAKE_BUILD_TYPE=Release \
  -DWITH_PAPI="${WITH_PAPI}" \
  -DWITH_RAPL="${WITH_RAPL}"

cmake --build "$BUILD_DIR" --parallel

echo ""
echo "Built binaries:"
ls -lh "${BUILD_DIR}"/bench_mlkem* 2>/dev/null || echo "(none found)"
