#!/bin/sh

set -e

if [ "`id -u`" != "0" ]; then
	exec sudo "${0}" "${@}"
fi

if [ "`lsusb -d 03eb:204b`" != "" ]; then
	echo "Found running CUL, entering bootloader..."
	echo "B01" >/dev/ttyACM0
	sleep 1
fi

if [ "`lsusb -d 03eb:2ff4`" != "" ]; then
	echo "Found CUL in bootloader-mode"
else
	echo "No CUL in bootloader-mode found or unable to enter bootloader mode!"
fi

echo "Programming..."
set -x
dfu-programmer atmega32u4 erase
dfu-programmer atmega32u4 flash CUL_V3.hex
dfu-programmer atmega32u4 start