#!/bin/bash

current_dir="$(pwd)/"

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

echo "###########################################"
echo "# 1- Disable security"
echo "###########################################"

function write_ob () {
    len_ob=0
    option_byte_name=()
    option_byte_val=()
    while [[ $# -gt 1 ]]; do
        echo $1 $2
        if [[ ! ( -z "$1" || -z "$2" ) ]]
        then
            option_byte_name+=($1)
            option_byte_val+=($2)
            len_ob=$(($len_ob+1))
        fi
        shift 2
    done
    # Check if the number of arguments is odd
    if [[ $# -eq 1 ]]; then
        echo "The last argument ($1) is not paired and will be ignored."
    fi
    len_ob=$(($len_ob-1))
    obj_str=""
    for i in $(seq 0 $len_ob)
    do
        obj_str="${option_byte_name[$i]}=${option_byte_val[$i]} $obj_str"
    done
    echo $obj_str
    #Writing byte
    $STM_CUBEPROG_PATH -c port=SWD mode=UR -q -ob "$obj_str" > /dev/null 2>&1
    if [[ ${?} -ne 0 ]]; then   
        echo "Error: Command write -ob $obj_str Failed"
        exit 1
    fi
    #Checking byte
    $STM_CUBEPROG_PATH -c port=SWD mode=UR -q -ob displ > temp.txt
    for i in $(seq 0 $len_ob)
    do  
        for read_ob in $(grep -oP "\s${option_byte_name[$i]}\s*:\s*0x[0-9A-Fa-f]+" temp.txt | awk '{print $3}')
        do
            if [[ $read_ob -ne ${option_byte_val[$i]} ]]
            then
                echo -e "Error: Option Byte ${option_byte_name[$i]} not modified as expected: read:$read_ob expected:${option_byte_val[$i]}"
                rm -f temp.txt  > /dev/null 2>&1
                exit 1
            fi
        done
    done

    rm -f temp.txt  > /dev/null 2>&1
}

echo "RDP: Read Out protection Level 1"
write_ob RDP 0xBB

echo "RDP+ESE: Read Out protection Level 0 + Security disabled"
write_ob RDP 0xAA ESE 0x0

echo "WRP: Write Protection disabled"
write_ob WRP1A_STRT 0x7F WRP1A_END 0x0 WRP1B_STRT 0x7F WRP1B_END 0x0

echo "------ User Configuration ------"
echo "nRST: No reset generated when entering the Stop/Standby/Shutdown modes"
write_ob nRST_STOP 0x1 nRST_STDBY 0x1 nRST_SHDW 0x1

echo "WDG_SW: Software window/independent watchdogs"
write_ob WWDG_SW 0x1 IWDG_SW 0x1

echo "IWDG: Independent watchdog counter frozen in Stop/Standby modes"
write_ob IWGD_STDBY 0x0 IWDG_STOP 0x0

echo "BOOT: CPU1+CPU2 CM0+ Boot lock disabled"
write_ob BOOT_LOCK 0x0 C2BOOT_LOCK 0x0

echo "------ Security Configuration ------"
echo "HDPAD: User Flash hide protection area access disabled"
write_ob HDPAD 0x1

echo "SPISD: SPI3 security disabled"
write_ob SUBGHSPISD 0x1

echo "SBRSA: Reset default value of SRAM Start address secure"
write_ob SNBRSA 0x1F SBRSA 0x1F

echo "SBRV: Reset default value of CPU2 Boot start address"
write_ob SBRV 0x8000
