#!/bin/sh /etc/rc.common

### Init script for LED schedule control

START=99
STOP=10
USE_PROCD=1

start_service() {
	enabled=$(uci -q get ledcontrol.@ledcontrol[0].enabled)
	[ -z "$enabled" ] && enabled=1

	if [ "$enabled" -eq 0 ]; then
		return 0
	fi

	procd_open_instance
	procd_set_param command /bin/sh -c '
		time_to_minutes() {
			echo "$1" | awk -F: "{ print (\$1 * 60) + \$2 }"
		}

		last_state="none"

		while true; do
			on_time=$(uci get ledcontrol.@ledcontrol[0].on_time 2>/dev/null)
			off_time=$(uci get ledcontrol.@ledcontrol[0].off_time 2>/dev/null)

			if [ -z "$on_time" ] || [ -z "$off_time" ]; then
				sleep 60
				continue
			fi

			on_minutes=$(time_to_minutes "$on_time")
			off_minutes=$(time_to_minutes "$off_time")
			cur_time=$(date +%H:%M)
			cur_minutes=$(time_to_minutes "$cur_time")

			if [ "$on_minutes" -lt "$off_minutes" ]; then
				if [ "$cur_minutes" -ge "$on_minutes" ] && [ "$cur_minutes" -lt "$off_minutes" ]; then
					if [ "$last_state" != "on" ]; then
						/usr/share/routerich/ledcontrol/led_control.sh on
						last_state="on"
					fi
				else
					if [ "$last_state" != "off" ]; then
						/usr/share/routerich/ledcontrol/led_control.sh off
						last_state="off"
					fi
				fi
			else
				if [ "$cur_minutes" -ge "$on_minutes" ] || [ "$cur_minutes" -lt "$off_minutes" ]; then
					if [ "$last_state" != "on" ]; then
						/usr/share/routerich/ledcontrol/led_control.sh on
						last_state="on"
					fi
				else
					if [ "$last_state" != "off" ]; then
						/usr/share/routerich/ledcontrol/led_control.sh off
						last_state="off"
					fi
				fi
			fi

			sleep 10
		done
	'
	procd_set_param respawn
	procd_close_instance
}


reload_service() {
	/etc/init.d/ledschedule restart
}

service_triggers() {
	procd_add_reload_trigger ledcontrol
}
