#! /bin/bash
# Copyright 2019-2025 NXP
# SPDX-License-Identifier: BSD-3-Clause
# The script for writing the image into MIMXRT1060  

# 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=/Applications/SEC_Provi_25.12/MCUXpresso Secure Provisioning Tool 25.12.app/Contents/Frameworks"
fi
if ! [ -d "$SPT_INSTALL_BIN" ]; then
  echo "FAILURE: Directory not found: $SPT_INSTALL_BIN"
  exit 2
fi
#  - SPSDK debug log, absolute path
if [ -z "${SPSDK_DEBUG_LOG_FILE}" ]; then
  export "SPSDK_DEBUG_LOG_FILE=${SPT_WORKSPACE}/logs/spsdk-debug.log"
fi

# Use parameter: "sdphost_connect <connection_param>" to use custom connection parameters for sdphost
# Use parameter: "blhost_connect <connection_param>" to use custom connection parameters for blhost
#     <connection_param> should be in format "-p COMx[,baud]" or "-u VID,PID"
# Use parameter: "manufacturing_task_no index" to set number/index of the manufacturing task (to avoid same filename created from two tasks)
# Use parameter: "set_sdphost_baud_rate <baud_rate>" to change baud rate from default (115200) to specfied speed
# Use parameter: "erase_all" to perform an erase of the entire flash memory instead erasing only regions that will be written

# Default connection parameters
export "sdphost_connect=-u 0x1FC9,0x0135"
export "set_sdphost_baud_rate=115200"
export "blhost_connect=-u 0x15A2,0x0073"
export "manufacturing_task_no="

echo "### Parse input arguments ###"
i=1
while (( i<=$#)); do
    param=${!i}
    case $param in
        "blhost_connect")
            i=$((i+1))
            export "blhost_connect=${!i}"
            ;;
        "sdphost_connect")
            i=$((i+1))
            export "sdphost_connect=${!i}"
            ;;
        "manufacturing_task_no")
            i=$((i+1))
            export "manufacturing_task_no=${!i}"
            ;;
        "erase_all")
            export "erase_all=1"
            ;;
        "set_sdphost_baud_rate")
            i=$((i+1))
            export "set_sdphost_baud_rate=${!i}"
            ;;
        *)
            echo "ERROR: Unsupported argument ${!i}"
            exit 2
    esac
    i=$((i+1))
done

# Used command line utilities
export "blhost=${SPT_INSTALL_BIN}/tools_scripts/blhost_spsdk_lnx_wrapper.sh"
export "sdphost=${SPT_INSTALL_BIN}/tools_scripts/sdphost_spsdk_lnx_wrapper.sh"

# SUBROUTINE hook script execution, accepts one argument "hook step", if specified it is passed into hook script, when not specified call context hook script
hook_execute()
{
    if [ $# -eq 0 ]; then
        if [ -x "${SPT_WORKSPACE}/hooks/write_context_lnx.sh" ]; then
            source "${SPT_WORKSPACE}/hooks/write_context_lnx.sh"
            if [ $? -ge 1 ]; then
                exit 2
            fi
        fi
    else
        if [ -x "${SPT_WORKSPACE}/hooks/write_lnx.sh" ]; then
            "${SPT_WORKSPACE}/hooks/write_lnx.sh" $1
            if [ $? -ge 1 ]; then
                exit 2
            fi
        fi
    fi
}

# Call hook that can modify environment variables
hook_execute
# hook executed before any other command is executed
hook_execute started

echo "### Check presence of FlashLoader ###"
"$blhost" $blhost_connect -j -- get-property 1 0 > /dev/null 2> /dev/null
if [ $? -ge 2 ]; then
    echo "### FlashLoader is not running yet, download and run it ###"

    if [ "$set_sdphost_baud_rate" != "115200" ]; then
        if [ "$set_sdphost_baud_rate" == "" ]; then
            echo "set_sdphost_baud_rate is not defined"
            exit 2
        fi
        echo "### Change speed of communication if uart is used at non-default speed ###"
        export "sdphost_connect_default_speed=${sdphost_connect/$set_sdphost_baud_rate/115200}"
        "$sdphost" $sdphost_connect_default_speed -j -- error-status
        if [ $? -ne 2 ]; then
            "$sdphost" $sdphost_connect_default_speed set-baudrate $set_sdphost_baud_rate
        fi
        "$sdphost" $sdphost_connect -j -- error-status
        if [ $? -ge 2 ]; then
            "$sdphost" $sdphost_connect -j -- error-status
            if [ $? -ge 2 ]; then
                exit 2
            fi
        fi
    fi

    echo "### Check communication with target bootloader ###"
    "$sdphost" $sdphost_connect -j -- error-status
    LAST_EXIT=$?
    if [ $LAST_EXIT -ge 2 ]; then
        exit 2
    fi

    echo "### Write FlashLoader ###"
    "$sdphost" $sdphost_connect -j -- write-file 0x20001C00 "${SPT_WORKSPACE}/bootable_images/unsigned_MIMXRT1060_flashloader.bin"
    if [ $? -ge 2 ]; then
        exit 2
    fi

    echo "### Start FlashLoader ###"
    "$sdphost" $sdphost_connect -j -- jump-address 0x20001C00
    if [ $? -ge 2 ]; then
        exit 2
    fi

    echo "### Waiting FlashLoader to be initialized for 3 seconds ###"
    echo "### Timeout wait value can be adjusted from Preferences ###"
    sleep 3

    echo "### Check presence of FlashLoader ###"
    "$blhost" $blhost_connect -j -- get-property 1 0
    if [ $? -ge 2 ]; then
        exit 2
    fi
fi
# hook executed after write of the flashloader is done
hook_execute flashloader_written

any_burn_fuses_phase1=0

echo "### Configure FlexSPI NOR memory using options on address 0x2000 ###"
"$blhost" $blhost_connect -j -- fill-memory 0x2000 4 0xC0000008 word
if [ $? -ge 2 ]; then
    exit 2
fi
"$blhost" $blhost_connect -j -- configure-memory 9 0x2000
if [ $? -ge 2 ]; then
    exit 2
fi
# hook executed after external memory configuration is done
hook_execute configure_ext_memory_done

echo "### Erase memory before writing image ###"
if [ "$erase_all" = "1" ]; then
    "$blhost" $blhost_connect -j -- flash-erase-all 9
    if [ $? -ge 2 ]; then
        exit 2
    fi
else
    "$blhost" $blhost_connect -j -- flash-erase-region 0x60000000 1799848 0
    if [ $? -ge 2 ]; then
        exit 2
    fi
fi
# hook executed after erase of the memory is done
hook_execute erase_done

echo "### Create Flash Configuration Block (FCB) using option on address 0x2000 ###"
"$blhost" $blhost_connect -j -- fill-memory 0x2000 4 0xF000000F word
if [ $? -ge 2 ]; then
    exit 2
fi
"$blhost" $blhost_connect -j -- configure-memory 9 0x2000
if [ $? -ge 2 ]; then
    exit 2
fi
# hook executed after creation of FCB in the memory is done
hook_execute create_fcb_done

echo "### Write image ###"
"$blhost" $blhost_connect -j -- write-memory 0x60001000 "${SPT_WORKSPACE}/bootable_images/disting_NT.bin" 0
if [ $? -ge 2 ]; then
    exit 2
fi
# hook executed after write of the image is done
hook_execute image_written
# hook executed after all steps of the script were executed
hook_execute finished