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

START=50
USE_PROCD=1

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"
}

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

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

	procd_open_instance

	procd_set_param command /usr/bin/udpxy
	procd_append_param command "-T"

	append_bool "$cfg" verbose "-V"
	append_bool "$cfg" status "-S"
	append_arg "$cfg" bind "-a"
	append_arg "$cfg" port "-p"
	append_arg "$cfg" source "-m"
	append_arg "$cfg" max_clients "-c"
	append_arg "$cfg" log_file "-l"
	append_arg "$cfg" buffer_size "-B"
	append_arg "$cfg" buffer_messages "-R"
	append_arg "$cfg" buffer_time "-H"
	append_arg "$cfg" nice_increment "-n"
	append_arg "$cfg" mcsub_renew "-M"

	config_get_bool aux "$cfg" 'respawn' '0'
	[ "$aux" = 1 ] && procd_set_param respawn

	procd_close_instance
}

service_triggers() { 
	procd_add_reload_trigger "udpxy" 
}

start_service() {
	config_load udpxy
	config_foreach start_instance udpxy
}
