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

PORT="${1:-/dev/ttyACM0}"
IDF_DIR="/home/user/esp/esp-idf"
FW_DIR="/home/user/lt/n_signer/firmware/feather_s3_tft"

if [[ ! -f "${IDF_DIR}/export.sh" ]]; then
  echo "ERROR: ESP-IDF export script not found at ${IDF_DIR}/export.sh" >&2
  exit 1
fi

if [[ ! -d "${FW_DIR}" ]]; then
  echo "ERROR: Firmware directory not found at ${FW_DIR}" >&2
  exit 1
fi

if [[ ! -e "${PORT}" ]]; then
  echo "WARNING: ${PORT} does not exist yet. If the board is in bootloader mode, check USB connection." >&2
fi

# shellcheck disable=SC1091
. "${IDF_DIR}/export.sh"

cd "${FW_DIR}"
idf.py -p "${PORT}" flash
