@ECHO OFF
:: Getting the CubeProgammer_cli path
call ../env.bat
set cube_fw_path=%cube_fw_path:"=%

:: Enable delayed expansion
setlocal EnableDelayedExpansion

set "projectdir=%~dp0"
set isGeneratedByCubeMX=%PROJECT_GENERATED_BY_CUBEMX%

:: CubeProgammer path and input files
set ob_flash_programming="ob_flash_programming.bat"
set obkey_programming="obkey_programming.bat"

set ob_flash_log="ob_flash_programming.log"
set obkey_programming_log="obkey_programming.log"
set provisioning_log="provisioning.log"

set "flash_layout=%cube_fw_path%\Projects\STM32H573I-DK\Applications\ROT\OEMiROT_Boot\Inc\flash_layout.h"

:: Get config updated by OEMiROT_Boot
set tmp_file=%projectdir%/img_config.bat
set s_data_xml="%projectdir%Images\OEMiROT_S_Data_Image.xml"
set ns_data_xml="%projectdir%Images\OEMiROT_NS_Data_Image.xml"
set s_data_init_xml="%projectdir%Images\OEMiROT_S_Data_Init_Image.xml"
set ns_data_init_xml="%projectdir%Images\OEMiROT_NS_Data_Init_Image.xml"

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

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_TrustZone=% (
echo =====
echo ===== Wrong Boot path: %oemirot_boot_path_project%
echo ===== please modify the env.bat to set the right path
goto step_error
)

:: ====================================================== STM32H5 product preparation ======================================================
:: =============================================== Steps to create the OEMiROT_Config.obk file ==============================================
echo Step 1 : Configuration management
echo    * OEMiROT_Config.obk generation:
echo        From TrustedPackageCreator (OBkey tab in Security panel).
echo        Select OEMiROT_Config.xml(Default path is \ROT_Provisioning\OEMiROT\Config\OEMiROT_Config.xml)
echo        Warning: Default keys must NOT be used in a product. Make sure to regenerate your own keys!
echo        Update the configuration (if/as needed) then generate OEMiROT_Config.obk file
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul
:: =============================================== Steps to create the DA_Config.obk file ===================================================
echo    * DA_Config.obk generation:
echo        Warning: Default keys must NOT be used in a product. Make sure to regenerate your own keys!
echo        From TrustedPackageCreator (Debug Authentication - Certificate Generation tab in Security panel),
echo        update the keys(s) (in \ROT_Provisioning\DA\Keys) and permissions (if/as needed)
echo        then regenerate the certificate(s)
echo        From TrustedPackageCreator (OBkey tab in Security panel),
echo        Select DA_Config.xml (in \ROT_Provisioning\DA\Config)
echo        Update the configuration (if/as needed) then generate DA_Config.obk file
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    * OEMiROT_Config.obk was created during CubeMX code generation
    echo.
    echo    * DA_Config.obk was created during CubeMX code generation
    echo        Press any key to continue...
    echo.
    if [%1] neq [AUTO] pause >nul
)
:: Configure OEMIROT_Boot project as OEMIROT
set "command=%python%%applicfg% setdefine -a comment -n OEMUROT_ENABLE -v 1 %flash_layout%"
%command%
IF !errorlevel! NEQ 0 goto :step_error
echo Step 2 : Images generation
echo    * Boot firmware image generation
echo        Open the OEMiROT_Boot project with preferred toolchain and rebuild all files.
echo        At this step the project is configured for OEMiROT boot path.
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul
::update xml file
if "%isGeneratedByCubeMX%" == "true" goto :cubemx1
call %tmp_file%

: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 the Secure project. The rot_tz_s_app_init_sign.hex and rot_tz_s_app_enc_sign.hex files are
    echo        generated with the postbuild command.
    echo        Rebuild the NonSecure project. The rot_tz_ns_app_init_sign.hex and rot_tz_ns_app_enc_sign.hex files are
    echo        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 secure generation (if Data secure image is enabled)
echo        Select OEMiRoT_S_Data_Image.xml(Default path is \ROT_Provisioning\OEMiROT\Images\OEMiRoT_S_Data_Image.xml)
echo        Generate the s_data_enc_sign.hex image
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul
if "%s_data_image_number%" == "0" (goto :no_s_data)
%stm32tpccli% -pb %s_data_xml% >> %provisioning_log%
if !errorlevel! neq 0 goto :step_error
%stm32tpccli% -pb %s_data_init_xml% >> %provisioning_log%
if !errorlevel! neq 0 goto :step_error
:no_s_data

echo    * Data non secure generation (if Data non secure image is enabled)
echo        Select OEMiROT_NS_Data_Image.xml(Default path is \ROT_Provisioning\OEMiROT\Images\OEMiROT_NS_Data_Image.xml)
echo        Generate the ns_data_enc_sign.hex image
echo        Press any key to continue...
echo.
if [%1] neq [AUTO] pause >nul
if "%ns_data_image_number%" == "0" (goto :no_ns_data)
%stm32tpccli% -pb %ns_data_xml% >> %provisioning_log%
if !errorlevel! neq 0 goto :step_error
%stm32tpccli% -pb %ns_data_init_xml% >> %provisioning_log%
if !errorlevel! neq 0 goto :step_error
:no_ns_data
:cubemx2
:: ========================================================= Board provisioning steps =======================================================
echo Step 3 : Provisioning
echo    * BOOT0 pin should be disconnected from VDD
echo        (STM32H573I-DK: set SW1 to position 0)
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%

set ob_flash_error=!errorlevel!
::type %ob_flash_log%
if %ob_flash_error% 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 ===========================================================
:product_state_choice
for /f %%A in ('"prompt $H & echo on & for %%B in (1) do rem"') do set "BS=%%A"
set "action=Define product state value"
echo    * %action%
if [%1] neq [AUTO] (
    set /p "product_state=%BS%       [ OPEN | PROVISIONED | TZ-CLOSED | CLOSED | LOCKED ]: "
) else (
    set "product_state=%2%"
    if /i "%product_state%" == "OPEN" (
    echo        Product state OPEN not supported in AUTO mode
    goto step_error
    )
)

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%" == "TZ-CLOSED" (
echo.
set ps_value=0xC6
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 product_state_choice

:: ================================================ Option Bytes and flash programming ======================================================
:: Connect BOOT0 pin to VDD
:connect_boot0
echo    * BOOT0 pin should be connected to VDD
echo        (STM32H573I-DK: set SW1 to position 1)
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=%provisioning_log%
echo    * %action%
set "command=%stm32programmercli% %connect_no_reset% -ob PRODUCT_STATE=0x17"
echo %command% > %provisioning_log%
%command% >> %provisioning_log%
if !errorlevel! neq 0 goto :step_error
echo.
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=%provisioning_log%
echo    * %action%
set "command=%stm32programmercli% %connect_no_reset% -ob PRODUCT_STATE=%ps_value%"
echo %command% >> %provisioning_log%
%command% >> %provisioning_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 .obk files ..."
set current_log_file=%obkey_programming_log%
echo    * %action%
set "command=start /w /b call %obkey_programming% AUTO"
%command% > %obkey_programming_log%
set obkey_prog_error=!errorlevel!
if %obkey_prog_error% neq 0 goto :step_error

echo        Successful obk provisioning
echo        (see %obkey_programming_log% for details)
echo.

if /i "%product_state%" NEQ "OPEN" goto :set_final_ps

echo    * BOOT0 pin should be disconnected from VDD
echo        (STM32H573I-DK: set SW1 to position 0)
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 =====
if [%1] neq [AUTO] 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 =====
if [%1] neq [AUTO] cmd /k
exit 1
