#!/bin/sh

export PLC=$(uci get plc.plc.interface)

utf8() {
	local s
	# If valid UTF-8, ok. Else assume CP1252, convert to UTF-8, if not ok use fallback of 8bit unicode codepoints to UTF-8,
	# if this also fails, take it as it is.
	# actually HFID allow only ASCII code 32..127 according to HomePlug-AV spec. So this usage is not standard conform!
	s=$(printf "%s" "$1" | iconv -s -f utf-8 -t utf-8) ||
	s=$(printf "%s" "$1" | iconv -s -f cp1252 -t utf-8) ||
	s=$(printf "$(printf "%s" "$1" | hexdump -e '/1 "x00x%02x"' | sed -e 's,x,\\x,g')" | iconv -s -f ucs-2be -t utf-8) ||
	s=$(printf "%s" "$1")
	echo "$s"
}

. /usr/share/libubox/jshn.sh

json_load "$(plcstat -t "$@" | awk -f /usr/share/rpcd/plcstat-t.awk)" 2>/dev/null

json_select devices >/dev/null
el=1
while json_select $((el++)) >/dev/null ; do
	json_get_vars mac
	mfg="n/a"
	usr="n/a"
	net="n/a"
	nmk="n/a"
	if plcwait -x -s -w 1 -q "$mac" ; then
		MAC= MFG= USR= NET= NMK=
		while IFS=" " read a b; do
			case "$a" in
			MAC|\
			MFG|\
			USR|\
			NET|\
			NMK)
				eval $a="\$b"
				;;
			esac
		done <<EOF
$(plcID -t 250 -H "$mac")
EOF
		[ "$mac" = "$MAC" ] && {
			mfg="$MFG"
			usr="$(utf8 "$USR")"
			net="$NET"
			nmk="$NMK"
		}
	fi
	json_add_string mfg "$mfg"
	json_add_string usr "$usr"
	json_add_string net "$net"
	json_add_string nmk "$nmk"
	json_select ..
done
json_select ..

json_dump