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

START=99
USE_PROCD=1

PROG=/usr/sbin/linkease
LOCAL_API=/var/run/linkease.sock

get_config() {
	config_get_bool enabled "$1" enabled 1
	config_get_bool logger "$1" logger 0
	config_get_bool allowPublic "$1" allowPublic 0
	config_get port "$1" port 8897
}

stop_linkeaselite_runtime() {
	[ -x /etc/init.d/linkeaselite ] && /etc/init.d/linkeaselite stop >/dev/null 2>&1
	if uci -q get linkeaselite.@linkeaselite[0] >/dev/null 2>&1; then
		uci -q set linkeaselite.@linkeaselite[0].enabled="0"
		uci -q commit linkeaselite
	fi
}

stop_linkeasefull_runtime() {
	[ -x /etc/init.d/linkeasefull ] && /etc/init.d/linkeasefull stop >/dev/null 2>&1
	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 linkease
	config_foreach get_config linkease
	[ "$enabled" != "1" ] && return 1
	[ -x "$PROG" ] || return 1

	stop_linkeaselite_runtime
	stop_linkeasefull_runtime
	rm -f "$LOCAL_API"

	procd_open_instance
	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
	[ "$logger" = "1" ] && procd_set_param stderr 1
	procd_set_param respawn
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "linkease"
}
