#! /bin/sh
# /etc/init.d/enable-nat
#  Enabling Network Address Translation for clients
#  sitting in the thin client network behind eth1
#
# chkconfig: 2345 52 78
# description: Enabling NAT for clients behind eth1

IPTABLES=/sbin/iptables

NETWORK_TO_NAT=
OUTSIDE_IF=eth0

# Only enable by default if LTSP is installed
if [ -e /opt/ltsp ] ; then
    NETWORK_TO_NAT="192.168.0.0/24"
fi

if [ -f /etc/default/enable-nat ] ; then
    . /etc/default/enable-nat
fi

# Bail out if no iptables binary or no configuration
[ -x ${IPTABLES} -a "$NETWORK_TO_NAT" ] || exit 0

do_status() {
    $IPTABLES -L -t nat |grep -A3 POSTROUTING
}

is_enabled() {
    if do_status | grep -q "$NETWORK_TO_NAT" ; then
	true
    else
	false
    fi
}

do_start() {
    if is_enabled ; then
	echo "NAT for clients on network $NETWORK_TO_NAT already enabled."
    else
	echo "Enabling NAT for clients on network $NETWORK_TO_NAT."
	$IPTABLES -t nat -A POSTROUTING -s $NETWORK_TO_NAT -o $OUTSIDE_IF -j MASQUERADE
    fi

    # Enable IP-forwarding if it isn't enabled already.
    if [ 0 = "`cat /proc/sys/net/ipv4/ip_forward`" ]; then
	echo "Enabling IPv4 forwarding."
	echo 1 > /proc/sys/net/ipv4/ip_forward
    fi

    do_status
}

do_stop() {
    if is_enabled ; then
	echo "Disabling NAT for clients on network $NETWORK_TO_NAT."
	$IPTABLES -F -t nat
    else
	echo "NAT for clients on network $NETWORK_TO_NAT already disabled."
    fi
    do_status
}

case "$1" in
    start)
        do_start
        ;;
    stop)
        do_stop
        ;;
    restart|force-reload)
        do_stop
        do_start
        ;;
    status)
        do_status
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|force-reload|status}"
        exit 2
        ;;
esac
exit 0
