#!/bin/sh /etc/rc.common
# Copyright (C) 2016 OpenWrt.org

START=98
STOP=20
PROG=/usr/bin/knxd
USE_PROCD=1

append_bool() {
	local section="$1"
	local option="$2"
	local value="$3"
	local _loctmp
	local default="$4"
	config_get_bool _loctmp "$section" "$option"
	[ -z "$_loctmp" ] && _loctmp="$default"
	[ "$_loctmp" -gt 0 ] && append params "--$value"
}

append_parm() {
	local section="$1"
	local option="$2"
	local switch="$3"
	local _loctmp
	local default="$4"
	config_get _loctmp "$section" "$option"
	[ -z "$_loctmp" ] && _loctmp="$default"
	[ -z "$_loctmp" ] && return 0
	append params "--$switch=$_loctmp"
}

start_service() {
	local options url
	config_load knxd
	append_parm args eibaddr "eibaddr" "0.0.1"
	append_parm args client_addrs "client-addrs" "0.0.2:10"
	append_parm args layer2 "layer2"
	append_bool args GroupCache "GroupCache" 0
	#append_parm args daemon "daemon" "/var/log/knxd.log"
	append_parm args error "error" # "5"
	append_parm args listen_tcp "listen-tcp" "6720"
	append_parm args Interface "Interface" # "eth0"
	append_parm args send_delay "send-delay" # "50"
	append_parm args Name "Name" "OpenWrt"
	append_bool args no_monitor "no-monitor" 0
	append_bool args Routing "Routing" 0
	append_bool args tpuarts_ack_all_group "tpuarts-ack-all-group" 0
	append_bool args tpuarts_ack_all_individual "tpuarts-ack-all-individual" 0
	append_bool args tpuarts_disch_reset "tpuarts-disch-reset" 0
	append_bool args Tunnelling "Tunnelling" 1
	append_bool args Discovery "Discovery" 1
	append_parm args Server "Server" "224.0.23.12"
	append_parm args listen_local "listen-local" "/var/run/knxd"
	append_parm args trace "trace" # "7"
	config_get url args url
	if [ "$url" == "usb:" ] ; then
		url="usb:""$(findknxusb | tail -n1 | sed -e 's/device: \([0-9]:[0-9]:[0-9]\):[0-9].*/\1/')"
	fi
	echo "/usr/lib/knxd_args $params -b $url"
	/usr/lib/knxd_args $params -b $url > /tmp/etc/knxd.ini
	procd_open_instance
	procd_set_param command $PROG "/tmp/etc/knxd.ini"
	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

reload_service()
{
	restart
}

service_triggers()
{
	procd_add_reload_trigger knxd
}
