#!/usr/bin/env bash
# ------------------------------------------------------------
# Reproduce rdragon setup logic: create /tmp/rundirXXXX, copy binary → code,
# copy data & *.c2m, execute <case>.access, and write dragon.env
# Arguments: <x2mFile>  <ompThreads>
# ------------------------------------------------------------
set -euo pipefail

x2mFile="$1"               # Example: rnr_0burn_spot.x2m
ompThreads="$2"

CODE_DIR="$(pwd)"                          # Project root directory
MACH="$(uname -sm | sed 's/[ ]/_/')"       # e.g., Darwin_arm64
RUN_DIR="$(mktemp -d /tmp/rundirXXXXXX)"   # Temporary runtime directory

echo "RunDirectory: $RUN_DIR"

# ---------- Copy the binary as ./code -------------------------
cp "$CODE_DIR/bin/$MACH/Dragon" "$RUN_DIR/code"
chmod +x "$RUN_DIR/code"

# —— New: Generate or copy dSYM symbol table ————————————————
if command -v dsymutil &>/dev/null; then
  dsymutil "$RUN_DIR/code"             # Generate code.dSYM in run dir
  echo "Generated dSYM in $RUN_DIR/code.dSYM"
elif [[ -d "$CODE_DIR/bin/$MACH/Dragon.dSYM" ]]; then
  cp -R "$CODE_DIR/bin/$MACH/Dragon.dSYM" "$RUN_DIR/code.dSYM"
  echo "Copied existing Dragon.dSYM to run dir"
else
  echo "Warning: no dSYM available (dsymutil missing and no prebuilt .dSYM)"
fi
# ———————————————————————————————————————————————————————————————

# ---------- Copy dataset & auxiliary files ---------------------
cp "$CODE_DIR/data/$x2mFile" "$RUN_DIR/mydata"

proc_dir="$CODE_DIR/data/${x2mFile%.x2m}_proc"
[[ -d $proc_dir ]] && cp "$proc_dir"/*.c2m "$RUN_DIR/" 2>/dev/null || true
cp -f "$CODE_DIR"/data/assert{S,V}.c2m "$RUN_DIR/" 2>/dev/null || true

# ---------- Execute <case>.access in the temp directory ---------
cd "$RUN_DIR"
access="$CODE_DIR/data/${x2mFile%.x2m}.access"
[[ -f $access ]] && bash "$access" "$CODE_DIR"

# ---------- Write env file for VS Code to read ------------------
cat > "$CODE_DIR/.vscode/dragon.env" <<EOF
RUN_DIR=$RUN_DIR
MACH=$MACH
OMP_NUM_THREADS=$ompThreads
EOF
ln -sfn "$RUN_DIR" "$CODE_DIR/.vscode/current_run"   # Point to latest run dir

echo "prepare-rdragon.sh done ✅  -> $RUN_DIR"
