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

. $IPKG_INSTROOT/lib/functions/network.sh

USE_PROCD=1
START=90

tunnel_id=1

missing() {
	echo "Not starting tunneldigger - missing $1" >&2
}

parse_broker() {
	local section="$1"

	config_get_bool enabled "$section" enabled 1
	config_get addresses "$section" address
	config_get uuid "$section" uuid
	config_get interface "$section" interface
	config_get limit_bw_down "$section" limit_bw_down
	config_get hook_script "$section" hook_script
	config_get bind_interface "$section" bind_interface
	config_get group "$section" group
	
	[ $enabled -eq 0 ] && return

	local broker_opts=""
	for address in $addresses; do
		append broker_opts "-b ${address}"
	done

	[ ! -z "${limit_bw_down}" ] && append broker_opts "-L ${limit_bw_down}"
	[ ! -z "${hook_script}" ] && append broker_opts "-s ${hook_script}"
	[ ! -z "${bind_interface}" ] && {
		# Resolve logical interface name.
		unset _bind_interface
		network_get_device _bind_interface "${bind_interface}" || _bind_interface="${bind_interface}"
		append broker_opts "-I ${_bind_interface}"
	}

	if [ -z "$uuid" ]; then
		missing uuid
		return
	elif [ -z "$interface" ]; then
		missing interface
		return
	fi

	procd_open_instance "tunneldigger_${tunnel_id}"
	procd_set_param command "/usr/bin/tunneldigger"
	procd_append_param command -f
	procd_append_param command -u "${uuid}"
	procd_append_param command -i "${interface}"
	procd_append_param command -t "${tunnel_id}"
	procd_append_param command ${broker_opts}
	[ -n "$group" ] && procd_set_param group "$group"
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn
	procd_close_instance

	let tunnel_id++
}

start_service() {
	config_load tunneldigger
	config_foreach parse_broker broker
}
