#!/usr/bin/env bash
set -euo pipefail
cd -- "$(dirname -- "$0")"
case_id=${1:-}
state=${2:-}
case "$case_id" in
  01A|01B|01C) model=ethernet_lab ;;
  08A|08B|08C) model=wifi_lab ;;
  *) printf 'Use: bash RUN.sh <01A|01B|01C|08A|08B|08C> <before|after>\n' >&2; exit 2 ;;
esac
if [[ ! -f "$model.cc" || ( "$state" != before && "$state" != after ) ]]; then
  printf 'Choose a case in this folder and state before or after.\n' >&2
  exit 2
fi
python_bin=${NS3_PYTHON:-.venv/bin/python}
if [[ ! -x "$python_bin" ]]; then
  python_bin=$(command -v "$python_bin" || true)
fi
if [[ -z "$python_bin" ]]; then
  printf 'Create and install the Ubuntu Python 3.12 environment described in README.md.\n' >&2
  exit 1
fi
base=$("$python_bin" -c 'from importlib.metadata import distribution; print(distribution("ns3").locate_file("ns3"))')
lib="$base/lib64"
export LD_LIBRARY_PATH="$lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
mkdir -p Build Output
if [[ ! -x "Build/$model" || "$model.cc" -nt "Build/$model" ]]; then
  g++ -std=c++20 -O2 -I"$base/include" "$model.cc" -L"$lib" -Wl,-rpath-link,"$lib" \
    -lns3.44-netanim -lns3.44-wifi -lns3.44-mobility -lns3.44-applications \
    -lns3.44-internet -lns3.44-bridge -lns3.44-csma -lns3.44-network -lns3.44-core \
    -Wl,--no-as-needed -l:libgtk-3.so.0 -l:libgobject-2.0.so.0 -l:libglib-2.0.so.0 \
    -o "Build/$model"
fi
cd Output
"../Build/$model" --case="$case_id" --state="$state"
