@echo off
COLOR A
echo Full Format ^!^!^!^!^!^!^!^!^!^!^!
setlocal EnableDelayedExpansion
SET /P M=COM port: 
echo -------------------------
echo BACKUP REGISTRATION CODE
esptool.exe --port COM%M% read_flash 0x3FB000 6 code.txt
echo SUCCESS!
echo -------------------------
echo ERASE FLASH
esptool.exe --port COM%M% erase_flash
echo SUCCESS!
echo -------------------------

set "INPUT=code.txt"
set "OUTPUT=eeprom_full.bin"
set "PADBIN=pad_ff.bin"
set "HEX=pad_ff.hex"
set /a TOTAL=4096

for %%I in (%INPUT%) do set /a SIZE=%%~zI

if !SIZE! GEQ !TOTAL! (
    echo %INPUT% is already >= 4096 bytes
    copy /Y %INPUT% %OUTPUT% >nul
    goto :done
)

set /a NEED=!TOTAL! - !SIZE!

set /a LINES=!NEED! / 16
set /a REM=!NEED! %% 16

> %HEX% (
    for /L %%i in (1,1,!LINES!) do echo FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
    if !REM! NEQ 0 (
        set "LINE="
        for /L %%j in (1,1,!REM!) do set "LINE=!LINE!FF "
        echo !LINE!
    )
)

certutil -f -decodehex %HEX% %PADBIN% >nul 2>&1
if errorlevel 1 (
    echo HIBA: certutil nem tudta létrehozni a bináris fájlt.
    goto :error
)

copy /b %INPUT% + %PADBIN% %OUTPUT% >nul

del %PADBIN%
del %HEX%

echo WRITE REGISTRATION CODE
esptool.exe --port COM%M% write_flash 0x3FB000 eeprom_full.bin
del %OUTPUT%
echo SUCCESS!
goto :done

:error
echo ERROR.
exit /b 1

:done
endlocal
echo -------------------------


pause