#!/bin/sh

# IPv4 part of the setup script, to be called with
# wan-interface-name lan-interface-name mapped-address \
# port-range-min port-range-max

WANIF=$1
LANIF=$2
MAPPED=$3
PRMIN=$4
PRMAX=$5

echo "my WAN interface is:" $WANIF
echo "my LAN interface is:" $LANIF
echo "the global mapped address is:" $MAPPED
echo "the port range is": $PRMIN ".." $PRMAX

set -x

sysctl -w net.ipv4.ip_forward=1
ip route add 224.0.0.0/4 dev $LANIF
touch /tmp/leases

# this is the dhcp server for the local network
/usr/sbin/dhcpd -q -4 -cf /etc/sdb4/confs/dhcpd4.conf -lf /tmp/leases $LANIF

iptables -F FORWARD
iptables -P FORWARD ACCEPT
iptables -t nat -F PREROUTING
iptables -t nat -F POSTROUTING

iptables -t nat -N SDCTLD
iptables -t nat -A PREROUTING -d $MAPPED -i tun0 -j SDCTLD
iptables -t filter -N SDCTLD
iptables -t filter -A FORWARD -i $LANIF ! -o $LANIF -j SDCTLD

iptables -t nat -A POSTROUTING -o tun0 -p tcp -j SNAT \
 --to-source $MAPPED:$PRMIN-$PRMAX
iptables -t nat -A POSTROUTING -o tun0 -p udp -j SNAT \
 --to-source $MAPPED:$PRMIN-$PRMAX
iptables -t nat -A POSTROUTING -o tun0 -p icmp -j SNAT \
 --to-source $MAPPED:$PRMIN-$PRMAX

export WANIF MAPPED SDPARAMS=direct/tcp:$PRMIN-$PRMAX/udp:$PRMIN-$PRMAX/

/usr/sbin/sdctld -f /etc/sdb4/confs/sdctld.conf
