#!/bin/bash

set -eu

waitdfu() {
    devid=$1
    for waiting in {1..51}; do
        if [ $waiting -ge 50 ]; then
            echo "Timeout: no dfu device arrived"
            return 1
        fi
        lsusb|grep -q "1eaf:$devid" && return 0
        sleep 0.1
    done
}

firmware=$1
if ! test -f "$firmware"; then
    echo "Firmware $firmware not found"
    exit 1
fi

# This "try" thing is because sometimes you found the device already in "0003" mode
# In that case, the easiest thing is to make it fail and press reset
for try in {1..3}; do
    echo "Waiting..."
    waitdfu 0003|| exit 1
    echo "Device found, uploading"
    dfu-util -d 1EAF:0003 -a 2 -D "$1" -R || dfuret=$?
    test $dfuret -eq 0 && exit 0
    echo "Please Reset!"
    test $try -ne 3 && sleep 0.2
done
exit $dfuret
