#!/bin/bash
# run_debug_app.sh - Launch the MARTe2 Debugging Environment using standard MARTeApp.ex

# 1. Environment Setup
if [ -f "./env.sh" ]; then
    source ./env.sh
else
    echo "ERROR: env.sh not found. Ensure you are in the project root."
    exit 1
fi

# 2. Paths
MARTE_EX="${MARTe2_DIR}/Build/${TARGET}/App/MARTeApp.ex"
DEBUG_LIB="$(pwd)/Build/libmarte_dev.so"

# Component library base search path
COMPONENTS_BUILD_DIR="${MARTe2_Components_DIR}/Build/${TARGET}/Components"

# DYNAMICALLY FIND ALL COMPONENT DIRS
# MARTe2 Loader needs the specific directories containing .so files in LD_LIBRARY_PATH
ALL_COMPONENT_DIRS=$(find "$COMPONENTS_BUILD_DIR" -type d)
for dir in $ALL_COMPONENT_DIRS; do
    if ls "$dir"/*.so >/dev/null 2>&1; then
        export LD_LIBRARY_PATH="$dir:$LD_LIBRARY_PATH"
    fi
done

# Ensure our build dir and core dir are included
export LD_LIBRARY_PATH="$(pwd)/Build:${MARTe2_DIR}/Build/${TARGET}/Core:${LD_LIBRARY_PATH}"

# 3. Cleanup
echo "Cleaning up lingering processes..."
pkill -9 MARTeApp.ex
sleep 1

# 4. Launch Application
echo "Launching standard MARTeApp.ex with debug_test.cfg..."
# PRELOAD ensures our DebugService class is available to the registry early
export LD_PRELOAD="${DEBUG_LIB}"
"$MARTE_EX" -f Test/Configurations/debug_test.cfg -l RealTimeLoader -s State1
