#!/bin/sh

. /lib/functions.sh
. /lib/functions/system.sh

v() {
	[ "$VERBOSE" -ge 1 ] && echo "$@"
}

# constants
PNOTIFY_NONE=0
PNOTIFY_CC_REBOOT=1
PNOTIFY_CC_FW_UPGRADE=2
PNOTIFY_PANEL_FW_UPGRADE=3
SYS_ROOT_PATH="/sys/bus/i2c/devices/0-0032"
SYSFS_NOTIFY_FILE_PATH="$SYS_ROOT_PATH/notify"

# initialize defaults
export VERBOSE=1
export DEBUG=0
export PROGRESS=0
export HELP=0
export TEST=0

# parse options
while [ -n "$1" ]; do
	case "$1" in
		-v) export VERBOSE="$(($VERBOSE + 1))";;
		-q) export VERBOSE="$(($VERBOSE - 1))";;
		-d|--debug) export DEBUG=1;;
		-i|--progress) export PROGRESS=1;;
		-c|--check) export TEST=1;;
		-h|--help) export HELP=1; break;;
		-*)
			echo "Invalid option: $1"
			exit 1
		;;
		*) break;;
	esac
	shift;
done

IMAGE="$1"

[ -z "$IMAGE" -o $HELP -gt 0 ] && {
	cat <<EOF
Usage: $0 [<upgrade-option>...] <image file or URL>

upgrade-option:
	-c | --check
	                Verify image but do not actually flash.
	-q              less verbose
	-v              more verbose
	-d              debug on
	-i              show progress indicator
	-h | --help     display this help

EOF
	exit 1
}

case "$IMAGE" in
	http://*|\
	https://*)
		wget -O /tmp/rgpanel_fw.txt "$IMAGE"
		IMAGE=/tmp/rgpanel_fw.txt
		;;
esac

IMAGE="$(readlink -f "$IMAGE")"

case "$IMAGE" in
	'')
		echo "Firmware image file not found."
		exit 1
		;;
	/tmp/*)	;;
	*)
		v "Image not in /tmp, copying..."
		cp -f "$IMAGE" /tmp/rgpanel_fw.txt
		IMAGE=/tmp/rgpanel_fw.txt
		;;
esac

( rg-bsl -q -c -f "$IMAGE" ) || {
	echo "Firmware image '$IMAGE' check failed."
	exit 1
}

if [ $TEST -eq 1 ]; then
	exit 0
fi

OPTS="-a 2 -I i2c -s 0x42"
if [ $DEBUG -eq 1 ]; then
	OPTS="$OPTS -d"
else
	OPTS="$OPTS -q"
fi

if [ $PROGRESS -eq 1 ]; then
	OPTS="$OPTS -i"
fi

flash_pin_name="$(/sbin/uci get rgpaneld.@parameters[0].flash_pin_name 2>/dev/null)"
reset_pin_name="$(/sbin/uci get rgpaneld.@parameters[0].reset_pin_name 2>/dev/null)"

if [ "x$flash_pin_name" != "x" ]; then
    OPTS="$OPTS -T $flash_pin_name"
fi

if [ "x$reset_pin_name" != "x" ]; then
    OPTS="$OPTS -R $reset_pin_name"
fi

/sbin/rg-notify.sh S0003 I0001

echo ":i 0 0 Acquire transport"

#/etc/init.d/rgpaneld stop
#sleep 2

retry=0
max_attempts=5

# while [ $retry -lt $max_attempts ]; do

# 	retry=$((retry + 1))
# done

echo $PNOTIFY_PANEL_FW_UPGRADE > $SYSFS_NOTIFY_FILE_PATH 2>/dev/null
sleep 1
rg-bsl $OPTS -f "$IMAGE"
rc=$?

if [ $rc -eq 0 ]; then
    /sbin/rg-notify.sh S0003 I0002
else
    /sbin/rg-notify.sh S0003 W0001
fi

rg-bsl $OPTS -x

# /etc/init.d/rgpaneld restart

exit $rc
