#!/bin/bash

#set -e

architecture="unknow"
case $(uname -m) in
    x86_64) architecture="amd64" ;;
    armv7l)    dpkg --print-architecture | grep -q "arm64" && architecture="aarch64" || architecture="armhf" ;;
    arm)    dpkg --print-architecture | grep -q "arm64" && architecture="aarch64" || architecture="armhf" ;;
    aarch64) architecture="aarch64";;
    riscv64) architecture="riscv64";;
esac


if [ $architecture = "unknow" ]; then
	echo "unknow architecture,exiting..."
	exit
fi


if [ $# -lt 4 ]; then
    echo "Usage: $0 $# <dummy_port> <altID> <usbID> <binfile>" >&2
    exit 1
fi
dummy_port="$1"; altID="$2"; usbID="$3"; binfile="$4"; dummy_port_fullpath="/dev/$1"
if [ $# -eq 5 ]; then
    dfuse_addr="--dfuse-address $5"
else
    dfuse_addr=""
fi


# Get the directory where the script is running.
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

#  ----------------- IMPORTANT -----------------
# The 2nd parameter to upload-reset is the delay after resetting before it exits
# This value is in milliseonds
# You may need to tune this to your system
# 750ms to 1500ms seems to work on my Mac
#echo  ${dummy_port_fullpath}

if [ $architecture == "amd64" ]; then
"${DIR}/upload-reset.elf" ${dummy_port_fullpath} 750
sleep 2
"${DIR}/upload-reset.elf" ${dummy_port_fullpath} 750
else
"${DIR}/deb_packages/$architecture/upload-reset.elf" ${dummy_port_fullpath} 750
sleep 2
"${DIR}/deb_packages/$architecture/upload-reset.elf" ${dummy_port_fullpath} 750
fi

DFU_UTIL=/usr/bin/dfu-util
#DFU_UTIL=${DIR}/dfu-util/dfu-util
if [ ! -x "${DFU_UTIL}" ]; then
    echo "$0: error: cannot find ${DFU_UTIL}" >&2
    exit 2
fi

echo "${DFU_UTIL}" -d ${usbID} -a ${altID} -D ${binfile} ${dfuse_addr} -R

"${DFU_UTIL}" -d ${usbID} -a ${altID} -D ${binfile} ${dfuse_addr} -R

echo -n Waiting for ${dummy_port_fullpath} serial...
dpkg --print-architecture
COUNTER=0
while [ ! -c ${dummy_port_fullpath} ] && ((COUNTER++ < 40)); do
    sleep 0.2
done

echo Done
