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

START=70

SERVICE_DAEMONIZE=1
SERVICE_WRITE_PID=1

IP=$(which ip)
IPTABLES=$(which iptables)
NATPMP=/usr/sbin/natpmp
PIDFILE=/var/run/natpmp.pid

natpmp_config() {
	local cfg="$1"

	config_get PUBLIC_IF "$cfg" outbound_interface
	config_get PRIVATE_IFS "$cfg" inbound_interfaces
	config_get IPTABLES_CHAIN "$cfg" iptables_chain
}

start() {
	config_load natpmp
	config_foreach natpmp_config natpmp

	. /lib/functions/network.sh

	# Flush all the rules in the natpmp chain, or create it, if it doesn't exists.
	$IPTABLES -t nat -F $IPTABLES_CHAIN 2>/dev/null || \
	$IPTABLES -t nat -N $IPTABLES_CHAIN

	# Handle all incoming connections in the natpmp chain.
	$IPTABLES -t nat -D PREROUTING -j $IPTABLES_CHAIN 2>/dev/null || true
	$IPTABLES -t nat -A PREROUTING -j $IPTABLES_CHAIN

	# Iterate through the private interfaces.
	BIND_ARGS=""
	for IF in $PRIVATE_IFS; do
		local dev
		network_get_device dev "$IF" || dev="$IF"

		# Get the IP address of this interface.
		ADDR=`$IP addr show dev $dev 2>/dev/null | grep "^ *inet .* $dev\$" | cut -d " " -f 6 | cut -d / -f 1`
		if [ -n "$ADDR" ] ; then
			# Add the IP address to the argument list.
			BIND_ARGS="$BIND_ARGS -a $ADDR"
		else
			echo "Could not get IP address of interface $dev. Skipping." >&2
		fi
	done

	if [ -z "$BIND_ARGS" ] ; then
		echo "No IP addresses to bind to. Exiting." >&2
		exit 1
	fi

	local pubdev
	network_get_device pubdev "$PUBLIC_IF" || pubdev="$PUBLIC_IF"

	SERVICE_PID_FILE="$PIDFILE"
	service_start $NATPMP -i "$pubdev" $BIND_ARGS -- "$IPTABLES_CHAIN"
}

stop() {
	config_load natpmp
	config_foreach natpmp_config natpmp

	# Unlink chain
	$IPTABLES -t nat -D PREROUTING -j $IPTABLES_CHAIN 2>/dev/null || true

	# Flush all the rules in the natpmp chain
	$IPTABLES -t nat -F $IPTABLES_CHAIN 2>/dev/null && \
	$IPTABLES -t nat -X $IPTABLES_CHAIN

	SERVICE_PID_FILE="$PIDFILE"
	service_stop $NATPMP
}