#!/bin/bash
#
# Init file for Dwall firewall
#
# Written by Dag Wieers <dag@wieers.com>.
#
# chkconfig: - 09 91
# description: Dwall firewall
#
# processname: dwall
# config: /etc/dwall/dwall.conf
# pidfile: /var/run/dwall

# source function library
source /etc/rc.d/init.d/functions

# Source networking configuration.
source /etc/sysconfig/network

# Check that networking is up.
[ "${NETWORKING}" != "no" ] || exit 0

### Check if Dwall is installed correctly
[ -x "/usr/bin/dwall" ] || exit 1
[ -r "/etc/dwall/dwall.conf" ] || exit 1

source /etc/dwall/dwall.conf

### Check if Dwall firewall exists
[ -x "$FIREWALL" ] || exit 0

### Check if iptables is installed
[ -x /sbin/iptables ] || exit 0


RETVAL=0
prog="dwall"
desc="Dwall iptables firewall"

KERNELMAJ="$(uname -r | sed                   -e 's,\..*,,')"
KERNELMIN="$(uname -r | sed -e 's,[^\.]*\.,,' -e 's,\..*,,')"

if [ "$KERNELMAJ" -lt 2 ] ; then
        exit 0
fi
if [ "$KERNELMAJ" -eq 2 -a "$KERNELMIN" -lt 3 ] ; then
        exit 0
fi
if  /sbin/lsmod 2>/dev/null |grep -q ipchains ; then
        # Don't do both
        exit 0
fi

### What does this do exactly ?
iftable() {
        if fgrep -qsx $1 /proc/net/ip_tables_names; then
                iptables -t "$@"
        fi
}

start() {
	echo -n $"Starting $desc ($prog): "
	daemon $FIREWALL
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog
	return $RETVAL
}

stop() {
	echo -n $"Shutting down $desc ($prog): "
        iptables -F
        iptables -X
	iptables -P INPUT ACCEPT
	iptables -P FORWARD DROP
	iptables -P OUTPUT ACCEPT
	success
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog
	return $RETVAL
}

restart() {
	stop
	start
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|reload)
	restart
	;;
  condrestart)
	[ -e /var/lock/subsys/$prog ] && restart
	RETVAL=$?
	;;
  status)
	status $prog
	RETVAL=$?
	;;
  *)
	echo $"Usage: $0 {start|stop|restart|condrestart|status}"
	RETVAL=1
esac

exit $RETVAL
