#!/bin/sh
erase_cmd="pyocd erase -c -t lcm32f067 --pack ~/.local/share/cmsis-pack-manager/Keil/LCM32F0xx_DFP/0.4.70.pack"
flash_cmd="pyocd flash -t lcm32f067 --pack ~/.local/share/cmsis-pack-manager/Keil/LCM32F0xx_DFP/0.4.70.pack build/*.hex"
idcode_cmd="pyocd cmd -t lcm32f067 --pack ~/.local/share/cmsis-pack-manager/Keil/LCM32F0xx_DFP/0.4.70.pack -c status"

# sudo apt install libcanberra-gtk-module libcanberra-gtk3-module
complete_cmd="canberra-gtk-play -i complete"
waining_cmd="canberra-gtk-play -i dialog-warning"

# complete_cmd="sleep 0"
# waining_cmd="sleep 0"

while true
do
    echo -ne "\r[ ] Checking Core...              "
    while true
    do
        core_log=$( $idcode_cmd 2>&1 )
        echo "$core_log" | grep -q "Core"
        if [ $? -eq 0 ]; then
            echo -ne "\r[X] MCU connected.Next to flash...    \033[K"
            break
        fi

        now=$(date "+%Y-%m-%d %H:%M:%S")
        echo -ne "\r[✓] $now  Waiting for MCU Connect...    \033[K"
        sleep 0.1
    done

    echo -ne "\r[ ] Erasing...                    "
    erase_log=$( $erase_cmd 2>&1 )
    echo "$erase_log" | grep -q "Chip erase complete"
    if [ $? -ne 0 ]; then
        echo -ne "\r[X] Erase failed. Restarting...   "
        ($waining_cmd 2)
        sleep 0.1
        continue
    fi

    echo -ne "\r[ ] Flashing...                   "
    flash_log=$( $flash_cmd 2>&1 )
    echo "$flash_log" | grep -q "programmed .* bytes"
    if [ $? -ne 0 ]; then
        echo -ne "\r[X] Flash failed. Restarting...   "
        ($waining_cmd 2)
        sleep 0.1
        continue
    fi



    now=$(date "+%Y-%m-%d %H:%M:%S")
    echo -e "\r[✓] $now  Erase and flash succeeded!  "
    ($complete_cmd 2)
    
    echo -ne "\r[ ] Checking Core...              "
    while true
    do
        core_log=$( $idcode_cmd 2>&1 )
        echo "$core_log" | grep -q "Core"
        if [ $? -ne 0 ]; then
            echo -ne "\r[X] MCU removed, restarting...    \033[K"
            sleep 0.1
            break
        fi

        now=$(date "+%Y-%m-%d %H:%M:%S")
        echo -ne "\r[✓] $now  MCU still connected.    \033[K"
    done
done
