#!/bin/bash

current_dir="$(pwd)/"
binary_file="$current_dir../STM32CubeIDE/Release/*.elf"

echo "###########################################"
echo "# 0- Set all global variables"
echo "###########################################"
source ./set-env.sh

echo "###########################################"
echo "# 1- Disable security"
echo "###########################################"
source ./disable_security.sh
if [[ $? -ne 0 ]]; then 
    echo "Error disabling security"
    exit 1
fi

echo "###########################################"
echo "# 2- Erase Memory"
echo "###########################################"
$STM_CUBEPROG_PATH -c port=SWD mode=UR -e all
if [[ $? -ne 0 ]]; then 
    echo "Error: Full Memory Erase Failure"
    exit 1
fi

echo "###########################################"
echo "# 3- Download binaries"
echo "###########################################"

function download_file () {
    if [[ ! -f $1 ]]; then
        echo "Error: $1 File not found. Check your build log..."
        exit 1
    fi

    if [[ $3 = "" ]]
    then
        echo "Downloading $2 binary ..."
        $STM_CUBEPROG_PATH -c port=SWD mode=UR -d $1 -v
    else
        echo "Downloading $2 binary @$3 ..."
        $STM_CUBEPROG_PATH -c port=SWD mode=UR -d $1 $3 -v
    fi

    if [[ $? -ne 0 ]]; then 
        echo "Error: Download failed"
        exit 1
    fi

    $STM_CUBEPROG_PATH -c port=SWD mode=HOTPLUG -hardRst
    if [[ $? -ne 0 ]]; then 
        echo "Error: Reset after download failed"
        exit 1
    fi

    echo "Done!"
}

download_file $binary_file $(basename $binary_file)

echo "Power cycle the board (unplug/plug USB cable) to apply the BFU security mechanisms..."
exit 0
