#!/bin/sh /etc/rc.common
# shellcheck disable=SC2039,SC3043
# vim: set noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 :

# shellcheck disable=SC2034
{
	START=90
	STOP=10
	USE_PROCD=1
}

_validate_section() {
	local tmp_hosts="$hosts" tmp_timeout="$timeout" tmp_tries="$tries"
	local tmp_interval="$interval" tmp_options="$options"

	uci_validate_section otb-tracker "$1" "$2" \
		'hosts:list(host)' \
		'timeout:uinteger' \
		'tries:uinteger' \
		'interval:uinteger' \
		'options:string'

	[ -z "$hosts"    ] && hosts=$tmp_hosts
	[ -z "$timeout"  ] && timeout=$tmp_timeout
	[ -z "$tries"    ] && tries=$tmp_tries
	[ -z "$interval" ] && interval=$tmp_interval
	[ -z "$options"  ] && options=$tmp_options
}

_launch_tracker() {
	case "$1" in
		loopback|lan*|if0*) return;;
	esac

	local interface_type
	config_get interface_type "$1" type

	local hosts timeout tries interval options
	_validate_section "defaults" "defaults"
	_validate_section "rule_type" "$interface_type"
	_validate_section "interface" "$1"

	local device ip4table ip6table
	config_get device "$1" device
	config_get ip4table "$1" ip4table

	[ -z "$device" ] || [ -z "$ip4table" ] && return

	procd_open_instance
	# shellcheck disable=SC2086
	procd_set_param command /bin/otb-tracker "$1" $options
	procd_append_param env "OTB_TRACKER_HOSTS=$hosts"
	procd_append_param env "OTB_TRACKER_TIMEOUT=$timeout"
	procd_append_param env "OTB_TRACKER_TRIES=$tries"
	procd_append_param env "OTB_TRACKER_INTERVAL=$interval"
	procd_append_param env "OTB_TRACKER_TABLE=$ip4table"
	procd_append_param env "OTB_TRACKER_DEVICE=$device"
	procd_set_param respawn 0 10 0
	procd_set_param stderr 1
	procd_close_instance
}

start_service() {
	config_load network
	config_foreach _launch_tracker interface
}

service_triggers() {
	procd_add_reload_trigger otb-tracker network
}

reload_service() {
	stop
	start
}
