#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

detect_port_from_arduino_cli() {
  local line
  while IFS= read -r line; do
    [[ -z "${line}" ]] && continue
    [[ "${line}" == Port* ]] && continue
    if [[ "${line}" == /dev/* ]]; then
      awk '{print $1}' <<<"${line}"
      return 0
    fi
  done < <(arduino-cli board list 2>/dev/null || true)
  return 1
}

detect_port_from_dev() {
  local candidates=()
  local path
  for path in /dev/ttyACM* /dev/ttyUSB*; do
    [[ -e "${path}" ]] || continue
    candidates+=("${path}")
  done

  if [[ "${#candidates[@]}" -eq 1 ]]; then
    printf '%s\n' "${candidates[0]}"
    return 0
  fi

  return 1
}

PORT="${PORT:-}"
if [[ -z "${PORT}" ]]; then
  PORT="$(detect_port_from_arduino_cli || true)"
fi
if [[ -z "${PORT}" ]]; then
  PORT="$(detect_port_from_dev || true)"
fi

if [[ -z "${PORT}" ]]; then
  echo "Не удалось автоматически найти USB-порт ESP32." >&2
  echo "Подключите плату и проверьте 'arduino-cli board list'." >&2
  echo "Либо укажите порт вручную: PORT=/dev/ttyACM0 ./flash_shine_homeserver_main.sh" >&2
  exit 1
fi

echo "== Найден порт: ${PORT}"
PORT="${PORT}" "${ROOT_DIR}/burn.sh" shine-homeserver-main
