#!/bin/sh
### BEGIN INIT INFO
# Provides:          nftables
# Required-Start:    $local_fs $network $remote_fs $syslog
# Required-Stop:     $local_fs $remote_fs $syslog
# Default-Start:
# Default-Stop:      0 1 2 3 4 5 6
# Short-Description: nftables firewall service
# Description:       nftables firewall system service
### END INIT INFO

# Author: Arturo Borrero Gonzalez <arturo@debian.org>

# Do NOT "set -e"

CONF=/etc/nftables.conf

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="firewall service"
NAME=nftables
BIN=/usr/sbin/nft
SCRIPTNAME=/etc/init.d/$NAME

# Exit if the package is not installed
[ -x "$BIN" ] || exit 0

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

do_start()
{
	# Return
	#  0 if start OK
	#  2 if start NOK

	# nft v0.4 return 0 if ENOENT $CONF
	if [ ! -r "$CONF" ] ; then
		echo "E: No such $NAME $DESC config file $CONF" >&2
		return 2
	fi

	$BIN -f $CONF || return 2
}

do_stop()
{
	# Return
	#   0 if stopped
	#   1 if already stopped
	#   2 if could not be stopped
	if ! do_status ; then
		$BIN flush ruleset || return 2
	fi
}

do_status()
{
	# Return
	#   0 if no rules
	#   1 if rules
	if [ "$($BIN list ruleset 2>/dev/null | wc -l)" = "0" ] ; then
		return 0
	fi

	return 1
}

case "$1" in
  start)
	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
	do_start
	ret="$?"
	case "$ret" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	exit $ret
	;;
  restart|force-reload)
	[ "$VERBOSE" != no ] && log_daemon_msg "Restarting $DESC" "$NAME"
	do_start
	ret="$?"
	case "$ret" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	exit $ret
	;;
  stop)
	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
	do_stop
	ret="$?"
	case "$ret" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	exit $ret
	;;
  status)
	if ! do_status ; then
		[ "$VERBOSE" != no ] && log_daemon_msg "Status of ${DESC}: rules loaded" "$NAME"
		[ "$VERBOSE" != no ] && log_end_msg 0
		exit 0
	else
		[ "$VERBOSE" != no ] && log_daemon_msg "Status of ${DESC}: no rules loaded" "$NAME"
		[ "$VERBOSE" != no ] && log_end_msg 1
		exit 1
	fi
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
	exit 3
	;;
esac

:
