::
::
:: We have to use this method because the nvs_key partiton has to be written 
:: at the same time as the firmware because the ESP32S3 will apply it's own
:: encryption to that partition the first time is starts.
::

echo off

if %2. EQU . (
    echo Usage: flash.sh serialNumber port
    goto end
)

echo Flashing Leaflet serial number %1

:: hardware and serial number lookup helpers
set HWMAJOR=A
set HWMINOR=1
set SNGROUP=b
set BASESN=4

:: set the serial number
set SN=%1
set PORT=%2
set START_NVS=0x9000
set START_NVS_KEYS=0x14000
set START_CSK_PART=0x15000 
set CSK_PART_SIZE=0x4000

set /a "SN=%SN%-%BASESN%"
)

set SNFILESTUB=%HWMAJOR%%HWMINOR%%SNGROUP%-%SN%

echo Using key file stub %SNFILESTUB%

:: Generate the code signing key partition
echo -- Generate encrypted code-signing key partition
python.exe %IDF_PATH%/components/nvs_flash/nvs_partition_generator/nvs_partition_gen.py encrypt ^
    --inputkey manufacturing/keys/keys-%SNFILESTUB%.bin ./ota_mqtt_csk.csv ./ota_mqtt_csk.bin %CSK_PART_SIZE%


:: Write the encrypted "nvs" partition
echo -- Write encrypted NVS partition
python.exe %IDF_PATH%\components\esptool_py\esptool\esptool.py -p %PORT% --before default_reset ^
    --after no_reset write_flash %START_NVS% manufacturing/bin/%SNFILESTUB%.bin

:: Flash the code signing key
echo -- Write the code signing key partition
python.exe %IDF_PATH%\components\esptool_py\esptool\esptool.py -p %PORT% --before default_reset ^
    --after no_reset write_flash %START_CSK_PART% ./ota_mqtt_csk.bin

:: Write everything except the firmware
echo -- Write bootloader, partition table, OTA initial data and NVS partition key
python.exe %IDF_PATH%\components\esptool_py\esptool\esptool.py --chip esp32s3 -p %PORT% -b 460800 --before=default_reset ^
    --after=no_reset write_flash --flash_mode dio --flash_freq 80m --flash_size 8MB ^
    0x0 build/bootloader/bootloader.bin ^
    0x8000 build/partition_table/partition-table.bin ^
    0x11000 build/ota_data_initial.bin ^
    %START_NVS_KEYS% manufacturing/keys/keys-%SNFILESTUB%.bin

:: Write the firmware (unencrypted the first time)
echo -- Write sensor_firmware
python.exe %IDF_PATH%\components\esptool_py\esptool\esptool.py --chip esp32s3 -p %PORT% -b 460800 --before=default_reset ^
    --after=no_reset write_flash --flash_mode dio --flash_freq 80m --flash_size 8MB ^
    0x20000 build/sensor-firmware.bin
    
:end
