#!/bin/bash

set -e -o pipefail

BASE=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")

if [ "$(uname -s)" = "Darwin" ] ; then
	BURN_TOOL="$BASE/tools/macos/tone_dfu_tool"
else
	BURN_TOOL="$BASE/tools/$(uname -m)/tone_dfu_tool"
fi

KHADAS_TOOL="$(command -v "$(basename "$0")" || true)"
KHADAS_USB_VID=0x3353
KHADAS_USB_XMOS_VID=0x20b1

DEVICE=
IMAGE=

RED='\033[0;31m'
RESET='\033[m'

error_msg() {
	echo -e "$RED"ERROR:"$RESET" $1
}

usage() {
	echo -e "Usage:"
	echo -e "$(basename $0) -i <path-to-firmware>"
}

if [ -z "$KHADAS_TOOL" ] || [ ! -L "$KHADAS_TOOL" ]; then
	error_msg "Please install `basename $0`. Execute 'INSTALL' script to install it."
	exit 1
fi

while getopts "i:h" flag; do
    case $flag in
		i)
		IMAGE="$OPTARG"
		;;
		h)
		usage
		exit
		;;
	esac
done

if [ ! -f "$IMAGE" ]; then
	error_msg "Image file '$IMAGE' doesn't exist!"
	usage
	exit 1
fi

if [ "$(uname -s)" = "Darwin" ]; then
	if ! ioreg -p IOUSB -l -x | grep idVendor | grep -q "${KHADAS_USB_VID}\|${KHADAS_USB_XMOS_VID}"; then
		error_msg "You should connect the Tone to your computer!"
		exit -1
	fi
else
	if ! lsusb -d $KHADAS_USB_VID: > /dev/null && ! lsusb -d $KHADAS_USB_XMOS_VID: > /dev/null; then
		error_msg "You should connect the Tone to your computer!"
		exit -1
	fi
fi


echo "Upgrading Tone firmware..."
$BURN_TOOL --download "$IMAGE"


echo "Done!"

