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

needRoot

usage() {
	die 'gwhw flash dali [-a|--i2c-addr] -- [IMAGE]'
}

testcmd2 mspflash

I2C_ADDR=
PRI_RAND=
T1=
T2=
customize=false
while : ; do
	case "$1" in
		-a|--a|--i2c-addr)
			case "$#" in 1) usage ;; esac; shift
			I2C_ADDR="$1"
			customize=true
		;;
		-a=*|--a=*|--i2c-addr=*)
			I2C_ADDR="$(expr "$1" : '-[^=]*=\(.*\)')"
			customize=true
		;;
		-r|--r|--rand)
			case "$#" in 1) usage ;; esac; shift
			PRI_RAND="$1"
			customize=true
		;;
		-r=*|--r=*|--rand=*)
			PRI_RAND="$(expr "$1" : '-[^=]*=\(.*\)')"
			customize=true
		;;
		--t1|--timeout1)
			case "$#" in 1) usage ;; esac; shift
			T1="$1"
			customize=true
		;;
		--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/dali.hex}"
shift

if [ -n "${DALI_ID}" ]; then
	I2C_ADDR="${DALI_ADDR}"
	customize=true
fi

#############################################################
customizable(){
	awk 'FNR==2{print $1;exit}' "${IMAGE}" | grep -Fq -- 'FF' 
}

customImage(){
	def="$(awk 'FNR==2{printf "%s%s%s%s%s%s%s%s",$1,$2,$3,$4,$5,$6,$7,$8;exit}' "${IMAGE}")"

	if [ -z "${I2C_ADDR}" ]; then
		addr="${def:4:2}"
	else
		addr="$(printf "%02X" "${I2C_ADDR}")"
	fi

	if [ -z "${PRI_RAND}" ]; then
		rand="${def:6:2}"
	else
		rand="$(printf "%02X" "${PRI_RAND}")"
	fi

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

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

	awk "
		FNR==2{
			printf \"${def:0:2} ${def:2:2} \"
			printf \"${addr:0:2} ${rand:0:2} \"
			printf \"${t1:0:2} ${t1:2:2} \"
			printf \"${t2:0:2} ${t2:2:2} \"
			printf \"00 00 00 00 00 00 00 00\"
			print \"\"
			next
		}{print}
	" "${IMAGE}"
}

getImage() {
	if [ 'clean' = "${IMAGE}" ]; then
		IMAGE=
	else
		[ 'blink-test' = "${IMAGE}" ] && IMAGE="${path}/bin/dali_blink_test.hex"
		[ -r "${IMAGE}" ] || die "Cant read binary"
		if $customize; then
			customizable || die "Image not customizable"
			customImage > "/tmp/custom-dali.hex"
			IMAGE="/tmp/custom-dali.hex"
			[ -r "${IMAGE}" ] || die "Cant read binary"
		fi
	fi
}
#############################################################
# Turn ON
$GPIO -es PERIF_USB_PWR

getImage

mspflash --gpio-rst="${DALI_RST}" --gpio-tst="${DALI_TST}" --i2c-dev="${DALI_I2C}" --binary="${IMAGE}"
