#!/bin/sh
#
# Copyright (c) 2018 The DragonFly Project.  All rights reserved.
#
# This code is derived from software contributed to The DragonFly Project
# by Aaron LI <aly@dragonflybsd.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 3. Neither the name of The DragonFly Project nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific, prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
# COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#

# PROVIDE: ipfw3
# REQUIRE: netif
# BEFORE:  NETWORKING

. /etc/rc.subr

name="ipfw3"
rcvar=`set_rcvar`
start_cmd="${name}_start"
start_precmd="${name}_precmd"
stop_cmd="${name}_stop"

ipfw3_precmd()
{
	# Load firewall modules, if not already loaded
	if ! ${SYSCTL} -q net.inet.ip.fw3.enable >/dev/null; then
		for _module in ${ipfw3_modules}; do
			kldload -n ${_module} || return 1
		done
	fi
	return 0
}

ipfw3_start()
{
	# Load firewall rules
	if [ -r "${ipfw3_script}" ]; then
		. "${ipfw3_script}"
		echo "Firewall ${name} rules loaded."
	elif [ "`${ipfw3_program} list`" = "65535  deny" ]; then
		echo 'Warning: kernel has firewall functionality, but' \
		     'firewall rules are not enabled.'
		echo '           All ip services are disabled.'
	fi

	# Enable the firewall
	${SYSCTL_W} net.inet.ip.fw3.enable=1
	echo "Firewall ${name} enabled"
}

ipfw3_stop()
{
	${ipfw3_program} -f flush
	echo "Firewall ${name} rules flushed."

	# XXX/TODO: also flush/delete lookup tables

	# Disable the firewall
	#
	${SYSCTL_W} net.inet.ip.fw3.enable=0
	echo "Firewall ${name} disabled"
}

load_rc_config ${name}
run_rc_command "$1"
