@echo off
setlocal enabledelayedexpansion
cls
color f0
echo -----------------------------------------
echo -                                       -
echo - V1.0  Digital Baseband Beta version   -
echo -                                       -
echo -----------------------------------------
echo.
:selectCOM
echo Available COM-ports:
set "_key=HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM"

for /f "tokens=3 delims= " %%c in ('reg query "!_key!" ^| find /v "HKEY"') do (
    set "_com_N=%%c"
    echo/!_com_N:~3! = !_com_N!
)

echo.
set /p "COM=Enter Digital Baseband's COM-port number (example: 3): "

set "validCOM="
for /f "tokens=3 delims= " %%c in ('reg query "!_key!" ^| find /v "HKEY"') do (
    set "_com_N=%%c"
    if /i "!_com_N:~3!"=="%COM%" set "validCOM=1"
)

if not defined validCOM (
    echo.
    echo Invalid COM-port!
    echo Please enter a valid COM-port number from the list.
    echo.
    goto selectCOM
)

echo Uploading software......
esptool.exe --chip esp32 --port COM%COM% --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size 4MB 0x1000 BB-Controller.ino.bootloader.bin 0x8000 BB-Controller.ino.partitions.bin 0xe000 boot_app0.bin 0x010000 BB-controller.ino.bin

if %ERRORLEVEL% neq 0 (
    echo.
    echo Error uploading! Please check the COM-port and Digital Baseband for their state.
    echo Press any key to exit the update tool.
    pause >NUL
    exit /b %ERRORLEVEL%
)
echo Update completed, press any key to close this program.
pause >NUL
endlocal
