. /etc/functions.sh
include /lib/network
scan_interfaces

upnp_ipt() {
	iptables "$@" 2>/dev/null
}

upnp_firewall_addif() {
	local extif
	local extip
	local iface

	config_load upnpd
	config_get iface config external_iface

	[ -n "$INTERFACE" -a "$INTERFACE" != "$iface" ] && return

	config_load network
	config_get extip "${iface:-wan}" ipaddr
	config_get extif "${iface:-wan}" ifname

	logger -t "upnp firewall" "adding wan interface $extif($extip)"

	upnp_ipt -t nat -N miniupnpd_${iface:-wan}_rule
	upnp_ipt -t nat -A miniupnpd_${iface:-wan}_rule -i $extif -d $extip -j MINIUPNPD
	upnp_ipt -t nat -A prerouting_rule -j miniupnpd_${iface:-wan}_rule

	upnp_ipt -t filter -N miniupnpd_${iface:-wan}_rule
	upnp_ipt -t filter -A miniupnpd_${iface:-wan}_rule -i $extif -o ! $extif -j MINIUPNPD
	upnp_ipt -t filter -A forwarding_rule -j miniupnpd_${iface:-wan}_rule
}

upnp_firewall_delif() {
	local iface

	config_load upnpd
	config_get iface config external_iface

	[ -n "$INTERFACE" -a "$INTERFACE" != "$iface" ] && return

	logger -t "upnp firewall" "removing wan interface"

	upnp_ipt -t nat -D prerouting_rule -j miniupnpd_${iface:-wan}_rule
	upnp_ipt -t nat -F miniupnpd_${iface:-wan}_rule
	upnp_ipt -t nat -X miniupnpd_${iface:-wan}_rule

	upnp_ipt -t filter -D forwarding_rule -j miniupnpd_${iface:-wan}_rule
	upnp_ipt -t filter -F miniupnpd_${iface:-wan}_rule
	upnp_ipt -t filter -X miniupnpd_${iface:-wan}_rule
}

upnp_firewall_start() {
	upnp_ipt -t nat -N MINIUPNPD
	upnp_ipt -t filter -N MINIUPNPD
	upnp_firewall_addif
}

upnp_firewall_stop() {
	upnp_firewall_delif
	upnp_ipt -t nat -F MINIUPNPD
	upnp_ipt -t nat -X MINIUPNPD
	upnp_ipt -t filter -F MINIUPNPD
	upnp_ipt -t filter -X MINIUPNPD
}
