#!/bin/sh /etc/rc.common
include /lib/network
scan_interfaces
config_get WAN wan ifname
START=46

#
# This functions forwards a port. The next args are required:
# $1 = WAN interface
# $2 = Origin Port
# $3 = Destination IP
# $4 = Destination Port
# $5 = protocol used
#


forward_port() {
        iptables -t nat -A prerouting_rule -i $1 -p $5 --dport $2 -j DNAT --to-destination $3:$4
        pdots=`echo $4 | sed 's/-/:/g'`
        iptables        -A forwarding_rule -i $1 -p $5 --dport $pdots -d $3 -j ACCEPT
}

remove_port() {
        iptables -t nat -D prerouting_rule -i $1 -p $5 --dport $2 -j DNAT --to-destination $3:$4  2> /dev/null
        pdots=`echo $4 | sed 's/-/:/g'`
        iptables        -D forwarding_rule -i $1 -p $5 --dport $pdots -d $3 -j ACCEPT 2> /dev/null
}

start(){
	while read line
        do
        	forward_port "$WAN" $line
        done < /etc/config/openports
}

stop(){
        while read line
        do
                remove_port "$WAN" $line
        done < /etc/config/openports

}

restart(){
	stop
	start
}
