#!/bin/sh
# Written by Steven Shiau <steven@nchc.org.tw> to use in DRBL for RedHat
# License: GPL
#
# set the iptables NAT
# clean the old tables

# Load DRBL setting and functions
if [ ! -f "/opt/drbl/sbin/drbl-conf-functions" ]; then
  echo "Unable to find /opt/drbl/sbin/drbl-conf-functions! Program terminated!" 
  exit 1
fi
. /opt/drbl/sbin/drbl-conf-functions

#
check_if_root

# main
USAGE="Usage: $0 {start|stop|restart}"
switch=$1

#
if [ $# -ne 1 ]; then
  echo "$USAGE"
  echo "Example: use the following to start the NAT service for clients"
  echo "$0 start"
  exit 1
fi
#
case "$switch" in
   "start"|"restart")
      [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
      echo "Now start the NAT service..."
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL

      /etc/init.d/iptables stop

      if [ -f /etc/sysconfig/iptables ]; then 
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
        echo "Warning! /etc/sysconfig/iptables is renamed as iptables.drblsave!"
        echo "Your firewall rules is overwritten!!! We set the NAT for clients with IP address 192.168.x.x to access this DRBL server!"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
        mv -f /etc/sysconfig/iptables /etc/sysconfig/iptables.drblsave
      fi
      /sbin/iptables -P FORWARD ACCEPT
      /sbin/iptables -P INPUT ACCEPT
      #/sbin/iptables -t nat -A POSTROUTING -s 192.168.0.0/255.255.0.0 -j MASQUERADE
      for ihost in $drblroot/*; do
         ip="`basename $ihost`"
        /sbin/iptables -t nat -A POSTROUTING -s $ip/255.255.255.255 -j MASQUERADE
      done
      #/sbin/iptables-save > /etc/sysconfig/iptables
      /etc/init.d/iptables save

      # Some bug in kernel 2.6.9, so we do not want to remove the module before 
      # restart the iptables
      if [ ! -f /etc/sysconfig/iptables-config ]; then
	echo 'IPTABLES_MODULES_UNLOAD="no"' > /etc/sysconfig/iptables-config
      else
        if grep -E -q "^[#\s]*IPTABLES_MODULES_UNLOAD=.*" /etc/sysconfig/iptables-config; then
           perl -p -i -e "s/^[#\s]*IPTABLES_MODULES_UNLOAD=.*/IPTABLES_MODULES_UNLOAD=\"no\"/" /etc/sysconfig/iptables-config 
        else
	   echo 'IPTABLES_MODULES_UNLOAD="no"' >> /etc/sysconfig/iptables-config
        fi
      fi

      #Making the rules stick and load on boot:
      perl -p -i -e "s/^net.ipv4.ip_forward.*/net.ipv4.ip_forward = 1/" /etc/sysctl.conf
      # Turn on ip_forward now.
      if [ "`cat /proc/sys/net/ipv4/ip_forward `" != "1" ]; then
        echo "Turn on ip_forward now."
        echo 1 > /proc/sys/net/ipv4/ip_forward
      else 
        echo "ip_forward is already on."
      fi
      ;;
    stop)
      [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
      echo "Now stop the NAT service..."
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      /etc/init.d/iptables stop
      ;;
    *)
      echo "$USAGE"
esac
