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

START=90
STOP=10

USE_PROCD=1
PROG=/usr/sbin/udp-broadcast-relay-redux
NAME=udp-broadcast-relay-redux
PIDCOUNT=0

validate_section_udp_broadcast_relay_redux()
{
    uci_validate_section udp_broadcast_relay_redux udp_broadcast_relay_redux "${1}" \
	'id:uinteger' \
	'port:port' \
	'network:list(string)' \
	'src_override:ip4addr' \
	'dest_override:ip4addr'

    [ -z "$id" ] && return 1

    [ -z "$network" ] && return 1

    [ -z "$port" ] && return 1

    return 0
}

udp_broadcast_relay_redux_instance() {
    local net network ifname id port src_override dest_override

    validate_section_udp_broadcast_relay_redux "${1}" || {
	echo "Validation failed"
	return 1
    }

    PIDCOUNT="$((PIDCOUNT + 1))"

    procd_open_instance
    procd_set_param command "$PROG" "--id" "${id}" "--port" "${port}"

    for net in $network; do
	network_get_device ifname "$net"
	if [ -z "$ifname" ]; then
	    network_get_physdev ifname "$net"
	fi
	if [ -n "$ifname" ]; then
	    procd_append_param command "--dev" "$ifname"
	    procd_append_param netdev "$ifname"
	fi
    done

    if [ -n "$src_override" ] ; then
        procd_append_param command "-s" "$src_override"
    fi

    if [ -n "$dest_override" ] ; then
        procd_append_param command "-t" "$dest_override"
    fi

    procd_add_jail ubr-${PIDCOUNT}
    procd_close_instance
}

start_service() {
    . /lib/functions.sh
    . /lib/functions/network.sh

    config_load udp_broadcast_relay_redux
    config_foreach udp_broadcast_relay_redux_instance udp_broadcast_relay_redux
}

service_triggers() {
    procd_add_reload_trigger "udp_broadcast_relay_redux"
    procd_add_validation validate_section_udp_broadcast_relay_redux
}
