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

START=70

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
	
    # 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
            # Get the IP address of this interface.
            ADDR=`$IP addr show dev $IF 2>/dev/null | grep "^ *inet .* $IF\$" | 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 $IF. Skipping." >&2
            fi
    done

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

    $NATPMP -p $PIDFILE -b -i "$PUBLIC_IF" $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

    kill $(cat $PIDFILE)
}
