#!/usr/bin/env bash
# =============================================================================
#  COSMOS  BER-vs-Eb/N0  —  one-shot runner
# -----------------------------------------------------------------------------
#  Download this ONE file to your reservation's console, edit the CONFIG block
#  below, then run it:
#
#        bash run_ber.sh
#
#  It grabs the experiment code, prepares everything, runs the measurement on
#  your two SDR nodes, and renders the BER curve — all you touch is CONFIG.
#  Re-running is safe (it reuses what it already fetched).
# =============================================================================

# ============================  CONFIG (edit me)  =============================
NODES="node18-19,node18-2"     # your two reserved B210 nodes as  TX,RX
FREQ_HZ=2000000000             # carrier in Hz (2.0 GHz works on the grid)
MODS="bpsk,qpsk"               # modulations to measure: bpsk,qpsk,8psk
RX_GAIN=60                     # receive gain in dB
NSYMS=50000000                 # bits per Eb/N0 step  (raise for a smoother low-BER tail)
EBN0="0:13:0.5"                # Eb/N0 sweep  start:stop:step  in dB
# ============================================================================

set -euo pipefail
REPO="https://gitlab.orbit-lab.org/tutorials/ber.git"
SRC="$HOME/ber-src"
BUNDLE="$HOME/tutorials-ber"

echo "==> [1/4] fetching experiment code"
if [ -d "$SRC/.git" ]; then git -C "$SRC" pull --ff-only --quiet || true
else git clone --quiet "$REPO" "$SRC"; fi

echo "==> [2/4] preparing the run bundle in $BUNDLE"
bash "$SRC/ansible/build_ber_bundle.sh" "$BUNDLE" >/dev/null
cd "$BUNDLE"

# turn the comma-separated MODS into a JSON list for ansible -e
MODS_JSON=$(python3 -c "import sys;print('[\"'+'\",\"'.join(s.strip() for s in sys.argv[1].split(','))+'\"]')" "$MODS")

echo "==> [3/4] measuring BER on $NODES  (mods=$MODS, ${NSYMS} bits/step)"
OMF_NODES="$NODES" ansible-playbook ber/ber.yml -e \
  "{\"ber_mods\":$MODS_JSON,\"ber_freq_hz\":$FREQ_HZ,\"ber_rx_gain\":$RX_GAIN,\"ber_nsyms\":$NSYMS,\"ber_ebn0\":\"$EBN0\"}"

echo "==> [4/4] rendering BER curves"
ansible-playbook ber/plot.yml

echo
echo "============================================================"
echo " DONE.  Results (CSV + SigMF + BER graph) are in:"
echo "     $BUNDLE/results/"
echo "============================================================"
