#!/usr/bin/env bash
# T1 RID Sensor — One-shot flash script
# Heltec WiFi LoRa V4 (ESP32-S3 + SX1262)
#
# Usage:
#   ./flash.sh                       # standard RID sensor build, auto-detect port
#   ./flash.sh --uav                 # UAV cross-band bridge variant (CC1101 433 MHz)
#   ./flash.sh --port COM7           # specify serial port
#   ./flash.sh --uav --port COM7     # both
#   ./flash.sh --fs-only             # just refresh model artifacts (LittleFS), keep firmware
#
# Flashes firmware (bootloader + partitions + app) AND LittleFS image with all
# trained model artifacts in /models/ (drone_classifier.tflite, the 4 attack
# detectors, markov_baseline.bin, threat.cactus).

set -euo pipefail

ENV="heltec_wifi_lora_v4"
PORT=""
FS_ONLY=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --uav)      ENV="heltec_wifi_lora_v4_uav_bridge"; shift ;;
    --port)     PORT="$2"; shift 2 ;;
    --fs-only)  FS_ONLY=1; shift ;;
    -h|--help)
      sed -n '2,15p' "$0"; exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 2 ;;
  esac
done

cd "$(dirname "$0")"

PORT_ARG=""
[[ -n "$PORT" ]] && PORT_ARG="--upload-port $PORT"

echo "============================================================"
echo "  T1 RID Sensor flash"
echo "  Env:    $ENV"
echo "  Port:   ${PORT:-auto-detect}"
echo "  Mode:   $([ $FS_ONLY -eq 1 ] && echo 'fs-only' || echo 'firmware + fs')"
echo "============================================================"

if [[ $FS_ONLY -eq 0 ]]; then
  echo "[1/2] Flashing firmware..."
  pio run -e "$ENV" -t upload $PORT_ARG
fi

echo "[*] Flashing LittleFS model image..."
pio run -e "$ENV" -t uploadfs $PORT_ARG

echo
echo "============================================================"
echo "  Done. Open serial monitor:"
echo "    pio device monitor -e $ENV $PORT_ARG"
echo "============================================================"
