#!/bin/sh
#

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

IPTABLES=/sbin/iptables

SYIPFILTER_CONF=/etc/sysconfig/syipfilter.conf

[ ! -f $SYIPFILTER_CONF ] && exit 0

. $SYIPFILTER_CONF


##################################################
# functions
##################################################
ipfilter_cleanup() {
	$IPTABLES -F
	$IPTABLES -X
	$IPTABLES -Z
}


ipfilter_deny_init() {
	ipfilter_cleanup
	$IPTABLES -P INPUT ACCEPT
	$IPTABLES -P FORWARD ACCEPT
	$IPTABLES -P OUTPUT ACCEPT
}


ipfilter_accept_init() {
	ipfilter_cleanup
	$IPTABLES -A INPUT -i lo -j ACCEPT
	$IPTABLES -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
	
	$IPTABLES -P INPUT DROP
	$IPTABLES -P FORWARD DROP
	$IPTABLES -P OUTPUT ACCEPT
}


register_deny_ips() {
	echo "$IPTABLES -A INPUT -m iprange --src-range $1 -j DROP"
	$IPTABLES -A INPUT -m iprange --src-range $1 -j DROP
}


register_accept_ips() {
	echo "$IPTABLES -A INPUT -m iprange --src-range $1 -j ACCEPT"
	$IPTABLES -A INPUT -m iprange --src-range $1 -j ACCEPT
}

##################################################
# end of functions
##################################################


if [ "$IPFILTER_SERVICE" != "yes" ]; then
	echo "IP Filtering is disabled"
	ipfilter_deny_init
	
	exit 0
fi

case "$1" in
	start)
		if [ "$IPFILTER_POLICY" = "ACCEPT" ]; then
			echo "syipfilter : Accept policy"
			ipfilter_accept_init

			while read i; do
				register_accept_ips $i
			done < $IPFILTER_ACCEPT_LIST
		elif [ "$IPFILTER_POLICY" = "DENY" ]; then
			echo "syipfilter : Deny policy"
			ipfilter_deny_init

			while read i; do
				register_deny_ips $i
			done < $IPFILTER_DENY_LIST
		else
			echo "syipfilter : Wrong policy"
			exit 1
		fi
		;;
	stop)
		ipfilter_deny_init
		;;
	status)
		$IPTABLES -L -v
		;;
	restart)
		$0 stop
		$0 start
		;;
	*)
		echo "Usage: syipfilter {start|stop|status|restart}"
		exit 1
		;;
esac

exit 0

