#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
NODE_VERSION="${ATHENA_BENCH_NODE_VERSION:-v24.16.0}"
NODE_DIST_DIR="${HOME}/.cache/athena-auth/dual-bench/node-${NODE_VERSION}-linux-x64"
NODE_BIN_DIR="${NODE_DIST_DIR}/bin"
BENCH_ITERATIONS="${DUAL_SERVER_BENCH_ITERATIONS:-20}"
BENCH_WARMUP="${DUAL_SERVER_BENCH_WARMUP:-3}"
BENCH_REPEATS="${DUAL_SERVER_BENCH_REPEATS:-3}"

ensure_linux_node() {
  if [[ -x "${NODE_BIN_DIR}/node" && -x "${NODE_BIN_DIR}/npm" ]]; then
    return
  fi

  mkdir -p "$(dirname "${NODE_DIST_DIR}")"
  local archive="node-${NODE_VERSION}-linux-x64.tar.xz"
  local temp_dir
  temp_dir="$(mktemp -d)"
  trap 'rm -rf "${temp_dir}"' RETURN

  curl -fsSLo "${temp_dir}/${archive}" "https://nodejs.org/dist/${NODE_VERSION}/${archive}"
  tar -xf "${temp_dir}/${archive}" -C "$(dirname "${NODE_DIST_DIR}")"
}

rebuild_reference_native_modules() {
  cd "${ROOT_DIR}/compat-tests/reference-server"
  PATH="${NODE_BIN_DIR}:${PATH}" npm rebuild better-sqlite3 >/dev/null
}

run_benchmark() {
  cd "${ROOT_DIR}"
  echo "[dual-bench] iterations=${BENCH_ITERATIONS} warmup=${BENCH_WARMUP} repeats=${BENCH_REPEATS}"
  PATH="${NODE_BIN_DIR}:${PATH}" \
    DUAL_SERVER_BENCH_ITERATIONS="${BENCH_ITERATIONS}" \
    DUAL_SERVER_BENCH_WARMUP="${BENCH_WARMUP}" \
    DUAL_SERVER_BENCH_REPEATS="${BENCH_REPEATS}" \
    cargo test --test dual_server_benchmark_tests dual_server_endpoint_latency_benchmark_report -- --nocapture
}

render_dashboard() {
  cd "${ROOT_DIR}"
  PATH="${NODE_BIN_DIR}:${PATH}" node scripts/render_dual_server_benchmark_report.mjs
}

ensure_linux_node
rebuild_reference_native_modules
run_benchmark
render_dashboard
