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

START=99
STOP=10
USE_PROCD=1

PROG=/usr/sbin/linkease-lite
LOCAL_API=/var/run/linkeaselite.sock

read_config() {
	section="$1"
	config_get_bool enabled "$section" enabled 1
	config_get port "$section" port 8897
	config_get_bool allowPublic "$section" allowPublic 0
}

sync_firewall() {
	uci -q delete firewall.linkeaselite
	if [ "$allowPublic" = "1" ]; then
		uci -q set firewall.linkeaselite=rule
		uci -q set firewall.linkeaselite.name="linkeaselite"
		uci -q set firewall.linkeaselite.target="ACCEPT"
		uci -q set firewall.linkeaselite.src="wan"
		uci -q set firewall.linkeaselite.proto="tcp"
		uci -q set firewall.linkeaselite.dest_port="$port"
	fi
	uci -q commit firewall
	/etc/init.d/firewall reload
}

stop_linkease_runtimes() {
	[ -x /etc/init.d/linkeasefull ] && /etc/init.d/linkeasefull stop >/dev/null 2>&1
	[ -x /etc/init.d/linkease ] && /etc/init.d/linkease stop >/dev/null 2>&1

	if uci -q get linkease.@linkease[0] >/dev/null 2>&1; then
		uci -q set linkease.@linkease[0].enabled="0"
		uci -q commit linkease
	fi
	if uci -q get linkeasefull.@linkeasefull[0] >/dev/null 2>&1; then
		uci -q set linkeasefull.@linkeasefull[0].enabled="0"
		uci -q commit linkeasefull
	fi
}

start_service() {
	config_load linkeaselite
	config_foreach read_config linkeaselite
	sync_firewall
	[ "$enabled" = "1" ] || return 1
	[ -x "$PROG" ] || return 1

	stop_linkease_runtimes
	rm -f "$LOCAL_API"

	procd_open_instance linkeaselite
	procd_set_param limits nofile="65535 65535"
	procd_set_param command "$PROG"
	procd_append_param command --deviceAddr ":$port" --localApi "$LOCAL_API"
	[ "$allowPublic" = "1" ] && procd_append_param command --allowPublic
	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "linkeaselite"
}
