#!/bin/bash
# Flash script for ESP32-C6
# Usage: ./flash_esp32c6.sh [PORT]

set -e

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

# ESP32-C6 flash addresses
BOOTLOADER_ADDR=0x0
PARTITIONS_ADDR=0x8000
FIRMWARE_ADDR=0x10000

# Detect port if not provided
if [ -z "$1" ]; then
    echo "Detecting ESP32-C6 serial port..."
    # Try to detect by attempting chip-id on all available ports
    for port in /dev/cu.* /dev/tty.*; do
        [ -e "$port" ] || continue
        # Skip Bluetooth and debug ports
        echo "$port" | grep -qE "(Bluetooth|debug-console)" && continue
        
        # Try to connect to this port
        if /opt/homebrew/bin/esptool --chip esp32c6 --port "$port" chip-id >/dev/null 2>&1; then
            PORT="$port"
            break
        fi
    done
    
    if [ -z "$PORT" ]; then
        echo "ERROR: Could not auto-detect ESP32-C6 serial port."
        echo ""
        echo "Please:"
        echo "1. Ensure the ESP32-C6 is plugged in via USB"
        echo "2. Put the device in download mode:"
        echo "   - Hold BOOT button, press and release RESET, then release BOOT"
        echo "3. Run this script with the port: ./flash_esp32c6.sh /dev/cu.usbserial-XXXX"
        echo ""
        echo "Available serial ports:"
        ls -1 /dev/cu.* /dev/tty.* 2>/dev/null | grep -vE "(Bluetooth|debug-console)" || echo "  (none found)"
        exit 1
    fi
    echo "Detected port: $PORT"
else
    PORT="$1"
fi

# Verify files exist
if [ ! -f "bootloader.bin" ] || [ ! -f "partitions.bin" ] || [ ! -f "firmware.bin" ]; then
    echo "ERROR: Required firmware files not found!"
    echo "Expected: bootloader.bin, partitions.bin, firmware.bin"
    exit 1
fi

echo ""
echo "Flashing ESP32-C6 on $PORT..."
echo "=================================="
echo ""

# Erase flash
echo "Step 1: Erasing flash..."
/opt/homebrew/bin/esptool --chip esp32c6 --port "$PORT" erase-flash

# Flash bootloader
echo ""
echo "Step 2: Flashing bootloader..."
/opt/homebrew/bin/esptool --chip esp32c6 --port "$PORT" write-flash --force $BOOTLOADER_ADDR bootloader.bin

# Flash partitions
echo ""
echo "Step 3: Flashing partition table..."
/opt/homebrew/bin/esptool --chip esp32c6 --port "$PORT" write-flash --force $PARTITIONS_ADDR partitions.bin

# Flash firmware
echo ""
echo "Step 4: Flashing firmware..."
/opt/homebrew/bin/esptool --chip esp32c6 --port "$PORT" write-flash --force $FIRMWARE_ADDR firmware.bin

echo ""
echo "=================================="
echo "Flash completed successfully!"
echo ""
echo "The device will now boot with the new firmware."
echo "Press RESET button if needed."

