#!/usr/bin/env bash
# Grant serial-port access for Arduino upload (CH340, CP210x, FTDI, etc.)
# Run once: sudo ./scripts/install-udev-rules.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUNDLED_UDEV="${SCRIPT_DIR}/99-platformio-udev.rules"
DEST="/etc/udev/rules.d/99-platformio-udev.rules"

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run with sudo: sudo $0" >&2
  exit 1
fi

# When run via sudo, HOME is /root — use the invoking user's home for PlatformIO fallback.
REAL_USER="${SUDO_USER:-${USER}}"
REAL_HOME="$(getent passwd "${REAL_USER}" | cut -d: -f6)"

PIO_UDEV="${REAL_HOME}/.platformio/penv/lib/python3.14/site-packages/platformio/assets/system/99-platformio-udev.rules"

if [[ -f "${BUNDLED_UDEV}" ]]; then
  SOURCE_UDEV="${BUNDLED_UDEV}"
elif [[ -f "${PIO_UDEV}" ]]; then
  SOURCE_UDEV="${PIO_UDEV}"
else
  echo "udev rules not found. Expected one of:" >&2
  echo "  ${BUNDLED_UDEV}" >&2
  echo "  ${PIO_UDEV}" >&2
  exit 1
fi

install -m 644 "${SOURCE_UDEV}" "${DEST}"
udevadm control --reload-rules
udevadm trigger

echo "Installed ${DEST} (from ${SOURCE_UDEV})"
echo "Unplug and replug the Arduino, then: pio run -t upload"
