#!/bin/bash
# EAB Launcher for launchd
# Keeps trying to connect to ESP32, waits if no device
#
# Note: launchd jobs may not always provide a full shell environment (e.g. HOME can be unset).
# Resolve EAB_DIR relative to this script so `python -m eab` can import from the local checkout.

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
EAB_DIR="$SCRIPT_DIR"
BASE_DIR="/tmp/eab-devices/default"
LOG_FILE="/tmp/eab-launcher.log"
# Use venv if available, otherwise find system python
if [ -f "$SCRIPT_DIR/.venv/bin/python3" ]; then
    PYTHON_BIN="$SCRIPT_DIR/.venv/bin/python3"
else
    PYTHON_BIN="$(command -v python3 || echo /usr/bin/python3)"
fi

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

log "EAB Launcher starting..."

# Ensure base directory exists
mkdir -p "$BASE_DIR"

while true; do
    # Check if device is present
    DEVICE=$(ls /dev/cu.usbmodem* /dev/cu.usbserial* 2>/dev/null | grep -v debug | head -1)

    if [ -n "$DEVICE" ]; then
        log "Found device: $DEVICE"

        # Run EAB with force flag (takes over from any stuck daemon)
        if ! cd "$EAB_DIR"; then
            log "ERROR: Failed to cd to EAB_DIR=$EAB_DIR"
            sleep 5
            continue
        fi

        # Ensure the local checkout is importable even under launchd's minimal environment.
        PYTHONPATH="$EAB_DIR" "$PYTHON_BIN" -m eab --port auto --base-dir "$BASE_DIR" --force >> "$LOG_FILE" 2>&1
        EXIT_CODE=$?

        log "EAB exited with code $EXIT_CODE"

        # If it exited cleanly (device disconnected), wait before retry
        if [ $EXIT_CODE -eq 0 ]; then
            log "Clean exit, waiting 5s before retry..."
            sleep 5
        else
            # Error exit, wait longer
            log "Error exit, waiting 10s before retry..."
            sleep 10
        fi
    else
        # No device, wait and retry
        sleep 10
    fi
done
