#!/bin/bash

# one-line usage
# /bin/bash -c "$(curl -fsSL https://dl.khadas.com/products/tone2/firmware/tone2_pro/mcu/upgrade_mcu.sh)"

echo "[i] Tone Board MCU upgrade (online script) - PRESS ANY KEY or Escape by Ctrl+C"
read -n1

cd ~
mkdir -p tone_upgrade
cd tone_upgrade

case $(uname) in
    Darwin) # MacOS

#install homebrew for mac os
which brew || \
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
#install-sh
brew install git libusb make automake mk-configure libtool pkg-config wget
echo 'export PATH="/usr/local/opt/m4/bin:$PATH"' >> ~/.zshrc

pkg-config --cflags libusb-1.0 || {
echo "[i] prepare libusb source"
git clone https://github.com/libusb/libusb.git
cd libusb
./autogen.sh
./configure
echo "[i] make libusb"
make
make install
cd ..
}
#pkg-config --libs libusb-1.0

    ;;

    *) # Linux
    #sudo apt-get update
    sudo apt-get install build-essential libusb-1.0-0-dev git
    ;;
esac

[ -s ./stm8flash/stm8flash ] || {
echo "[i] prepare stm8flash"
git clone https://github.com/vdudouyt/stm8flash.git
make -C stm8flash
}

FW=tone2pro-mcu-boot-app-v1.4-221128.zip

[ -s $FW ] || {
echo "[i] download last FW $FW"
wget https://dl.khadas.com/products/tone2/firmware/tone2_pro/mcu/$FW
unzip $FW
}

echo "[i] please connect your ST-Link paired with Tone Board and PRESS ANY KEY"
read -n1

./stm8flash/stm8flash -cstlinkv2 "-pstm8s003?3" -s flash \
    -w tone2pro-mcu-boot-app-v1.4-221128.hex || {
    echo "[i] UPGRADE ERROR ($?) - check previous error messages - and try to resolve it
or submit some message to us about this issue plz!"
    exit 1
    }

echo "[i] MCU Upgrade Complete!"
