#!/bin/sh

get_signal()
{
	local mac_other_side="$1"
	local wifidev="wlan0"
	local line

	iw dev $wifidev station get "$mac_other_side" 2>/dev/null |
	 while read line; do {
		case "$line" in
			*"signal avg:"*)
				set $line
				echo ${3//-/}	# remove the minus
				return 0
			;;
		esac
	} done
}

led()
{
	local which="$1"

	case "$which" in
		A)
			echo "ubnt:red:link1"
		;;
		B)
			echo "ubnt:orange:link2"
		;;
		C)
			echo "ubnt:green:link3"
		;;
		D)
			echo "ubnt:green:link4"
		;;
	esac
}

do_led()
{
	local which="$1"	# A, B, ...
	local value="$2"
	local dir="/sys/devices/platform/leds-gpio/leds"
	local file="$dir/$( led "$which" )/trigger"

	case "$value" in
		off)
			value="none"
		;;
		on|*)
			value="default-on"
		;;
	esac

	echo "$value" >"$file"
}

all_off()
{
	echo "all leds are off now"

	do_led "A" "off"
	do_led "B" "off"
	do_led "C" "off"
	do_led "D" "off"

	exit 1
}

minimac2fullmac()
{
	local mac="$1"
	local char

	for char in 1 2 : 3 4 : 5 6 : 7 8 : 9 10 : 11 12; do {
		case $char in
			:)
				echo -n ":"
			;;
			*)
				echo -n "$( echo "$mac" | cut -b $char )"
			;;
		esac
	} done
}

trap all_off SIGINT

MAC_OTHER_SIDE="$1"
L1="${2:-70}"	# all on
L2="${3:-72}"	# 3 on
L3="${4:-74}"	# 2 on
L4="${5:-76}"	# 1 on
		# otherwise off

case "$MAC_OTHER_SIDE" in
	test_leds)
		while true; do {
			do_led "A" "on"
			do_led "B" "on"
			do_led "C" "on"
			do_led "D" "on"
			sleep 1
			do_led "A" "off"
			do_led "B" "off"
			do_led "C" "off"
			do_led "D" "off"
			sleep 1
		} done
	;;
	auto)
		MAC_OTHER_SIDE="$( iw dev wlan0 station dump | head -n1 | cut -d' ' -f2 )"
		[ -z "MAC_OTHER_SIDE" ] && {
			echo "no station found"
			exit 1
		}
	;;
	*)
		[ ${#MAC_OTHER_SIDE} = 12 ] && {
			MAC_OTHER_SIDE="$( minimac2fullmac "$MAC_OTHER_SIDE" )"
		}
	;;
	"")
		echo "Usage: $0 <other_side|auto> <level1> <level2> <level3> <level4>"
		echo " e.g.: $0 "11:22:33:44:55:66" 70 72 74 76"
		exit 1
	;;
esac

while true; do {

	SIGNAL="$( get_signal "$MAC_OTHER_SIDE" )"

	if [ -z "$SIGNAL" ]; then
		echo "no signal ($MAC_OTHER_SIDE)"
		sleep 1
		continue
	else
		echo "Signal average: -$SIGNAL ($MAC_OTHER_SIDE)"
	fi

	if   [ $SIGNAL -lt $L1 ]; then
		do_led "A" "on"
		do_led "B" "on"
		do_led "C" "on"
		do_led "D" "on"
	elif [ $SIGNAL -lt $L2 ]; then
		do_led "A" "on"
		do_led "B" "on"
		do_led "C" "on"
		do_led "D" "off"
	elif [ $SIGNAL -lt $L3 ]; then
		do_led "A" "on"
		do_led "B" "on"
		do_led "C" "off"
		do_led "D" "off"
	elif [ $SIGNAL -lt $L4 ]; then
		do_led "A" "on"
		do_led "B" "off"
		do_led "C" "off"
		do_led "D" "off"
	else
		do_led "A" "off"
		do_led "B" "off"
		do_led "C" "off"
		do_led "D" "off"
	fi
} done

