#!/bin/sh /etc/rc.common
# Copyright (C) 2009-2015 OpenWrt.org

START=90
USE_PROCD=1

PROG=/usr/bin/owserver

append_arg() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get val "$cfg" "$var"
	[ -n "$val" -o -n "$def" ] && procd_append_param command $opt "${val:-$def}"
}

append_bool() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get_bool val "$cfg" "$var" "$def"
	[ "$val" = 1 ] && procd_append_param command "$opt"
}

append_plain() {
	procd_append_param command "$1"
}

append_param() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get val "$cfg" "$var"
	[ -n "$val" -o -n "$def" ] && procd_append_param "$opt" "${val:-$def}"
}

start_instance() {
	local cfg="$1"
	local enabled

	config_get_bool enabled "$cfg" 'enabled' '0'
	[ "$enabled" = 0 ] && return 1

	procd_open_instance

	procd_set_param command "$PROG" --foreground --error_print=1

	# common parameters
	append_bool "$cfg" readonly "--readonly"
	append_arg "$cfg" error_level "--error_level"
	config_list_foreach "$cfg" options append_plain
	config_list_foreach "$cfg" devices append_plain
	append_param "$cfg" user user

	# owserver-specific
	append_arg "$cfg" port "--port"
	append_arg "$cfg" max_connections "--max_connections"

	procd_set_param respawn

	procd_close_instance

}

service_triggers() {
	procd_add_reload_trigger owserver
}

start_service() {
	config_load owserver
	config_foreach start_instance owserver
}