#!/usr/bin/bash
#
# camcomDemoStart - Start the CamCom demo (simulated camera) environment
#
# Starts: server (if not auto-started by GUI) and GUI
# Usage: camcomDemoStart [--no-gui]
#

set -e

# Configuration
SIM_CFG="${PREFIX}/resource/config/camcom/example_sim.yaml"
LOG_LEVEL="INFO"

# Parse arguments
START_GUI=true
while [[ $# -gt 0 ]]; do
    case "$1" in
        --no-gui)
            START_GUI=false
            shift
            ;;
        -h|--help)
            echo "Usage: $(basename "$0") [--no-gui]"
            echo "  --no-gui  Start server only, skip GUI"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Check prerequisites
if [[ -z "${PREFIX}" ]]; then
    echo "ERROR: PREFIX not set"
    exit 1
fi

if [[ ! -f "$SIM_CFG" ]]; then
    echo "ERROR: Config not found: $SIM_CFG"
    exit 1
fi

# Stop any existing environment silently
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
"${SCRIPT_DIR}/camcomDemoStop" &>/dev/null || true

# Check if GUI will auto-start the server
gui_starts_server() {
    # Parse YAML for gui.start_srv: true
    # Using grep/sed since we can't assume yq is installed
    if grep -q "start_srv:\s*true" "$SIM_CFG" 2>/dev/null; then
        return 0  # true
    fi
    return 1  # false
}

# Detect available terminal emulator
detect_terminal() {
    for term in gnome-terminal konsole xfce4-terminal mate-terminal tilix terminator xterm; do
        if command -v "$term" &>/dev/null; then
            echo "$term"
            return
        fi
    done
    echo ""
}

TERM_EMU=$(detect_terminal)

# Function to start a command in a new terminal window
# Uses exec so killing the process also closes the terminal
# Writes process PID and terminal PID to variables
start_in_terminal() {
    local title="$1"
    local cmd="$2"
    local pid_var="$3"
    local term_pid_var="$4"
    
    if [[ -z "$TERM_EMU" ]]; then
        # No terminal emulator found, run in background
        echo "  (no terminal emulator found, running in background)"
        bash -c "$cmd" &
        eval "$pid_var=$!"
        eval "$term_pid_var=0"
        return
    fi
    
    # Use exec to replace bash with the process - terminal closes when process exits
    local term_pid=0
    case "$TERM_EMU" in
        gnome-terminal)
            gnome-terminal --title="$title" --class="camcom-$title" --geometry=120x35 -- bash -c "exec $cmd" &
            ;;
        konsole)
            konsole --separate --title "$title" --geometry 1000x600+100+100 -e bash -c "exec $cmd" &
            term_pid=$!
            ;;
        xfce4-terminal)
            xfce4-terminal --title="$title" --geometry=120x35 -e "bash -c 'exec $cmd'" &
            term_pid=$!
            ;;
        mate-terminal)
            mate-terminal --title="$title" --geometry=120x35 -e "bash -c 'exec $cmd'" &
            term_pid=$!
            ;;
        tilix)
            tilix -t "$title" -e "bash -c 'exec $cmd'" &
            term_pid=$!
            ;;
        terminator)
            terminator --title="$title" --geometry=1000x600 -e "bash -c 'exec $cmd'" &
            term_pid=$!
            ;;
        xterm)
            xterm -title "$title" -geometry 120x35 -e bash -c "exec $cmd" &
            term_pid=$!
            ;;
    esac
    
    # Wait for process to start, then find its PID
    sleep 1
    local proc_name=$(echo "$cmd" | awk '{print $1}')
    local proc_pid=$(pgrep -n -f "$proc_name" 2>/dev/null || echo "0")
    eval "$pid_var=$proc_pid"
    eval "$term_pid_var=$term_pid"
}

echo "Starting CamCom Sim Environment..."
echo "  Config:   $SIM_CFG"
echo "  Terminal: ${TERM_EMU:-none (background mode)}"
echo ""

SRV_PID=""
SRV_TERM_PID=""
GUI_PID=""

# Check if GUI will start the server
if gui_starts_server; then
    echo "[1/2] Server will be started by GUI (start_srv: true)"
else
    # Start server in new terminal
    echo "[1/2] Starting server..."
    SRV_CMD="camcomServer -c '$SIM_CFG' -l '$LOG_LEVEL' -v"
    start_in_terminal "CamCom Server (Sim)" "$SRV_CMD" SRV_PID SRV_TERM_PID
    echo "      PID: $SRV_PID"
    
    # Wait for server to initialize
    sleep 1
fi

# Start GUI
if $START_GUI; then
    echo "[2/2] Starting GUI..."
    camcomGui -c "$SIM_CFG" -l "$LOG_LEVEL" -v &
    GUI_PID=$!
    echo "      PID: $GUI_PID"
else
    echo "[2/2] GUI skipped (--no-gui)"
fi

# Save PIDs to file for camcomDemoStop
PID_FILE="/tmp/camcom_demo.pids"
cat > "$PID_FILE" <<EOF
SRV_PID=${SRV_PID:-0}
SRV_TERM_PID=${SRV_TERM_PID:-0}
EOF
[[ -n "$GUI_PID" ]] && echo "GUI_PID=$GUI_PID" >> "$PID_FILE"

echo ""
echo "Environment started. PIDs saved to $PID_FILE"
echo "Run 'camcomDemoStop' to stop all processes."
