@echo off
@rem Copyright 2020-2024 NXP
@rem SPDX-License-Identifier: BSD-3-Clause
@rem Script to build MCX A14x/A15x Master Boot Image using nxpimage tool

@rem Environment variables - absolute paths simplifying re-use of the script on another machine
@rem  - Absolute path to SPT workspace (it is recommended to copy/move all user files in this workspace)
SETLOCAL ENABLEDELAYEDEXPANSION
if "%SPT_WORKSPACE%"=="" (
  SET "SPT_WORKSPACE=%~dp0"
  SET "SPT_WORKSPACE=!SPT_WORKSPACE:~0,-1!"
)
ENDLOCAL & SET "SPT_WORKSPACE=%SPT_WORKSPACE%"
if not exist "%SPT_WORKSPACE%\" (
  @echo FAILURE: Directory not found "%SPT_WORKSPACE%"
  exit 2
)
@rem  - Absolute path to SPT installation directory
if "%SPT_INSTALL_BIN%"=="" (
  SET "SPT_INSTALL_BIN=C:\nxp\MCUX_Provi_v9\bin\_internal"
)
if not exist "%SPT_INSTALL_BIN%\" (
  @echo FAILURE: Directory not found "%SPT_INSTALL_BIN%"
  exit 2
)

@rem Used command line utilities
SET "nxpimage=%SPT_INSTALL_BIN%\tools_scripts\nxpimage_spsdk_win_wrapper.bat"
SET "pfr=%SPT_INSTALL_BIN%\tools\spsdk\pfr.exe"

if not exist "%SPT_WORKSPACE%\bootable_images\." (
    mkdir "%SPT_WORKSPACE%\bootable_images"
    if errorlevel 1 exit 2
)
if exist "%SPT_WORKSPACE%\hooks\build_win.bat" (
    @rem hook executed before any other command is executed
    call "%SPT_WORKSPACE%\hooks\build_win.bat" started
    if errorlevel 1 exit 2
)

@echo ### Create Master Boot Image using nxpimage tool ###
call "%nxpimage%" mbi export -c "%SPT_WORKSPACE%\configs\mbi_config.yaml"
if errorlevel 2 exit 2
if exist "%SPT_WORKSPACE%\hooks\build_win.bat" (
    @rem hook executed after build of bootable image is done
    call "%SPT_WORKSPACE%\hooks\build_win.bat" build_image_done
    if errorlevel 1 exit 2
)

@echo ### Create CMPA page - binary ###
@echo %pfr% generate-binary -c %SPT_WORKSPACE%\configs\cmpa.yaml -o %SPT_WORKSPACE%\configs\cmpa.bin
"%pfr%" generate-binary -c "%SPT_WORKSPACE%\configs\cmpa.yaml" ^
        -o "%SPT_WORKSPACE%\configs\cmpa.bin"
if errorlevel 1 (
    exit 2
)
if exist "%SPT_WORKSPACE%\hooks\build_win.bat" (
    @rem hook executed after CFPA or/and CMPA page generation is done
    call "%SPT_WORKSPACE%\hooks\build_win.bat" pfr_generation_done
    if errorlevel 1 exit 2
)
if exist "%SPT_WORKSPACE%\hooks\build_win.bat" (
    @rem hook executed after all steps of the script were executed
    call "%SPT_WORKSPACE%\hooks\build_win.bat" finished
    if errorlevel 1 exit 2
)