#!/bin/sh
# Tool for help in building firewalls using iptables/ipchains.
# License: GNU GPL
# (c) 2002 Olgierd Pieczul <wojrus@pld.org.pl>
#
# chkconfig: 345 09 98
# description: firewall is a tool helping in building firewalls

# $Revision: 1.13 $, $Date: 2002/03/28 09:41:11 $

. /etc/rc.d/init.d/functions

if [ -f /etc/sysconfig/firewall ]; then
	. /etc/sysconfig/firewall
fi
if [ ! "$USERSPACE_TOOL" = "ipchains" ] && [ ! "$USERSPACE_TOOL" = "iptables" ]; then
	echo 'You must have USERSPACE_TOOL set to "iptables" or "ipchains"'
	exit 1
fi

debug=false
if [ "$MODE" = "debug" ]; then
    debug=true
fi

. /usr/share/tree-firewall/functions-$USERSPACE_TOOL

fdir=/etc/firewall

# set rules for each chain in given directory.
typeset ret=0
chains() {
	for chain in $2/*; do
		if [ -f $chain ] && echo $chain | egrep -vq '~$'; then
			case "$1" in
			policy)
				args=$(egrep -v "^\#" $chain | head -1)
				if [ "$args" ]; then
					set_policy $(basename $chain) "$args" $3 || ret=1
				fi
				;;
			add | del)
				tmp="$IFS"; IFS='
'
				for args in $(egrep -v "^\#" $chain); do
				IFS="$tmp"
					if [ "$args" ]; then
							$1_rule $(basename $chain) "$args" $3 || ret=1 
					fi
				done
				;;
			esac
		fi
	
	done	
	return $ret
}

case "$1" in

policy)
	if $debug; then
	    echo "# policy"
	    tables policy
	else
	    show "Firewall: Setting policy"
	    busy
	    tables policy && ok || fail	
	fi
	;;

add | del)
	if [ $2 ]; then
		case "$2" in
		all)
			if [ -f $fdir/.sets ]; then
				for set in $(cat $fdir/.sets); do
					$0 $1 $(basename $set)
				done
			else
				for set in $fdir/*; do
					if [ -d $set ] ; then
						$0 $1 $(basename $set)
					fi
				done
			fi
			;;
		*)
			if [ -d $fdir/$2 ] && [ "$2" != "policy" ]; then
				if $debug; then
					echo "# $2"
					tables $1 $2
				else
					if [ "$1" = "add" ]; then
						show "Firewall: Adding set: $2"
					elif [ "$1" = "del" ]; then
						show "Firewall: Removing set: $2"
					fi
					busy
					tables $1 $2 && ok || fail
				fi
				if [ $# -gt 2 ]; then
					action=$1
					shift; shift
					$0 $action $*
				fi
			elif [ "$2" = "policy" ]; then
                if [ $# -gt 2 ]; then
                	action=$1
	                shift; shift
    	            $0 $action $*
				fi
			else
				echo No such set: $2
				if [ $# -gt 2 ]; then
					action=$1
					shift; shift
					$0 $action $*
				fi
				exit 1
			fi
			;;
		esac
	else
		echo "Usage: $0 $1 set-name"
	fi
	;;

clean | stop)
	if $debug; then
		clean
	else
		show "Firewall: Removing all rules"
		busy
		clean && ok || fail
	fi
	;;

tree)
	echo "*"
	tree $fdir -I "*~" | egrep -
	;;

start)
	$0 policy
	$0 add all
	;;

restart)
	$0 clean
	$0 start
	;;	
reload | status)
	echo not implemented
	;;
-v)
	export MODE=debug
	shift
	$0 $*
	;;
*)
	echo "Usage: $0 (add|del|clean|tree|start|restart)"
esac
