#!/bin/sh
# Functions for iptables for tree-firewall
# License: GNU GPL
# (c) 2002 Olgierd Pieczul <wojrus@pld.org.pl>

# $Revision: 1.11 $, $Date: 2002/07/17 08:06:24 $

add_rule() {
	if $debug; then
		echo iptables -t $3 -A $1 $2
		iptables -t $3 -A $1 $2
	else
		ret=0
		iptables -t $3 -A $1 $2 >/dev/null 2>/dev/null || ret=1
		return $ret	
	fi
}

addfirst_rule() {
	if $debug; then
		echo iptables -t $3 -I $1 $2
		iptables -t $3 -I $1 $2
	else
		ret=0
		iptables -t $3 -I $1 $2 >/dev/null 2>/dev/null || ret=1
		return $ret	
	fi
}
	
del_rule() {
	if $debug; then
		echo iptables -t $3 -D $1 $2
		iptables -t $3 -D $1 $2
	else
		ret=0
		iptables -t $3 -D $1 $2 >/dev/null 2>/dev/null || ret=1
		return $ret
	fi
}
																		
policy_rule() {
	if $debug; then
		echo iptables -t $3 -P $1 $2
		iptables -t $3 -P $1 $2
	else
		ret=0
		iptables -t $3 -P $1 $2 >/dev/null 2>/dev/null || ret=1
		return $ret
	fi
}

tables() {
	action=$1; set=$2; ret=0
	if [ "$action" = "policy" ]; then
			dir="policies"
	else
			dir="sets"
	fi
	for p_table in $root/$dir/$set/*; do
		if [ -d $p_table ]; then
			# create chains in table
			if [ "$action" = "add" ] || [ "$action" = "addfirst" ]; then
				for chain in $(ls -1 $p_table/* | egrep -v '~$'); do
					if [ -f $chain ]; then
						chain=$(basename $chain)
						table=$(basename $p_table)
						chain_exist $chain $table || chain_create $chain $table
					fi
				done
			fi
			chains $action $p_table $(basename $p_table) || ret=1 
			# remove chains from table
			if [ "$action" = "del" ]; then
				for chain in $(ls -1 $p_table/* | egrep -v '~$'); do
					if [ -f $chain ]; then
						chain=$(basename $chain)
						table=$(basename $p_table)
						chain_exist $chain $table && chain_empty $chain $table && {
							chain_references $chain $table || chain_remove $chain $table
					 	}
					fi
				done
			fi
		fi
	done
	return $ret
}

chain_exist() {
chains=$(iptables -n -t $2 -L $1 2>/dev/null | egrep '^Chain') 
if [ "$chains" ]; then
		return 0
else
		return 1
fi
}

chain_empty() {
	if [ "$(iptables -n -L $1 2>/dev/null | egrep '^[^(Chain|target)]')" ] ; then
		return 1
	else
		return 0
	fi
}

chain_references() {
	if [ "$(iptables -n -L $1 2>/dev/null | egrep '^Chain' | sed 's/^.*(\(.*\) references).*$/\1/')" == "0" ]; then
		return 1
	else
		return 0
	fi
}

chain_create () {
	if $debug; then
		echo iptables -t $2 -N $1 
	fi
	iptables -t $2 -N $1 
}

chain_remove () {
	if $debug; then
		echo iptables -t $2 -X $1 
	fi
	iptables -t $2 -X $1
}
