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

needRoot
daliI2COK

usage() {
	die 'gwhw dali shark [raw]'
}

OPT="${1:-parsed}"
shift
#############################################################

read64() {
	while :; do
		echo "START"
		i2ctransfer -y "${DALI_BUS}" w1@"${DALI_ADDR}" 0x3c r68 \
		| sed -r 's/^(.{20})(.*)$/\1\2 \2/g' \
		| sed 's/\(.... .... .... ....\) /\1\n/g'
		usleep 200000
	done
}

process64() {
	I=0
	local cnt=
	local cntp=
	while read a b c d; do
		if [ ${a} = "START" ]; then
			I=0
			cntp="$cnt"
			continue
		fi
		if [ "$I" = "0" ]; then
			cnt="$((${d}${c:2}))"
			[ -z "$cntp" ] && cntp="${cnt}"

			FROM="$(( ${cntp} % 16 ))"
			TO="$((   ${cnt}  % 16 ))"
			[ "${FROM}" -gt "${TO}" ] && TO="$(( TO+16 ))"
		fi
		if [ "$cnt" = "$cntp" ]; then
			: $((I++))
			continue
		fi
		II="$((I-1))"
		if [ "$II" -ge "${FROM}" ] && [ "$II" -lt "${TO}" ] ; then
			local LEN="$(( (a & 0x1f)-1 ))"
			local ADDR=
			local CMD=
			local SELF=
			local ERR=
			if [ "16" = "${LEN}" ]; then
				[ "1" = "$(( (c & 0x80) == 0x00 ))" ] && ADDR="S$(( (c >> 1) & 0x3f ))"
				[ "1" = "$(( (c & 0xe0) == 0x80 ))" ] && ADDR="G$(( (c >> 1) & 0x0f ))"
				[ "1" = "$(( (c & 0xfe) == 0xfe ))" ] && ADDR="BR"
				if [ "1" = "$(( (c & 0x01) == 0x00 ))" ]; then
					CMD="L$(( b ))"
				else
					CMD="${b}"
				fi
			elif [ "8" = "${LEN}" ]; then
				CMD="${b}"
			fi
			[ "1" = "$(( (a & 0x40) == 0x40 ))" ] && SELF="SELF"
			[ "1" = "$(( (a & 0x80) == 0x80 ))" ] && ERR="ERR"
			printf "%5d: 0x${a:2}${b:2}${c:2}${d:2} LEN:%2d %-3s %5s %5s%5s\n" "$((cntp++))" "${LEN}" "${ADDR}" "${CMD}" "${SELF}" "${ERR}"
		fi
		: $((I++))
	done
}

processRaw() {
	I=0
	local cnt=
	local cntp=
	while read a b c d; do
		if [ ${a} = "START" ]; then
			I=0
			cntp="$cnt"
			continue
		fi
		if [ "$I" = "0" ]; then
			cnt="$((${d}${c:2}))"
			[ -z "$cntp" ] && cntp="${cnt}"

			FROM="$(( ${cntp} % 16 ))"
			TO="$((   ${cnt}  % 16 ))"
			[ "${FROM}" -gt "${TO}" ] && TO="$(( TO+16 ))"
		fi
		if [ "$cnt" = "$cntp" ]; then
			: $((I++))
			continue
		fi
		II="$((I-1))"
		if [ "$II" -ge "${FROM}" ] && [ "$II" -lt "${TO}" ] ; then
			printf "0x${a:2}${b:2}${c:2}${d:2}\n"
		fi
		: $((I++))
	done
}

case "${OPT}" in
	parsed) read64 | process64
	;;
	raw) read64 | processRaw
esac
