#!/usr/bin/env bash
# run_combined_test.sh — launch the combined integration test
#
# Usage:
#   ./run_combined_test.sh [OPTIONS]
#
# Options:
#   -m <MARTe2_DIR>       Override MARTe2 installation dir (default: $MARTe2_DIR)
#   -c <MARTe2_Components_DIR>  Override MARTe2-components dir
#   -b <BUILD_TARGET>     Build target (default: x86-linux)
#   -s                    Skip building — run with whatever is already built
#   -d                    Start debugger web UI (marte2debugger) automatically
#   -h                    Show this help
#
# Ports used:
#   44500/tcp+udp  UDPStreamer1 control + data (scalar signals)
#   44501/tcp      UDPStreamer2 control (packed arrays FirstSample/LastSample)
#   44502/tcp      UDPStreamer3 control (packed arrays FullArray)
#   44503/udp      UDPStreamer1 multicast data (239.0.0.1)
#   8080/tcp       DebugService control
#   8081/udp       DebugService UDPS stream
#   8082/tcp       DebugService log
#   9090/tcp       TCPLogger
#   7777/tcp       Debugger web UI (if -d is given)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CFG="${SCRIPT_DIR}/Test/Configurations/combined_test.cfg"

BUILD_TARGET="${TARGET:-x86-linux}"
SKIP_BUILD=0
START_UI=0

# ── Parse arguments ───────────────────────────────────────────────────────────
while getopts "m:c:b:sdh" opt; do
    case "$opt" in
        m) MARTe2_DIR="$OPTARG" ;;
        c) MARTe2_Components_DIR="$OPTARG" ;;
        b) BUILD_TARGET="$OPTARG" ;;
        s) SKIP_BUILD=1 ;;
        d) START_UI=1 ;;
        h)
            sed -n '2,40p' "$0" | grep '^#' | sed 's/^# \?//'
            exit 0
            ;;
        *) echo "Unknown option: -$OPTARG" >&2; exit 1 ;;
    esac
done

# ── Validate environment ──────────────────────────────────────────────────────
if [[ -z "${MARTe2_DIR:-}" ]]; then
    echo "ERROR: MARTe2_DIR is not set. Source env.sh first or pass -m <dir>."
    echo "  source ${SCRIPT_DIR}/env.sh"
    exit 1
fi

if [[ -z "${MARTe2_Components_DIR:-}" ]]; then
    echo "ERROR: MARTe2_Components_DIR is not set. Source env.sh first or pass -c <dir>."
    exit 1
fi

MARTE2_BIN="${MARTe2_DIR}/Build/${BUILD_TARGET}/App/MARTeApp.ex"
if [[ ! -x "$MARTE2_BIN" ]]; then
    # Some builds use MARTe2.sh as the launcher wrapper
    MARTE2_BIN="${MARTe2_DIR}/Build/${BUILD_TARGET}/App/MARTe2.sh"
fi
if [[ ! -x "$MARTE2_BIN" ]]; then
    echo "ERROR: MARTe2 executable not found at ${MARTe2_DIR}/Build/${BUILD_TARGET}/App/"
    exit 1
fi

# ── Build ─────────────────────────────────────────────────────────────────────
if [[ "$SKIP_BUILD" -eq 0 ]]; then
    echo "==> Building components (TARGET=${BUILD_TARGET})..."
    make -C "${SCRIPT_DIR}" -f Makefile.gcc TARGET="${BUILD_TARGET}" 2>&1 | tail -20
    echo "==> Build done."
fi

# ── Library path ─────────────────────────────────────────────────────────────
BUILD_DIR="${SCRIPT_DIR}/Build/${BUILD_TARGET}"

export LD_LIBRARY_PATH="\
${MARTe2_DIR}/Build/${BUILD_TARGET}/Core:\
${MARTe2_Components_DIR}/Build/${BUILD_TARGET}/Components/DataSources/LinuxTimer:\
${MARTe2_Components_DIR}/Build/${BUILD_TARGET}/Components/DataSources/LoggerDataSource:\
${MARTe2_Components_DIR}/Build/${BUILD_TARGET}/Components/GAMs/IOGAM:\
${MARTe2_Components_DIR}/Build/${BUILD_TARGET}/Components/GAMs/WaveformGAM:\
${BUILD_DIR}/Components/DataSources/UDPStreamer:\
${BUILD_DIR}/Components/GAMs/SineArrayGAM:\
${BUILD_DIR}/Components/GAMs/TimeArrayGAM:\
${BUILD_DIR}/Components/Interfaces/DebugService:\
${BUILD_DIR}/Components/Interfaces/TCPLogger:\
${LD_LIBRARY_PATH:-}"

# ── Loader parameters ─────────────────────────────────────────────────────────
LOADER_PARAMS=(
    -l RealTimeLoader
    -f "${CFG}"
    -s Running
    -m StateMachine:START
)

# ── Optionally start the web UI ───────────────────────────────────────────────
UI_PID=""
if [[ "$START_UI" -eq 1 ]]; then
    UI_BIN="${SCRIPT_DIR}/Client/debugger/marte2debugger"
    echo "==> Building debugger web UI..."
    (cd "${SCRIPT_DIR}/Client/debugger" && go build -o marte2debugger .)
    # Check if port 7777 is already in use
    if ss -tlnH sport = :7777 2>/dev/null | grep -q 7777; then
        echo "==> Debugger web UI already running on http://localhost:7777"
    else
        echo "==> Starting debugger web UI on http://localhost:7777 ..."
        "${UI_BIN}" -addr :7777 &
        UI_PID="$!"
        sleep 0.5
    fi
    echo "    Open http://localhost:7777 in your browser."
    echo "    In the connection panel set:"
    echo "      Host=127.0.0.1   TCP=8080   UDP=8081   Log=9090"
    echo ""
fi

# ── Cleanup handler ───────────────────────────────────────────────────────────
cleanup() {
    echo ""
    echo "==> Shutting down..."
    if [[ -n "$UI_PID" ]] && kill -0 "$UI_PID" 2>/dev/null; then
        kill "$UI_PID"
    fi
}
trap cleanup EXIT INT TERM

# ── Launch MARTe2 ─────────────────────────────────────────────────────────────
echo "==> Launching MARTe2..."
echo "    Config : ${CFG}"
echo "    State  : Running"
echo "    Streams: UDPStreamer1=44500  UDPStreamer2=44501  UDPStreamer3=44502"
echo "    Debug  : TCP=8080  UDP=8081  Log=9090 (TcpLogger auto-injected)"
echo ""
echo "    Press Ctrl-C to stop."
echo ""

exec "${MARTE2_BIN}" "${LOADER_PARAMS[@]}"
