#!/bin/sh
#############################################################
path="${0%/*}"
. "$path/inc/gwhw.inc"

needRoot

usage() {
	die 'gwhw flash wd [-t|--timeout] [-f|--flags] -- [IMAGE]'
}

testcmd2 mspflash

T1=
T2=
FF=
customize=false
while : ; do
	case "$1" in
		-f|--f|--flags)
			case "$#" in 1) usage ;; esac; shift
			FF="$1"
			customize=true
		;;
		-f=*|--f=*|--flags=*)
			FF="$(expr "$1" : '-[^=]*=\(.*\)')"
			customize=true
		;;
		-t|--t|--timeout|--t1|--timeout1)
			case "$#" in 1) usage ;; esac; shift
			T1="$1"
			customize=true
		;;
		-t=*|--t=*|--timeout=*|--t1=*|--timeout1=*)
			T1="$(expr "$1" : '-[^=]*=\(.*\)')"
			customize=true
		;;
		--t2|--timeout2)
			case "$#" in 1) usage ;; esac; shift
			T2="$1"
			customize=true
		;;
		--t2=*|--timeout2=*)
			T2="$(expr "$1" : '-[^=]*=\(.*\)')"
			customize=true
		;;
		--)
			shift
			break
		;;
		-*)
			usage
		;;
		*)
			break
		;;
	esac
	shift
done

IMAGE="${1:-$path/bin/wd.hex}"
shift

#############################################################
customImage(){
	def="$(awk 'FNR==2{printf "%s%s%s%s%s%s",$1,$2,$3,$4,$5,$6;exit}' "${IMAGE}")"
	if [ -z "${T1}" ]; then
		t1="${def:0:4}"
	else
		t1="$(printf "%04X" "${T1}")"
		t1="${t1:2:2}${t1:0:2}"
	fi

	if [ -z "${T2}" ]; then
		t2="${def:4:4}"
	else
		t2="$(printf "%04X" "${T2}")"
		t2="${t2:2:2}${t2:0:2}"
	fi

	if [ -z "${FF}" ]; then
		ff="${def:8:4}"
	else
		ff="$(printf "%04X" "${FF}")"
		ff="${ff:2:2}${ff:0:2}"
	fi

	awk "
		FNR==2{
			printf \"${t1:0:2} ${t1:2:2} \"
			printf \"${t2:0:2} ${t2:2:2} \"
			printf \"${ff:0:2} ${ff:2:2} \"
			printf \"00 00 00 00 00 00 00 00 00 00\"
			print \"\"
			next
		}{print}
	" "${IMAGE}"
}
#############################################################
if [ 'clean' = "${IMAGE}" ]; then
	IMAGE=
else
	[ -r "${IMAGE}" ] || die "Cant read binary"
	if $customize; then
		customImage > "/tmp/custom-wd.hex"
		IMAGE="/tmp/custom-wd.hex"
		[ -r "${IMAGE}" ] || die "Cant read binary"
	fi
fi

mspflash --gpio-rst="${WD_RST}" --gpio-tst="${WD_TST}" --i2c-dev="${WD_I2C}" --binary="${IMAGE}"

# TODO: do not reset after flashing
# device mey reset cpu immediatelly after flashing and msp reset
