#!/bin/sh

# meshtastic_flash_firmware.sh
# 2026-08-21
# by Gernot Walzl

# This script flashes the Meshtastic firmware of an ESP32 device via USB.
# To get the LILYGO T3S3-S3 into bootloader mode,
# keep the Boot button pressed during startup.

# https://meshtastic.org/docs/hardware/devices/
# https://meshtastic.org/docs/getting-started/flashing-firmware/esp32/cli-script/

MCU="esp32s3"
VERSION="2.7.26.54e0d8d"
ARCHIVE="firmware-${MCU}-${VERSION}.zip"
DOWNLOAD="https://github.com/meshtastic/firmware/releases/download/v${VERSION}/${ARCHIVE}"
SHA256SUM="339650ced8b8c859751f04be69c6af845fea96baca1327518f199afd2595a9d4"
DEVICE=${DEVICE:-'tlora-t3s3-v1'}

set -e

# download firmware archive
if [ ! -f "$ARCHIVE" ]; then
  wget -O "$ARCHIVE" "$DOWNLOAD" || exit 1
fi
if [ "$(sha256sum "$ARCHIVE" | cut -f 1 -d ' ')" != "$SHA256SUM" ]; then
  exit 1
fi

# install firmware flasher
if [ ! -d esptool.venv ]; then
  python3 -m venv esptool.venv
  pip install --upgrade esptool
fi
. esptool.venv/bin/activate

# permissions to access serial ports (over USB)
if ! groups | grep -q dialout; then
  sudo usermod -a -G dialout "$USER"
fi

# extract firmware
DIR=$(basename "$ARCHIVE" .zip)
unzip "$ARCHIVE" -d "$DIR"

# flash firmware
cd "$DIR" || exit 1
chmod +x device-update.sh
./device-update.sh -f "firmware-${DEVICE}-${VERSION}.bin"