@echo off
setlocal EnableDelayedExpansion
title ESP32 Firmware Flash Tool
color 0A

echo.
echo ============================================
echo        ESP32 FIRMWARE FLASH TOOL
echo ============================================
echo The highest number is probably the last device you plugged in.
echo.

:: Gather COM ports from Win32_PnPEntity (CH340 compatible)
set i=0
for /f "usebackq tokens=1 delims=" %%A in (`
    powershell -NoProfile -Command ^
    "(Get-CimInstance Win32_PnPEntity | Where-Object { $_.Name -match 'COM[0-9]+' }).Name | ForEach-Object { if ($_ -match 'COM[0-9]+') { $matches[0] } }"
`) do (
    set /a i+=1
    set "PORT[!i!]=%%A"
)

if %i%==0 (
    echo No COM ports detected.
    echo Make sure your ESP32 is plugged in.
    pause
    exit /b
)

echo Available COM Ports:
echo ---------------------
for /l %%N in (1,1,%i%) do (
    echo   %%N^) !PORT[%%N]!
)

echo.
set /p choice=Select a port number: 

if "!PORT[%choice%]!"=="" (
    echo Invalid selection.
    pause
    exit /b
)

set "COMPORT=!PORT[%choice%]!"

echo.
echo Selected: %COMPORT%
echo Starting flash...
echo.

esptool.exe --chip esp32 --port %COMPORT% --baud 460800 write-flash 0x0 firmware.bin

echo.
echo Flash complete.
pause