#!/bin/bash

# This script handles firewall configuration for given iface name.

usage()
{
	echo '/etc/net FireWall handler'
	echo "Usage: $0 <interface> <action>" >&2
	exit 1
}


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

NAME=$1
ACTION=$2

pickup_defaults
. ${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

case "$FW_TYPE" in
	iptables)
	 	[ -d "$MYIFACEDIR/fw/$FW_TYPE" ] || exit 0
		export FW_TYPE IPTABLES_SYSTEM_CHAINS IPTABLES_HUMAN_SYNTAX IPTABLES_INPUT_POLICY \
				IPTABLES_FORWARD_POLICY IPTABLES_OUTPUT_POLICY IPTABLES_RULE_EMBEDDING
		# Load own interface syntax if exists
		[ "$NAME" != "default" ] && is_yes "$IPTABLES_HUMAN_SYNTAX" && {
			[ -f "$MYIFACEDIR/fw/$FW_TYPE/syntax" ] && [ -s "$MYIFACEDIR/fw/$FW_TYPE/syntax" ] && {
				export IPTABLES_SYNTAX_DIR="$MYIFACEDIR/fw/$FW_TYPE"
				export IPTABLES_SYNTAX=
				export IPTABLES_SED_RULES=
			}
		}
		case "$ACTION" in
			start)
				iptables_preload
				iptables_start "$NAME"
				;;
			stop)
				iptables_preload
				iptables_stop "$NAME"
				;;
			restart)
				iptables_preload
				iptables_stop "$NAME"
				iptables_start "$NAME"
				;;
			reload)
				iptables_preload
				iptables_stop "$NAME"
				iptables_start "$NAME"
				;;
			*)
				echo "${0##*/} {start|stop|restart|reload}"
				exit 1
				;;
		esac
		;;
	*)
		echo "Firewall type $FW_TYPE isn't supported"
esac

