#!/bin/bash
#########################################################################################
#
#  Compile + upload the 05_ProximitySensing example to an attached Arduino Nano 33 BLE.
#
#  Usage:
#    ./upload_proximity.sh            # auto-detect port
#    ./upload_proximity.sh -p PORT    # specify port explicitly
#    ./upload_proximity.sh --no-monitor   # skip opening the serial monitor afterwards
#
#  Copyright (c) 2026 ProtoCentral Electronics
#  Licensed under the MIT License.
#
#########################################################################################

set -euo pipefail

LIBRARY_PATH="$(cd "$(dirname "$0")" && pwd)"
EXAMPLE_NAME="05_ProximitySensing"
SKETCH_PATH="$LIBRARY_PATH/examples/$EXAMPLE_NAME"
BOARD_FQBN="arduino:mbed_nano:nano33ble"
CORE_NAME="arduino:mbed_nano"
BAUD_RATE="115200"
BUILD_DIR="/tmp/fdc2214_build/$EXAMPLE_NAME"

SERIAL_PORT=""
OPEN_MONITOR=1

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info()    { echo -e "${BLUE}[INFO]${NC} $1"; }
ok()      { echo -e "${GREEN}[OK]${NC} $1"; }
warn()    { echo -e "${YELLOW}[WARN]${NC} $1"; }
err()     { echo -e "${RED}[ERROR]${NC} $1"; }

while [[ $# -gt 0 ]]; do
    case "$1" in
        -p|--port)        SERIAL_PORT="$2"; shift 2 ;;
        --no-monitor)     OPEN_MONITOR=0; shift ;;
        -h|--help)
            grep '^#' "$0" | sed 's/^# \{0,1\}//'
            exit 0 ;;
        *)
            err "Unknown argument: $1"
            exit 1 ;;
    esac
done

if ! command -v arduino-cli >/dev/null 2>&1; then
    err "arduino-cli not found. Install from https://arduino.github.io/arduino-cli/"
    exit 1
fi

if [[ ! -d "$SKETCH_PATH" ]]; then
    err "Sketch folder missing: $SKETCH_PATH"
    exit 1
fi

if ! arduino-cli core list 2>/dev/null | grep -q "$CORE_NAME"; then
    info "Installing $CORE_NAME core (one-time)..."
    arduino-cli core update-index
    arduino-cli core install "$CORE_NAME"
fi
ok "$CORE_NAME core ready"

detect_port() {
    if [[ -n "$SERIAL_PORT" ]]; then return; fi

    info "Detecting Nano 33 BLE serial port..."
    if [[ "$OSTYPE" == "darwin"* ]]; then
        SERIAL_PORT=$(ls /dev/cu.usbmodem* 2>/dev/null | head -1 || true)
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        SERIAL_PORT=$(ls /dev/ttyACM* 2>/dev/null | head -1 || true)
    fi

    if [[ -z "$SERIAL_PORT" ]]; then
        err "No serial port found. Plug in the board or pass -p /dev/cu.usbmodemXXXX"
        exit 1
    fi
    ok "Using port: $SERIAL_PORT"
}

mkdir -p "$BUILD_DIR"

info "Compiling $EXAMPLE_NAME for Nano 33 BLE..."
arduino-cli compile \
    --fqbn "$BOARD_FQBN" \
    --library "$LIBRARY_PATH" \
    --build-path "$BUILD_DIR" \
    --warnings default \
    "$SKETCH_PATH"
ok "Compile succeeded"

detect_port

info "Uploading to $SERIAL_PORT..."
arduino-cli upload \
    --fqbn "$BOARD_FQBN" \
    --port "$SERIAL_PORT" \
    --input-dir "$BUILD_DIR"
ok "Upload complete"

if (( OPEN_MONITOR == 1 )); then
    sleep 1
    info "Opening serial monitor on $SERIAL_PORT @ $BAUD_RATE (Ctrl+C to exit)..."
    arduino-cli monitor --port "$SERIAL_PORT" --config baudrate=$BAUD_RATE
fi
