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

# Start after bdmf shell, wanconf, and switch-script but before the network-script
START=20
STOP=10

USE_PROCD=1

. /lib/functions.sh

handle_ebtables_chain() {
	local sid="$1"
	local table
	local chain
	local target
	local policy
	local append
	local enabled
	local ret

	config_get table "$sid" table filter
	config_get chain "$sid" chain
	config_get policy "$sid" policy RETURN
	config_get target "$sid" target
	config_get_bool append "$sid" append 1
	config_get_bool enabled "$sid" enabled 1

	[ "$enabled" = "0" ] && return
	[ -z "${chain}" -o -z "${target}" ] && return

	if [ "$append" != "0" ]; then
		append="-A"
	else
		append="-I"
	fi

	ebtables --concurrent -t "$table" -N "$target" -P "$policy" 2> /dev/null
	ret=$?

	if [ $ret -eq 0 ]; then
		ebtables --concurrent -t "$table" ${append} "$chain" -j "$target"
	else
		ebtables --concurrent -t "$table" -D "$chain" -j "$target"
		ebtables --concurrent -t "$table" ${append} "$chain" -j "$target"
	fi
}

handle_ebtables_rule() {
	local sid="$1"
	local table
	local chain
	local target
	local match
	local value
	local enabled
	local ret

	config_get table "$sid" table filter
	config_get chain "$sid" chain
	config_get match "$sid" match
	config_get value "$sid" value
	config_get target "$sid" target RETURN
	config_get_bool append "$sid" append 1
	config_get_bool enabled "$sid" enabled 1

	[ "$enabled" = "0" ] && return
	[ -z "${chain}" -o -z "${target}" ] && return

	if [ "$append" != "0" ]; then
		append="-A"
	else
		append="-I"
	fi

	ebtables --concurrent -t "$table" -D "$chain" ${match} -j "$target" ${value} 2> /dev/null
	ebtables --concurrent -t "$table" ${append} "$chain" ${match} -j "$target" ${value}
}

start_service() {
	config_load bridging
	config_foreach handle_ebtables_chain chain
	config_foreach handle_ebtables_rule rule
}

reload_service() {
	stop
	start
}


service_triggers() {
	procd_add_reload_trigger bridging
}
