#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: pftables
# REQUIRE: pf
# KEYWORD: shutdown

# Copyright (c) 2014-2016, Thomas Zander
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# 
# * 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.
# 
# 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 HOLDER 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.

# Quick HOWTO
# ===========
# This script expects the following variables in /etc/rc.conf to do its work
#
# pftables_enable="YES"
# pftables_list="NameOfTable1 NameOfTable2 NameOfTable3" # ...and so on
# pftables_dir="/path/to/existing/dir/where/tables/should/be/stored"
#
# There are no default values, so all of these values must be set

. /etc/rc.subr

name="pftables"
desc="Save and restore pftables in between reboots"
rcvar="pftables_enable"
load_rc_config $name

extra_commands="status flush reload"

status_cmd="pftables_status"
flush_cmd="pftables_flush"
stop_cmd="pftables_flush"
start_cmd="pftables_start"
reload_cmd="pftables_start"

pftables_start()
{
	for _t in ${pftables_list}; do
		echo "Restoring pf table ${_t} from ${pftables_dir}/pftables-${_t}"
		$pf_program -t ${_t} -T add -f ${pftables_dir}/pftables-${_t} 2> /dev/null
	done
}

pftables_status()
{
	for _t in ${pftables_list}; do
		echo "${_t}:"
		$pf_program -t ${_t} -T show 2> /dev/null
	done
}

pftables_flush()
{
	for _t in ${pftables_list}; do
		echo "Flushing pf table ${_t} to ${pftables_dir}/pftables-${_t}"
		$pf_program -t ${_t} -T show > ${pftables_dir}/pftables-${_t} 2> /dev/null
	done
}

run_rc_command "$1"
