#!/bin/bash

envfile="/run/appliance-env"
[ -f ${envfile} ] && . ${envfile}

# VOIP devices don't have LED's
[ -z "${APPLIANCE_PART/*voip*}" ] && exit 0
[ -z "${APPLIANCE_PART/*s810*}" ] && exit 0
[ -z "${APPLIANCE_PART/*edp01*}" ] && exit 0


leds=(power status)
led_paths=(/sys/class/leds/led0 /sys/class/leds/led1)
colors=(red green blue)

states=(on off state)
flash=(yes no)

led=${1,,*}
color=${2,,*}
state=${3,,*}
blink=${4:-no}
blink=${blink,,*}

temp1=" ${leds[*]} "
temp2=" ${colors[*]} "
temp3=" ${states[*]} "
temp4=" ${flash[*]} "

if [ $# -lt 3 -o "${temp1/ ${led} /}" = "$temp1" \
-o "${temp2/ ${color} /}" = "$temp2" \
-o "${temp3/ ${state} /}" = "$temp3" \
-o "${temp4/ ${blink} /}" = "$temp4" ]; then
	logger -t $0 "Invalid parameters"
	exit 1
fi

actions=(action_on action_off action_state)

action_on() {
	for l_color in ${colors[*]/$2/}
	do
		action_off $1 $l_color $3
	done

	if [ ! -d "$3_$2" ]; then
		logger -p user.warning -t "$0[$$]" "Path not found $3_$2"
	else
#		logger -p user.info -t "$0[$$]" "Turning ON $3_$2"
		if [ "$1" == "${flash[0]}" ]; then
			echo heartbeat > $3_$2/trigger
		else
			echo default-on > $3_$2/trigger
		fi
	fi
}

action_off() {
	if [ ! -d "$3_$2" ]; then
		logger -p user.warning -t "$0[$$]" "Path not found $3_$2"
	else
#		logger -p user.info -t "$0[$$]" "Turning OFF $3_$2"
		echo none > $3_$2/trigger
	fi
}

action_state() {
	if [ ! -d "$3_$2" ]; then
		logger -p user.warning -t "$0[$$]" "Path not found $3_$2"
	else
		status=`sed -e 's/.*\[\(.*\)\].*/\1/' $3_$2/trigger`
		echo $status
	fi
}

for index in ${!leds[*]}
do
	if [ ${leds[$index]} = $led ]; then
		led_path=${led_paths[$index]}
		break
	fi
done

for index in ${!states[*]}
do
	if [ ${states[$index]} = $state ]; then
		eval ${actions[$index]} $blink $color $led_path
		break
	fi
done
