#!/bin/bash

# This script handles firewall configuration for given iface name.

usage()
{
	echo "Usage: $0 <interface> <action>" > /dev/stderr
	exit 1
}


[ -z "$1" -o -z "$2" ] && usage

NAME=$1
ACTION=$2

. ${SCRIPTDIR:=/etc/net/scripts}/functions
. ${SCRIPTDIR:=/etc/net/scripts}/functions-fw

[ -z "$NETPROFILE" ] && init_netprofile

if [ -d $IFACEDIR/$NAME@$NETHOST ]; then
	MYIFACEDIR=$IFACEDIR/$NAME@$NETHOST
else
	MYIFACEDIR=$IFACEDIR/$NAME
fi

[ -d "$MYIFACEDIR" ] || {
	print_error "interface configuration directory '$MYIFACEDIR' not found"
	exit 1
}

[ -z "$CONFIG_FW" ] && {
	SourceIfNotEmpty `profiled_filename /etc/net/ifaces/default/options`
	SourceIfNotEmpty `profiled_filename /etc/net/ifaces/default/fw/options`
}

if  ! is_yes "$CONFIG_FW";  then
	print_message "Firewall is disabled"
	exit 1
fi

SourceIfNotEmpty "$MYIFACEDIR/fw/options"

# FIXME
#init_netprofile
#pickup_options

iptables_local_start()
{
	is_yes "$IPTABLES_HUMAN_SYNTAX" && [ -z "$iptables_syntax" ] && { 
		iptables_load_syntax `profiled_filename /etc/net/ifaces/default/fw/iptables/syntax`
		iptables_create_sed_rules "$iptables_syntax"
	}			
	is_yes "$IPTABLES_HUMAN_SYNTAX" && [ -z "$iptables_sed_rules" ] && iptables_create_sed_rules "$iptables_syntax"
	iptables_start "$NAME"
}

iptables_local_stop()
{
	is_yes "$IPTABLES_HUMAN_SYNTAX" && [ -z "$iptables_syntax" ] && { 
		iptables_load_syntax `profiled_filename /etc/net/ifaces/default/fw/iptables/syntax`
		iptables_create_sed_rules "$iptables_syntax"
	}			
	is_yes "$IPTABLES_HUMAN_SYNTAX" && [ -z "$iptables_sed_rules" ] && iptables_create_sed_rules "$iptables_syntax"
	iptables_stop "$NAME"
}

case "$FW_TYPE" in
	iptables)
		is_dir_ok "$MYIFACEDIR/fw/$FW_TYPE" || exit 0
		export FW_TYPE IPTABLES_SYSTEM_CHAINS IPTABLES_HUMAN_SYNTAX IPTABLES_INPUT_POLICY \
				IPTABLES_FORWARD_POLICY IPTABLES_OUTPUT_POLICY
		# Load own interface syntax if exists
		[ "$NAME" != "default" ] && is_yes "$IPTABLES_HUMAN_SYNTAX" && {
			is_file_ok "$MYIFACEDIR/fw/$FW_TYPE/syntax" && ! is_empty_file "$MYIFACEDIR/fw/$FW_TYPE/syntax" && {
				IPTABLES_SYNTAX_DIR="$MYIFACEDIR/fw/$FW_TYPE"
				export iptables_syntax=
				export iptables_sed_rules=
			}
		}
		case "$ACTION" in
			start)
				iptables_local_start
				;;
			stop)
				iptables_local_stop
				;;
			restart)
				iptables_local_stop
				iptables_local_start
				;;
			reload)
				iptables_local_stop
				iptables_local_start
				;;
			*)
				echo "${0##*/} {start|stop|restart|reload}"
				exit 1
				;;
		esac
		;;
	*)
		echo "Firewall type $FW_TYPE doesn't supported"
esac

