#!/bin/bash

# one-line usage
# /bin/bash -c "$(curl -fsSL https://dl.khadas.com/Firmware/Tone2/upgrade_dfu.sh)"

DL=https://dl.khadas.com/Firmware/Tone2/
FW=Tone2_Pro_Firmware_V1.20_210408
FN=Tone2_Pro_XMOS_V1.20_210408.bin
FWZ=$FW.zip

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

cd ~
[ -d tone_upgrade ] || mkdir tone_upgrade
cd tone_upgrade

case $(uname) in
    Darwin) # MacOS
    OS=osx
#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
    OS=linux
    #sudo apt-get update
    sudo apt-get install build-essential libusb-1.0-0-dev git pkg-config
    echo 'SUBSYSTEM=="usb", ATTR{idVendor}=="3353", ATTR{idProduct}=="a002", MODE="0666"' | sudo tee /etc/udev/rules.d/tone-upgrade.rules

    ;;
esac


D=.

case $OS in
    DISABLED=osx)
    pos=_macos
    F=$D/tone_dfu_tool$pos
    [ -s $F ] || {
    wget https://dl.khadas.com/products/tone2/dfu_tool/tone_dfu_tool$pos
    chmod 0777 $F
    }
    ;;
    *)
    D=USB-Audio-2.0-Software-v6.1/sc_usb_audio/module_dfu/host/xmos_dfu_$OS
    ;;
esac

[ -s $D/tone_dfu_tool$pos ] || {
echo "[i] prepare dfu tool"
git clone https://github.com/numbqq/USB-Audio-2.0-Software-v6.1
make -C $D
}

[ -s $FWZ ] || {
echo "[i] download last FW $FWZ"
wget $DL/$FWZ
unzip $FWZ
}

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

echo ../tone_dfu_tool$pos --download "$FW/$FN"

LOG=upgrade.log

$D/tone_dfu_tool$pos --download "$FW/$FN" 2>&1 | tee $LOG

grep -q "Download complete" upgrade.log || {
    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] DFU Upgrade Complete!"
