@echo off
@rem Copyright 2023-2025 NXP
@rem SPDX-License-Identifier: BSD-3-Clause
@rem Script to configure shadow registers on RT7xx and reset
@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!"
  FOR %%i in ("!SPT_WORKSPACE!") DO (
    SET "SPT_WORKSPACE=%%~dpi"
  )
  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 /B 2
)
@rem - Absolute path to SPT installation directory
if "%SPT_INSTALL_BIN%"=="" (
  SET "SPT_INSTALL_BIN=C:\nxp\SEC_Provi_25.09\bin\_internal"
)
if not exist "%SPT_INSTALL_BIN%\" (
  @echo FAILURE: Directory not found "%SPT_INSTALL_BIN%"
  exit /B 2
)
@rem - SPSDK debug log, absolute path
if "%SPSDK_DEBUG_LOG_FILE%"=="" (
  SET "SPSDK_DEBUG_LOG_FILE=%SPT_WORKSPACE%\logs\spsdk-debug.log"
)


@rem Used command-line utilities
set "shadowregs=%SPT_INSTALL_BIN%\tools\spsdk\shadowregs.exe"
set "nxpdebugmbox=%SPT_INSTALL_BIN%\tools\spsdk\nxpdebugmbox.exe"

@echo Start debug session, so we can write shadow registers into processor in ISP mode
@echo call "%nxpdebugmbox%" -i pyocd -s LK5FAWWDFXLWZ cmd -f mimxrt798s start-debug-session
call "%nxpdebugmbox%" -i pyocd -s LK5FAWWDFXLWZ cmd -f mimxrt798s start-debug-session
if errorlevel 1 exit /B 2

@echo Load shadow registers into processor
@echo call "%shadowregs%" -i pyocd -s LK5FAWWDFXLWZ -f mimxrt798s loadconfig -c "%SPT_WORKSPACE%\gen_scripts\sr_config.yaml"
call "%shadowregs%" -i pyocd -s LK5FAWWDFXLWZ -f mimxrt798s loadconfig -c "%SPT_WORKSPACE%\gen_scripts\sr_config.yaml"
if errorlevel 1 exit /B 2

@echo Reset, so the shadow registers are applied
@echo call "%shadowregs%" -i pyocd -s LK5FAWWDFXLWZ -f mimxrt798s reset
call "%shadowregs%" -i pyocd -s LK5FAWWDFXLWZ -f mimxrt798s reset
if errorlevel 1 exit /B 2