#!/bin/bash
MAKEFILE_PATH="STM32CubeIDE/Release/"
UPDATE_SCRIPTS_PATH="Scripts/"
UPDATE_SCRIPTS_FILENAME="./update-network.sh"
CURRENT_DIR=$PWD

function help_func () {
    cat << EOF
Usage: ./build.sh [-y|-h]

Description:
    Simple script to update c model of neural network and/or build the firmware

Options:
    -y          Set all answer to yes
    -h|--help   Show this message
EOF
}

# Parse command line arguments
bypass=""
while [[ $# -gt 0 ]]; do
    case "$1" in
        -y)
            bypass=Y
            ;;
        -h)
            help_func
            exit 1
            ;;
        --help)
            help_func
            exit 1
            ;;
        *)
            echo "Unknown option: $1"
            help_func
            exit 1
            ;;
    esac
    shift
done

# 1.Update CModel
answer=$bypass
while true; do
    if [[ $answer == "" ]]; then
        read -r -p "Do you wish to update the code on firmware? (Y/N): " answer
    fi
    case $answer in
        [Yy]* )
            echo "Updating C model of neural network..."
            cd $UPDATE_SCRIPTS_PATH
            $UPDATE_SCRIPTS_FILENAME -y
            cd $CURRENT_DIR
            break;;
        [Nn]* )
            break;;
        * )
            answer=""
            echo "Please answer Y or N.";;
    esac
done

# 2.Clean prompt
answer=$bypass
cd $MAKEFILE_PATH
while true; do
    if [[ $answer == "" ]]; then
        read -r -p "Do you wish to clean the project folder first? (Y/N): " answer
    fi
    case $answer in
        [Yy]* )
            echo "Launching make clean..."
            make -j4 clean
            break;;
        [Nn]* )
            break;;
        * )
            answer=""
            echo "Please answer Y or N.";;
    esac
done

# 3.Build FW
echo "Building the firmware"
make -j4 all
cd $CURRENT_DIR
