@ECHO OFF

:: Enable delayed expansion
setlocal EnableDelayedExpansion

:: Getting the CubeProgammer_cli path
call ../env.bat

set isGeneratedByCubeMX=%PROJECT_GENERATED_BY_CUBEMX%
:: CubeProgammer path and input files
set ob_flash_programming="ob_flash_programming.bat"
set password_programming="../DA/password_provisioning.bat"
set create_password="../DA/create_password.bat"

set ob_flash_log="ob_flash_programming.log"
set password_programming_log="../DA/password_provisioning.log"
set create_password_log="../DA/create_password.log"
set state_change_log="provisioning.log"

:: Initial configuration
set product_state=OPEN
set connect_no_reset=-c port=SWD speed=fast ap=1 mode=Hotplug
set connect_reset=-c port=SWD speed=fast ap=1 mode=UR

goto exe:
goto py:
:exe
::line for window executable
set "applicfg=%cube_fw_path%\Utilities\PC_Software\ROT_AppliConfig\dist\AppliCfg.exe"
set "python="
if exist %applicfg% (
echo run config Appli with windows executable
goto prov
)
:py
::line for python
echo run config Appli with python script
set "applicfg=%cube_fw_path%\Utilities\PC_Software\ROT_AppliConfig\AppliCfg.py"
set "python=python "

:prov
echo =====
echo ===== Provisioning of OEMiRoT boot path
echo ===== Application selected through env.bat:
echo =====   %oemirot_boot_path_project%
echo ===== Product state must be Open. Execute  \ROT_Provisioning\DA\regression.bat if not the case.
echo =====
echo.

:: bypass this step when Generated By CubeMX
if "%isGeneratedByCubeMX%" == "true" goto :cubemx
if /i %oemirot_boot_path_project% == %oemirot_boot_path_project:OEMiROT_Appli=% (
echo =====
echo ===== Wrong Boot path: %oemirot_boot_path_project%
echo ===== please modify the env.bat to set the right path
goto step_error
)

:: ========================================================= Keys generation steps ==========================================================  
echo Step 1 : Configuration management
echo    * OEM Keys generation:
echo        Warning: Default keys must NOT be used in a product.
echo        Run Keygen script to randomly regenerate your own keys (Keys/*.pem and OEMiROT_Boot/Src/keys.c)
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul

:: ========================================================= Images generation steps ========================================================  
:cubemx
if "%isGeneratedByCubeMX%" == "true" (
    echo Step 1 : Configuration management
    echo    * OEM Keys were created during CubeMX code generation (Keys/*.pem and OEMiROT_Boot/Src/keys.c)
    echo        Press any key to continue...
    echo.
    if [%1] neq [AUTO] pause >nul
)
echo Step 2 : Images generation
echo    * Boot firmware image generation
echo        Open the OEMiROT_Boot project with preferred toolchain and rebuild all files.
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul
::update xml file
if "%isGeneratedByCubeMX%" == "true" goto :cubemx1

:cubemx1
echo    * Code firmware image generation
if "%isGeneratedByCubeMX%" == "true" (
    echo        If the configuration of OEMiROT_Boot project has been updated, reload and regenerate STM32CubeMX application project.
    echo        Open the regenerated application project with preferred toolchain and rebuild all files.
) else (
    echo        Open the OEMiROT_Appli_TrustZone project with your preferred toolchain
    echo        Rebuild all files. The appli_enc_sign.hex file is generated with the postbuild command
)
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul
if "%isGeneratedByCubeMX%" == "true" goto :cubemx2
echo    * Data generation (if Data image is enabled)
echo        Select OEMiROT_Data_Image.xml(Default path is \ROT\Provisioning\OEMiROT\OEMiROT_Data_Image.xml)
echo        Generate the data_enc_sign.hex image
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul
:cubemx2
:: ========================================================= Board provisioning steps =======================================================  
echo Step 3 : Provisioning password
echo    * BOOT0 pin should be disconnected from VDD
echo        (NUCLEO-H503RB: disconnect CN7/pin5 from CN7/pin7)
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul

:: ================================================= Option Bytes and flash programming =====================================================  
set "action=Programming the option bytes and flashing the images ..."
set current_log_file=%ob_flash_log%
set "command=start /w /b call %ob_flash_programming% AUTO"
echo    * %action%
%command% > %ob_flash_log%

if !errorlevel! neq 0 goto :step_error

echo        Successful option bytes programming and images flashing
echo        (see %ob_flash_log% for details)
echo.

:: ================================================= Final product state selection ==========================================================
set "action=Password provisioning"
echo    * %action%
echo        WARNING: The password is definitively provisioned (in OTP), and cannot be changed even after regression
echo        Once provisioned, be sure not to change the password anymore (will not work)
echo        Press any key to continue...
echo.
pause >nul
goto create_password

:define_product_state
set "action=Define final product state value"
echo    * %action%
set /p "product_state=      %USERREG% [ OPEN | PROVISIONED | CLOSED | LOCKED ]: "

if /i "%product_state%" == "OPEN" (
echo.
set ps_value=0xED
goto connect_boot0 
)

if /i "%product_state%" == "PROVISIONED" (
echo.
set ps_value=0x2E
goto set_provisionning_ps
)

if /i "%product_state%" == "CLOSED" (
echo.
set ps_value=0x72
goto set_provisionning_ps
)

if /i "%product_state%" == "LOCKED" (
echo.
set ps_value=0x5C
goto set_provisionning_ps
)

echo        WRONG product state selected
set current_log_file="./*.log files "
echo;
goto define_product_state

:: ======================================================= Create board password =========================================================   
:create_password
echo    * Password board creation
echo        Create a "user_password.bin" file.(Default path is \ROT_Provisioning\DA\user_password.bin)
echo        WARNING: This step must be done at least one time to generate the password
echo        If the content of the user_password is correct the next step could be executed
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul

set "action=Creating user password"
set current_log_file=%create_password_log%
set "command=start /w /b call %create_password% AUTO"
echo    * %action%
%command% > %create_password_log%

if !errorlevel! neq 0 goto :step_error

echo        User password correctly created
echo        (see %create_password_log% for details)
echo.
goto define_product_state

:: ========================================= Product State configuration and Provisioning steps ==========================================   
:: Connect BOOT0 pin to VDD 
:connect_boot0
if /i "%password%" == "y" goto :nopassword_step
echo    * BOOT0 pin should be connected to VDD
echo        (NUCLEO-H503RB: connect CN7/pin5 with CN7/pin7)
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul
goto provisioning_step

:: Provisioning execution 
:set_provisionning_ps
set "action=Setting the product state PROVISIONING"
set current_log_file=%state_change_log%
echo    * %action%
set "command=%stm32programmercli% %connect_no_reset% -ob PRODUCT_STATE=0x17"
::%stm32programmercli% %connect_reset% > %state_change_log%
echo %command% > %state_change_log%
%command% >> %state_change_log%
if !errorlevel! neq 0 goto :step_error
echo.
if /i "%password%" == "y" goto :set_final_ps
goto provisioning_step

:: Set the final product state of the STM32H5 product
:set_final_ps
set "action=Setting the final product state %product_state%"
set current_log_file=%state_change_log%
echo    * %action%
set "command=%stm32programmercli% %connect_no_reset% -ob PRODUCT_STATE=%ps_value%"
echo %command% >> %state_change_log%
%command% >> %state_change_log%
echo.
:: In the final product state, the connection with the board is lost and the return value of the command cannot be verified
goto final_execution

:: Provisioning the obk files step
:provisioning_step
set "action=Provisionning the password ..."
set current_log_file=%password_programming_log%
echo    * %action%
set "command=start /w /b call %password_programming% AUTO"
%command% > %password_programming_log%
if !errorlevel! neq 0 goto :step_error

echo        Successful password provisioning
echo        (see %password_programming_log% for details)
echo.
if /i "%product_state%" NEQ "OPEN" goto :set_final_ps

:nopassword_step
echo    * BOOT0 pin should be disconnected from VDD
echo        (NUCLEO-H503RB: disconnect CN7/pin5 from CN7/pin7)
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul

:: ============================================================= End functions =============================================================  
:: All the steps to set the STM32H5 product were executed correctly
:final_execution
echo =====
echo ===== The board is correctly configured.
if "%isGeneratedByCubeMX%" == "true" goto :no_menu
echo ===== Connect UART console (115200 baudrate) to get application menu.

:no_menu
echo =====
cmd /k
exit 0

:: Error when external script is executed
:step_error
echo.
echo =====
echo ===== Error while executing "%action%".
echo ===== See %current_log_file% for details. Then try again.
echo =====
cmd /k
exit 1

