#!/bin/sh

. /lib/functions.sh

ZONE_NAME_FILE="/tmp/twamp_fw_zone"

#created by the icwmp package
log() {
	echo "${@}"|logger -t firewall.twamp -p info
}

if [ ! -f "/etc/config/twamp" ]; then
	exit 0;
fi

collect_zone_name() {
	local name network

	config_get name "${1}" name ""
	if [ -z "${name}" ]; then
		return
	fi

	config_get network "${1}" network ""
	for i in ${network}; do
		var="${i}_zone"
		echo "${var}=${name}" >> "${ZONE_NAME_FILE}"
	done
}

load_zone_names() {
	rm -f "${ZONE_NAME_FILE}"
	config_load firewall
	config_foreach collect_zone_name zone
}

get_firewall_zone() {
	if [ ! -f "${ZONE_NAME_FILE}" ]; then
		echo ""
		return
	fi

	var="${1}_zone="
	name="$(cat ${ZONE_NAME_FILE} | grep ${var} | head -n 1 | cut -d'=' -f 2)"
	echo "${name}"
}

configure_firewall() {
	local enable port interface

	config_get enable "${1}" enable "1"
	config_get port "${1}" port
	config_get interface "${1}" interface
	if [ "$enable" -eq 0 ] || [ -z "${port}" ] || [ -z "${interface}" ]; then
		return 0;
	fi

	zone_name="$(get_firewall_zone ${interface})"
	if [ -z "${zone_name}" ]; then
		log "Rule can not be added without zone name for interface ${interface}"
		return
	fi

	iptables -w 1 -nL zone_"${zone_name}"_input 2>/dev/null 1>&2
	if [ "$?" -eq 0 ]; then
		iptables -w 1 -I zone_"${zone_name}"_input -p udp --dport "${port}" -j ACCEPT -m comment --comment "TWAMP reflector port"
	fi
}

delete_rule() {
        zone_name="$(get_firewall_zone ${1})"
        if [ -z "${zone_name}" ]; then
                return
        fi

        while iptables -w 1 -nL zone_"${zone_name}"_input --line-numbers 2>/dev/null | grep "TWAMP reflector port"; do
		rule_num="$(iptables -w 1 -nL zone_"${zone_name}"_input --line-numbers | grep "TWAMP reflector port" | head -1|awk '{print $1}')"
		if [ -n "${rule_num}" ]; then
			iptables -w 1 -D zone_"${zone_name}"_input "${rule_num}";
		fi
	done
}

# Loop through all interfaces and delete the twamp reflector rule from interface's input chain
load_zone_names

config_load network
config_foreach delete_rule interface

config_load twamp
config_get twamp_enable twamp enable "0"
if [ "${twamp_enable}" -eq "0" ]; then
	rm -f "${ZONE_NAME_FILE}"
	exit 0;
fi

config_foreach configure_firewall twamp_reflector
rm -f "${ZONE_NAME_FILE}"
