#!/bin/bash

LPCBIN=/home/ROULETTE/terminal/lpc21isp

echo "********************************************************************"
PRINT_USAGE=0
if [ -n "$3" ]; then
	TRIES=$3
else
	TRIES=3
	echo "You can provide tries parameter. Using default value "$TRIES
	PRINT_USAGE=1
fi
if [ -c "$2" ]; then 
	PORT=$2
else
	PORT="/dev/ttyUSB3"
	echo "You may provide serial port device parameter. Using default port "$PORT
	PRINT_USAGE=1
fi
if [ -f "$1" ]; then 
	FIRMWARE=$1
else
	FIRMWARE="/home/ROULETTE/terminal_home/FIRMWARE/IGPlatformV6.0.hex"
	echo "You may provide Firmware filename parameter. Using default "$FIRMWARE
	PRINT_USAGE=1
#	echo "USAGE: "$0" [PATH_TO_FIRWARE FILE] [SERIAL PORT DEVICE] [SYNC_RETRIES]"
fi
if [ $PRINT_USAGE -gt 0 ];then
	echo "USAGE: "$0" [PATH_TO_FIRWARE FILE] [SERIAL PORT DEVICE] [SYNC_RETRIES]"
	echo
fi;

[[ $@ != *"quiet"* ]] && echo "Using FIRMWARE: "$FIRMWARE
[[ $@ != *"quiet"* ]] && echo "Using SerialPORT: "$PORT
[[ $@ != *"quiet"* ]] && echo "Using TRIES: "$TRIES

[[ $@ != *"quiet"* ]] && echo "Starting FIRMWARE upgrade!"
[[ $@ != *"quiet"* ]] && echo "Press Ctrl+C to abort now(2 seconds...)"
[[ $@ != *"quiet"* ]] && echo ""
sleep 2
if [ ! -f $FIRMWARE ]; then
	echo "Can not access "$FIRMWARE
	echo "Nothing to do, exiting.."
	exit 3
fi

if [[ $@ != *"quiet"* ]]; then
	echo "Starting"
	$LPCBIN -wipe -try$TRIES -hex $FIRMWARE $PORT 115200 12000
	RES=$?
else
	$LPCBIN -wipe -try$TRIES -hex $FIRMWARE $PORT 115200 12000 2>/dev/null 1>/dev/null
	RES=$?
fi

if [ $RES -ne 0 ] && [ ! -c "$2" ]; then  #if not success of first port and port was not provided with parameter, then try also other ports
	echo "Failed on port "$PORT", retrying on /dev/ttyUSB4"
	PORT="/dev/ttyUSB4"
	$LPCBIN -wipe -try$TRIES -hex  $FIRMWARE $PORT 115200 12000
	RES=$?
fi

if [ $RES -ne 0 ] && [ ! -c "$2" ]; then 
	echo "Failed on port "$PORT", retrying on /dev/ttyUSB5"
	PORT="/dev/ttyUSB5"
	$LPCBIN -wipe -try$TRIES -hex  $FIRMWARE $PORT 115200 12000
	RES=$?
fi

if [ $RES -ne 0 ] && [ ! -c "$2" ]; then 
	echo "Failed on port "$PORT", retrying on /dev/ttyUSB6"
	PORT="/dev/ttyUSB6"
	$LPCBIN -wipe -try$TRIES -hex  $FIRMWARE $PORT 115200 12000
	RES=$?
fi

if [ $RES -ne 0 ] && [ ! -c "$2" ]; then 
	echo "Failed on port "$PORT", retrying on /dev/ttyUSB7"
	PORT="/dev/ttyUSB7"
	$LPCBIN -wipe -try$TRIES -hex  $FIRMWARE $PORT 115200 12000
	RES=$?
fi

if [ $RES -eq 0 ]; then
	[[ $@ != *"quiet"* ]] && echo "Firmware upgraded successfuly."
	[[ $@ != *"quiet"* ]] && echo "********************************************************************"
else
	[[ $@ != *"quiet"* ]] && echo
	[[ $@ != *"quiet"* ]] && echo "Firmware upgrade ERROR."
	[[ $@ != *"quiet"* ]] && echo "Make sure device is in ISP mode, place jumper and cycle power supply(RGB semaphore should be white!)."
	[[ $@ != *"quiet"* ]] && echo "********************************************************************"
fi

exit $RES


