#!/bin/bash

INTERVAL=10
WIFI_MGMT=wifi_mgmt

# profile
CONF_DIR=/etc/moxa-wifi-utils
PRODUCT_DIR=${CONF_DIR}/product.d

KVERSION=$(which kversion)
[ -z "${KVERSION}" ] && >&2 echo "Error: \`kversion\` not found." && exit 1

PRODUCT="$(${KVERSION} 2> /dev/null | awk '{print $1}')"

_init_config() {
	for conf in $(ls ${PRODUCT_DIR}); do
		if [ "${conf: -5}" == ".conf" ]; then
			. ${PRODUCT_DIR}/$conf
		fi
	done

	eval "_product_${PRODUCT}_profile" 2>/dev/null
	if [ x"$?" != x"0" ]; then
		>&2 echo "Error: \`kversion\` or profile not found."
		_exit 1
	fi
}

_signal_led_flush() {
	slot=$1
	if [ -z "$SIGNAL_LED_FLUSH" ]; then
		# Operation not support. Return.
		return
	fi
	# Use product config signal led flush
	signal_led_flush_funcs="$(echo "$SIGNAL_LED_FLUSH" | \
				sed -e "s/\$SLOT/$slot/g")"
	IFS=$'\n'
	for i in $signal_led_flush_funcs; do
		eval "$i"
	done
}

_signal_led() {
	slot=$1
	signal=$2

	#echo slot: $slot
	#echo signal: $signal
	if  echo "$signal" | grep -q "N/A"; then
		_signal_led_flush ${slot}
		return
	fi

	signal=$(echo "$signal" | awk 'END {print $(NF-4)}')
	if [ $signal -ge -30 ]; then
		#echo "Excellent"
		if [ -n "$SIGNAL_LED_EXCELLENT" ]; then
			# Use product config to signal led.
			signal_led_funcs="$(echo "$SIGNAL_LED_EXCELLENT" | \
					sed -e "s/\$SLOT/$slot/g")"
		else
			# Operation not support. Return.
			return
		fi
	elif [ $signal -ge -70 ]; then
		#echo "Fair"
		if [ -n "$SIGNAL_LED_FAIR" ]; then
			# Use product config to signal led.
			signal_led_funcs="$(echo "$SIGNAL_LED_FAIR" | \
					sed -e "s/\$SLOT/$slot/g")"
		else
			# Operation not support. Return.
			return
		fi
	elif [ $signal -ge -80 ]; then
		#echo "Poor"
		if [ -n "$SIGNAL_LED_POOR" ]; then
			# Use product config to signal led.
			signal_led_funcs="$(echo "$SIGNAL_LED_POOR" | \
					sed -e "s/\$SLOT/$slot/g")"
		else
			# Operation not support. Return.
			return
		fi
	else
		#echo "No signal"
		_signal_led_flush ${slot}
		return
	fi

	IFS=$'\n'
	for i in $signal_led_funcs; do
		eval "$i"
	done
}

_loop() {
	while [ 1 ]; do
		modules=$(${WIFI_MGMT} interfaces)
		for i in $(seq 0 $((modules-1))); do
			slot=$(${WIFI_MGMT} -i wlan$i slot)
			signal=$(${WIFI_MGMT} -i wlan$i signal)
			_signal_led ${slot} "${signal}"
		done
		sleep ${INTERVAL}
	done
}

usage() {
	echo "Usage:"
	echo "  $1 [OPTION]"
	echo ""
	echo "Options:"
	echo "  -i <polling interval>"
	echo "		Polling interval in seconds to update the signal LED"
	echo "  -h"
	echo "		Show help"
	echo "  -v"
	echo "		Print version"
}


while getopts  "i:vh" flag; do
	if [ "${flag}" == "i" ]; then
		re='^[0-9]+$'
		if ! [[ $OPTARG =~ $re ]] ; then
			   echo "error: Interval should be a number" >&2
			   usage $0
			   exit 1
		fi
		INTERVAL=$OPTARG
	elif [ "${flag}" == "h" ]; then
		usage $0
		exit 0
	elif [ "${flag}" == "v" ]; then
		${WIFI_MGMT} version
		exit 0
	fi
done

_init_config
_loop
