#! /bin/bash
# Copyright 2020-2024 NXP
# SPDX-License-Identifier: BSD-3-Clause
# Script to build MCX A14x/A15x Master Boot Image using nxpimage tool

# 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)"
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:/nxp/MCUX_Provi_v9/bin/_internal"
fi
if ! [ -d "$SPT_INSTALL_BIN" ]; then
  echo "FAILURE: Directory not found: $SPT_INSTALL_BIN"
  exit 2
fi

# Used command line utilities
export "nxpimage=${SPT_INSTALL_BIN}/tools_scripts/nxpimage_spsdk_lnx_wrapper.sh"
export "pfr=${SPT_INSTALL_BIN}/tools/spsdk/pfr"

mkdir -p "${SPT_WORKSPACE}/bootable_images"
if [ $? -ge 1 ]; then
    exit 2
fi
if [ -x "${SPT_WORKSPACE}/hooks/build_lnx.sh" ]; then
    # hook executed before any other command is executed
    "${SPT_WORKSPACE}/hooks/build_lnx.sh" started
    if [ $? -ge 1 ]; then
        exit 2
    fi
fi

echo '### Create Master Boot Image using nxpimage tool ###'
"$nxpimage" mbi export -c "${SPT_WORKSPACE}/configs/mbi_config.yaml"
if [ $? -ge 2 ]; then
    exit 2
fi
if [ -x "${SPT_WORKSPACE}/hooks/build_lnx.sh" ]; then
    # hook executed after build of bootable image is done
    "${SPT_WORKSPACE}/hooks/build_lnx.sh" build_image_done
    if [ $? -ge 1 ]; then
        exit 2
    fi
fi

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 [ $? -ge 1 ]; then
    exit 2
fi
if [ -x "${SPT_WORKSPACE}/hooks/build_lnx.sh" ]; then
    # hook executed after CFPA or/and CMPA page generation is done
    "${SPT_WORKSPACE}/hooks/build_lnx.sh" pfr_generation_done
    if [ $? -ge 1 ]; then
        exit 2
    fi
fi
if [ -x "${SPT_WORKSPACE}/hooks/build_lnx.sh" ]; then
    # hook executed after all steps of the script were executed
    "${SPT_WORKSPACE}/hooks/build_lnx.sh" finished
    if [ $? -ge 1 ]; then
        exit 2
    fi
fi