#! /bin/sh
#
### BEGIN INIT INFO
# Provides: ndn-iptables
# Required-Start: $remote_fs $syslog $networking $procps
# Required-Stop:     $remote_fs $syslog
# Default-Start: 2 3 5
# Default-Stop: 0 1 4 6
# Short-Description: iptables starting
# Description: manage iptables services.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
SAVE=/sbin/iptables-save
RESTORE=/sbin/iptables-restore
IPTABLES=/sbin/iptables
SAVE6=/sbin/ip6tables-save
RESTORE6=/sbin/ip6tables-restore
IPTABLES6=/sbin/ip6tables
IPSET=/sbin/ipset
IPSETDIR=/var/lib/ipset
NAME=ndn-iptables
DESC=ndn-iptables
BASERULES=/var/lib/iptables/base.rules
MYRULES=/var/lib/iptables/my.rules
AUTORULES=/var/lib/iptables/auto.rules
BASERULES6=/var/lib/ip6tables/base.rules
MYRULES6=/var/lib/ip6tables/my.rules
AUTORULES6=/var/lib/ip6tables/auto.rules

LISTS=$(/bin/ls /var/lib/ipset | egrep "\.ipset$"|sort)

test -x $SAVE || exit 0
test -x $RESTORE || exit 0
test -f $BASERULES || exit 0
test -f $MYRULES || exit 0
test -x $SAVE6 || exit 0
test -x $RESTORE6 || exit 0
test -f $BASERULES6 || exit 0
test -f $MYRULES6 || exit 0
test -x $IPSET || exit 0

# Include ndn-iptables defaults if available
if [ -f /etc/default/ndn-iptables ] ; then
	. /etc/default/ndn-iptables
fi

set -e

case "$1" in
  start)
	echo -n "Starting $DESC: "
        for L in $LISTS
        do
                echo -n "Restoring ipset $L ..." 
                $IPSET restore -f $IPSETDIR/$L -exist || true
                echo "done"
        done
	cat $BASERULES $AUTORULES $MYRULES 2>/dev/null | awk -F# '{print $1}' | $RESTORE || true
	cat $BASERULES6 $AUTORULES6 $MYRULES6 2>/dev/null | awk -F# '{print $1}' | $RESTORE6 || true
	echo "$NAME."
	;;
  stop)
	echo -n "Stopping $DESC: "
	$IPTABLES -F || true
	$IPTABLES6 -F || true
	echo "$NAME."
        echo -n "Stopping ipset ..."
        $IPSET flush || true
        echo "done"
	;;
  #reload)
	#
	#	If the daemon can reload its config files on the fly
	#	for example by sending it SIGHUP, do it here.
	#
	#	If the daemon responds to changes in its config file
	#	directly anyway, make this a do-nothing entry.
	#
	# echo "Reloading $DESC configuration files."
	# start-stop-daemon --stop --signal 1 --quiet --pidfile \
	#	/var/run/$NAME.pid --exec $DAEMON
  #;;
  restart|force-reload)
	#
	#	If the "reload" option is implemented, move the "force-reload"
	#	option to the "reload" entry above. If not, "force-reload" is
	#	just the same as "restart".
	#
	echo -n "Restarting $DESC: "
	$0 stop
	sleep 1
	$0 start
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart}" >&2
	exit 1
	;;
esac

exit 0
