#!/bin/bash
# chkconfig: 35 20 80
# description: loads saved iptables configuration
#
# config: /etc/config.d/iptables

IPTSAVE=`which iptables-save`
IPTRESTORE=`which iptables-restore`
IPTCONFIG=/etc/config.d/iptables

start() {
    echo -n "Starting iptables: "
    if [ ! -e /var/run/iptables ]; then
        if [ -z $IPTSAVE -o -z $IPTRESTORE ]; then
	    echo -n "missing iptables binaries"
	    echo -e $RESULT_FAIL
	else
	    if [ ! -e "$IPTCONFIG" ]; then
	        echo -n "no config to load, forwarding enabled"
		echo -e $RESULT_WARN
            else
	        echo 1 > /proc/sys/net/ipv4/ip_forward
	        $IPTRESTORE < $IPTCONFIG
	        echo -e $RESULT_OK
	    fi
	    touch /var/run/iptables
	fi
    else
        echo -n "already running"
	echo -e $RESULT_WARN
    fi
}

stop() {
    echo -n "Stopping iptables: "
    if [ ! -e /var/run/iptables ]; then
        echo -n "not running";
	echo -e $RESULT_FAIL
    else
        if [ -z $IPTSAVE -o -z $IPTRESTORE ]; then
            echo -n "missing iptables binaries"
            echo -e $RESULT_FAIL
        else
	    $IPTSAVE > $IPTCONFIG
	    # restore EMPTY iptables ruleset
            $IPTRESTORE < $IPTCONFIG-empty
	    echo 0 > /proc/sys/net/ipv4/ip_forward

	    rm /var/run/iptables
	    echo -e $RESULT_OK
	fi
    fi
}

restart() {
   stop
   start
}

status() {
   echo -n "iptables status: "

   if [ -e /var/run/iptables ]; then
      echo "running"
   else
      echo "not running"
   fi
}

case $1 in
   start|stop|restart|status) ;;
   *)     echo "Usage: $0 {start|stop|restart|status}"; exit 1  ;;
esac

. /lib/lsb/init-functions
