#! /bin/bash 
# Copyright 2024 NXP
# SPDX-License-Identifier: BSD-3-Clause
# Environment variables - absolute paths simplifying re-use of the script on another machine
#  - Absolute path to SPT workspace (it is recommended to copy/move all user files in this workspace)
if [ -z "${SPT_WORKSPACE}" ]; then
  export "SPT_WORKSPACE=$(cd "$(dirname "$0")"; pwd -P)"
  export "SPT_WORKSPACE=$(dirname "$SPT_WORKSPACE")"
fi
if ! [ -d "$SPT_WORKSPACE" ]; then
  echo "FAILURE: Directory not found: $SPT_WORKSPACE"
  exit 2
fi
#  - Absolute path to SPT installation directory
if [ -z "${SPT_INSTALL_BIN}" ]; then
  export "SPT_INSTALL_BIN=C:/Users/nxf47345/Desktop/securep_b240623/_internal"
fi
if ! [ -d "$SPT_INSTALL_BIN" ]; then
  echo "FAILURE: Directory not found: $SPT_INSTALL_BIN"
  exit 2
fi

echo "Sign the application using imgtool"
export "imgtool=${SPT_INSTALL_BIN}/tools/imgtool/imgtool"
export "nxpimage=${SPT_INSTALL_BIN}/tools_scripts/nxpimage_spsdk_mac_wrapper.sh"

# Convert image format
"$nxpimage" utils binary-image convert -i "C:/Users/nxf47345/OneDrive - NXP/work/MCX/MCX A10/software/a10_secure_boot/frdmmcxa153_ota_mcuboot_basic/Debug/frdmmcxa153_ota_mcuboot_basic.axf" -f BIN -o "${SPT_WORKSPACE}/bootable_images/frdmmcxa153_ota_mcuboot_basic_converted_mcuboot_app_image.bin"
if [ $? -ge 2 ]; then
    exit 2
fi

"$imgtool" sign \
  --version 1.0 \
  --header-size 0x200 \
  --pad-header \
  --slot-size 0xC000 \
  --align 16 \
  --pad \
  --confirm \
  --key "C:/Users/nxf47345/OneDrive - NXP/work/MCX/MCX A10/software/a10_secure_boot/frdmmcxa153_mcuboot_opensource/keys/sign-ecdsa-p256-priv.pem" \
  "${SPT_WORKSPACE}/bootable_images/frdmmcxa153_ota_mcuboot_basic_converted_mcuboot_app_image.bin" \
  "${SPT_WORKSPACE}/bootable_images/frdmmcxa153_ota_mcuboot_basic_signed.bin"
if [ $? -ge 1 ]; then
    exit 2
fi

echo "Successfuly signed the application using imgtool: ${SPT_WORKSPACE}/bootable_images/frdmmcxa153_ota_mcuboot_basic_signed.bin"