@echo off
setlocal EnableDelayedExpansion
title Kelvin - first flash
cd /d "%~dp0"

rem ---------------------------------------------------------------------------
rem  Kelvin node - first flash, for Windows.
rem
rem  Writes the factory image to a blank or reflashed ESP32 over USB. Fetches
rem  what it needs on first run and keeps it beside this file, so a second run
rem  works offline.
rem
rem  Usage:
rem    flash-kelvin.bat              find the board and flash it
rem    flash-kelvin.bat COM9         use that port, skip the search
rem    flash-kelvin.bat COM9 /erase  wipe the chip first - settings and logs go
rem
rem  https://kelvin.arcanesystems.co.uk
rem ---------------------------------------------------------------------------

set "BASE=https://kelvin.arcanesystems.co.uk"
set "IMAGE=kelvin-node-factory.bin"
set "ESPTOOL=esptool.exe"
set "PORT="
set "ERASE="

rem Arguments in either order, so "/erase COM9" works as well as "COM9 /erase".
for %%A in (%*) do (
  set "ARG=%%~A"
  if /i "!ARG!"=="/erase" (set "ERASE=1") else (set "PORT=!ARG!")
)

echo.
echo  ===========================================================
echo    KELVIN - first flash
echo  ===========================================================
echo.

rem --- 1. what it needs -----------------------------------------------------

where curl >nul 2>&1
if errorlevel 1 (
  echo  This needs curl, which ships with Windows 10 1803 and later.
  echo  On older Windows, download these two by hand into this folder:
  echo    %BASE%/tools/esptool.exe
  echo    %BASE%/%IMAGE%
  goto :fail
)

if not exist "%ESPTOOL%" (
  echo  Fetching esptool - 8.8 MB, once.
  curl -L -f --progress-bar -o "%ESPTOOL%.part" "%BASE%/tools/esptool.exe"
  if errorlevel 1 goto :nodownload
  move /y "%ESPTOOL%.part" "%ESPTOOL%" >nul
  echo.
)

rem The image is checked against the published manifest every run, not merely
rem downloaded when absent. Fetch-if-missing would quietly keep flashing
rem whatever version happened to be downloaded first, which is the sort of
rem thing nobody notices until a board is two releases behind.
rem
rem It doubles as an integrity check: firmware.json carries the SHA-256, so a
rem half-finished download is caught before it reaches the board rather than
rem after.
echo  Checking the firmware image...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference='Stop';" ^
  "$have = '';" ^
  "if (Test-Path '%IMAGE%') { $have = (Get-FileHash '%IMAGE%' -Algorithm SHA256).Hash.ToLower() };" ^
  "try { $m = Invoke-RestMethod -UseBasicParsing '%BASE%/firmware.json' }" ^
  "catch {" ^
  "  if ($have) { Write-Host ('  Offline - using the image already here.'); exit 0 }" ^
  "  Write-Host ('  Offline, and no image here yet.'); exit 2 };" ^
  "if ($have -eq $m.factory.sha256) { Write-Host ('  Up to date: ' + $m.version); exit 0 };" ^
  "if ($have) { Write-Host ('  Newer firmware available: ' + $m.version) }" ^
  "else { Write-Host ('  Fetching firmware ' + $m.version) };" ^
  "Invoke-WebRequest -UseBasicParsing $m.factory.latestUrl -OutFile '%IMAGE%.part';" ^
  "$got = (Get-FileHash '%IMAGE%.part' -Algorithm SHA256).Hash.ToLower();" ^
  "if ($got -ne $m.factory.sha256) { Remove-Item '%IMAGE%.part'; Write-Host ('  Download did not match its checksum.'); exit 3 };" ^
  "Move-Item -Force '%IMAGE%.part' '%IMAGE%';" ^
  "Write-Host ('  Firmware ' + $m.version + ' ready.')"
if errorlevel 1 goto :nodownload
rem Belt and braces: on a Windows old enough to lack PowerShell the block
rem above does nothing at all rather than failing, and flashing a file that
rem is not there is a confusing way to find that out.
if not exist "%IMAGE%" goto :nodownload
echo.

rem --- 2. which port --------------------------------------------------------

if not "%PORT%"=="" goto :haveport

echo  Looking for the board...
echo.

set "PORTLIST=%TEMP%\kelvin-ports.txt"
del "%PORTLIST%" 2>nul

rem Win32_PnPEntity rather than the bare port names: the whole problem here is
rem telling a CH340 apart from a Bluetooth link that also calls itself COM.
rem
rem PowerShell does the matching, and strips the trailing "(COMx)" off the
rem name - a bracket read back inside a FOR block closes the block early and
rem the rest of the script falls apart.
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$pat='CH340|CH910|CP210|FTDI|Silicon Labs|USB.?SERIAL|Prolific';" ^
  "Get-CimInstance Win32_PnPEntity -ErrorAction SilentlyContinue |" ^
  "Where-Object { $_.Name -match '\(COM\d+\)' } |" ^
  "ForEach-Object {" ^
  "  $null = $_.Name -match '\((COM\d+)\)';" ^
  "  $p = $Matches[1];" ^
  "  $label = ($_.Name -replace '\s*\(COM\d+\)\s*$','');" ^
  "  $likely = 0; if ($_.Name -match $pat) { $likely = 1 };" ^
  "  '{0}|{1}|{2}' -f $p, $likely, $label }" ^
  > "%PORTLIST%" 2>nul

set "COUNT=0"
set "GUESS="
set "GUESSES=0"
for /f "usebackq tokens=1,2,* delims=|" %%P in ("%PORTLIST%") do (
  set /a COUNT+=1
  set "P!COUNT!=%%P"
  set "LABEL=%%R"
  rem Printed through a variable, not inline: see the note above about brackets.
  echo    [!COUNT!]  %%P    !LABEL!
  if "%%Q"=="1" (
    set /a GUESSES+=1
    set "GUESS=%%P"
  )
)
del "%PORTLIST%" 2>nul

if "%COUNT%"=="0" goto :noports

echo.
if "%GUESSES%"=="1" (
  echo  That looks like %GUESS%.
  set /p "ANSWER=  Press Enter to use it, or type a number or a port: "
) else (
  if "%GUESSES%"=="0" echo  Nothing there is obviously a USB serial adapter.
  if not "%GUESSES%"=="0" echo  More than one candidate.
  set /p "ANSWER=  Which one? Type a number from the list, or a port: "
)

rem Empty takes the guess. A number picks that line, because P1..Pn were set
rem while the list was printed. Anything else is read as a port name typed out.
if "!ANSWER!"=="" (
  set "PORT=%GUESS%"
) else (
  if defined P!ANSWER! (
    call set "PORT=%%P!ANSWER!%%"
  ) else (
    set "PORT=!ANSWER!"
  )
)

:haveport
if "%PORT%"=="" (
  echo.
  echo  No port chosen.
  goto :fail
)
echo.
echo  Using %PORT%.
echo.

rem --- 3. flash -------------------------------------------------------------

if defined ERASE (
  echo  Erasing the whole chip first.
  "%ESPTOOL%" --chip esp32 --port %PORT% --baud 460800 erase_flash
  if errorlevel 1 goto :flashfailed
  echo.
)

echo  Writing %IMAGE% at 0x0. About a minute.
echo.
"%ESPTOOL%" --chip esp32 --port %PORT% --baud 460800 ^
  write_flash -z --flash_mode dio --flash_freq 40m --flash_size 4MB ^
  0x0 "%IMAGE%"
if errorlevel 1 (
  echo.
  echo  460800 did not take. Trying again slowly.
  echo.
  "%ESPTOOL%" --chip esp32 --port %PORT% --baud 115200 ^
    write_flash -z --flash_mode dio --flash_freq 40m --flash_size 4MB ^
    0x0 "%IMAGE%"
  if errorlevel 1 goto :flashfailed
)

echo.
echo  ===========================================================
echo    Done. The node should show KELVIN, then its readout.
echo  ===========================================================
echo.
echo  Next:
echo    - its own Wi-Fi network name and password are on its screen
echo    - or install the app from %BASE%
echo.
goto :done

rem --- problems -------------------------------------------------------------

:noports
echo    None found.
echo.
echo  No COM ports at all. Usually one of:
echo    - a charge-only USB cable. They are common and look identical.
echo    - the CH340 driver is missing. Search the web for "CH340 driver".
echo    - the board is not powered.
goto :fail

:nodownload
echo.
echo  Could not download from %BASE%.
echo  Check this machine is online, then run it again.
del "%ESPTOOL%.part" 2>nul
del "%IMAGE%.part" 2>nul
goto :fail

:flashfailed
echo.
echo  ===========================================================
echo    The flash did not finish.
echo  ===========================================================
echo.
echo  In order of likelihood:
echo.
echo   1. The board is not in download mode. Hold BOOT, tap EN,
echo      release BOOT, then run this again.
echo   2. Wrong port. Run  flash-kelvin.bat COMx  with the right one.
echo      Device Manager, under Ports, shows which is the CH340.
echo   3. Something else has the port open. Close any serial monitor,
echo      Arduino IDE or PlatformIO window.
echo   4. A charge-only USB cable.
echo.
goto :fail

:fail
echo.
pause
exit /b 1

:done
pause
exit /b 0
