SYSCONFIG_FILE_4="/etc/sysconfig/iptables"
SYSCONFIG_FILE_6="/etc/sysconfig/ip6tables"

IPTABLES_SERVICE_NAME_4="iptables"
IPTABLES_SERVICE_NAME_6="ip6tables"

IPTABLES_BIN_PATH="/sbin"

rule_template() {
	echo "INPUT -p udp --sport 161 --dport $1 -j ACCEPT"
}

add_rules_iptables() {
# $1 - iptables(ip6tables)
# $2 - port 
	"${IPTABLES_BIN_PATH}/$1" "-I" `rule_template $2`
	
}

delete_rules_iptables() {
# $1 - iptables(ip6tables)
# $2 - port
	"${IPTABLES_BIN_PATH}/$1" "-D" `rule_template $2`
}

save_rules_iptables() {
	service "$1"-save > "$2"
}

change_rules_fedora() {
	local ACTION=$1		# delete or add
	local NAME=$2 		# iptables(iptables6) restart service
	local CONFFILE=$3	# config file path for sysconfig-firewall
	local PORT=$4
		
	#check service and configfile availability
	if ! [ -f "$CONFFILE" ]; then
		log_message "cannot find file $CONFFILE"		
		return 1
	fi
	
	# save iptables on/off status
	service "$NAME" status 
	local STATUS=$?
	log_message "STATUS <$STATUS>"

	# at fedora 16 "iptables status" always returns 0
	# so turn it on in any case
	# TODO: try to determine whether iptables on or off
	service "$NAME" start
	
	
	# add or delete new rules to ip(6)tables 
	# first, delete old rules 
	# in order to avoid repeated rules
	delete_rules_iptables "$NAME" "$PORT"
	if [ $ACTION == "add" ] ; then
		add_rules_iptables "$NAME" "$PORT"
	fi
	
	# drop all rules to configfile
	service "$NAME" save

	# restore iptables on/off status
	if [ "$STATUS" != "0" ] ; then
		log_message "#restore iptables off status"
		service "$NAME" stop		 
	fi	
}

plug_hifw_fedora() {
	log_message "delete_rules_throught_Fedora_RH"
	
	change_rules_fedora "delete" "$IPTABLES_SERVICE_NAME_4" "$SYSCONFIG_FILE_4" "$1"
	change_rules_fedora "delete" "$IPTABLES_SERVICE_NAME_6" "$SYSCONFIG_FILE_6" "$1"
}

make_hifw_fedora() {
# mhifw - make hole in firewall for Fedora and RH distr
# add rules to iptables, then save new rules in /etc/systocfig/ip(6)tables
	change_rules_fedora "add" "$IPTABLES_SERVICE_NAME_4" "$SYSCONFIG_FILE_4" "$1"
	local RESULT="$?"
	change_rules_fedora "add" "$IPTABLES_SERVICE_NAME_6" "$SYSCONFIG_FILE_6" "$1"
	
	return $RESULT
}

