#!/bin/sh
# Button Handler start-up script.

CONFIG_FILE="/tmp/button-handler.conf"

APP_NAME="button-handler"
APP_BIN="/usr/bin/${APP_NAME}"
APP_OPTS="-c ${CONFIG_FILE}"
APP_PID_FILE="/var/run/${APP_NAME}.pid"

WD_BIN="barix-wd"

create_config() {
	rm -f ${CONFIG_FILE}
	# read up to 16 actions
	for idx in {1..16}; do
        action=$(uci -q get button_handler.action${idx})
		if [ $? -ne 0 ]; then
			# no more configurations
			continue
		fi
		press_time=$(uci -q get button_handler.action${idx}.press_time)
		trigger=$(uci -q get button_handler.action${idx}.trigger)
		if [ ${trigger} == "pressed" ] || [ ${trigger} == "released" ]; then
			script=$(uci -q get button_handler.action${idx}.script)
			echo "${press_time} ${trigger} ${script}" >> ${CONFIG_FILE}
		else
			led_time_on=$(uci -q get button_handler.action${idx}.led_time_on)
			led_time_off=$(uci -q get button_handler.action${idx}.led_time_off)
			led_color=$(uci -q get button_handler.action${idx}.led_color)
			echo "${press_time} ${trigger} ${led_time_on} ${led_time_off} ${led_color}" >> ${CONFIG_FILE}
		fi
	done
}

start() {
	if [ ! -f /barix/config/current/button_handler ]; then
		cp -f /barix/config/defaults/button_handler /barix/config/current/button_handler
	fi

	create_config

	echo "${APP_NAME}: Starting the ${APP_NAME} application..."
	${WD_BIN} --pid-file=${APP_PID_FILE} --timeout=5 --background --start -- ${APP_BIN} ${APP_OPTS}
	echo "${APP_NAME}: Starting the ${APP_NAME} application...DONE"
}

stop() {
	echo "${APP_NAME}: Stopping the ${APP_NAME} application..."
	${WD_BIN} --pid-file=${APP_PID_FILE} --stop --wait
	echo "${APP_NAME}: Stopping the ${APP_NAME} application...DONE"
}

restart() {
	stop
	start
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart|reload)
		restart
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
esac

exit 0
