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

ROOT_DIR="$(cd "$(dirname "$0")/../../.." && pwd)"
NATIVE_SUMMARY="$ROOT_DIR/build/native/sim-configs/summary.tsv"
NATIVE_CLASS_SUMMARY="$ROOT_DIR/build/native/sim-configs/class-summary.tsv"
NATIVE_PATH_MATRIX="$ROOT_DIR/build/native/sim-configs/path-matrix.tsv"
NATIVE_SOURCE_PROOF_SUMMARY="$ROOT_DIR/build/native/native-source-proof-summary.tsv"
NATIVE_BUILD_DIR="$ROOT_DIR/build/native/sim-configs"
NATIVE_SOURCE_PROOF_INPUTS=(
  "$ROOT_DIR/tools/build_native_probes.sh"
  "$ROOT_DIR/tools/source-manifest.txt"
  "$ROOT_DIR/runtime/core/linuxcnc_wrap/linuxcnc_millturn_user_m_boundary_probe.cpp"
  "$ROOT_DIR/runtime/core/linuxcnc_wrap/linuxcnc_tool_db_boundary_probe.cpp"
  "$ROOT_DIR/runtime/core/linuxcnc_wrap/linuxcnc_python_remap_boundary_probe.cpp"
)

native_source_proof_refresh_required() {
  if [[ ! -f "$NATIVE_SOURCE_PROOF_SUMMARY" ]]; then
    return 0
  fi
  for input in "${NATIVE_SOURCE_PROOF_INPUTS[@]}"; do
    if [[ "$input" -nt "$NATIVE_SOURCE_PROOF_SUMMARY" ]]; then
      return 0
    fi
  done
  return 1
}

if [[ ! -f "$NATIVE_SUMMARY" || ! -f "$NATIVE_CLASS_SUMMARY" || ! -f "$NATIVE_PATH_MATRIX" ]]; then
  "$ROOT_DIR/tests/native/verify_sim_configs.sh"
fi
if native_source_proof_refresh_required; then
  "$ROOT_DIR/tools/build_native_probes.sh"
fi

mkdir -p "$NATIVE_BUILD_DIR"
exec 9>"$NATIVE_BUILD_DIR/inventory.lock"
flock 9

if [[ "${SKIP_INTERP_BUILD:-0}" != "1" ]]; then
  "$ROOT_DIR/tools/build_wasm_core.sh"
fi

node "$ROOT_DIR/tests/wasm/node/verify_sim_configs_inventory_wasm.mjs"
