#!/bin/sh
#
# iptables	Start Netfilter tables
#
# chkconfig: 2345 08 92
# description:	Starts, stops Netfilter tables
#
# config: /etc/sysconfig/nftables.conf
#
### BEGIN INIT INFO
# Provides: nftables
# Required-Start:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop Netfilter tables
# Description: Start, stop and save Netfilter tables
### END INIT INFO

# Source function library.
. /etc/init.d/functions

NFT=/usr/sbin/nft
NFTABLES_CONFIG=/etc/sysconfig/nftables.conf
VAR_SUBSYS_NFTABLES=/var/lock/subsys/nftables

if [ ! -x $NFT ]; then
    echo -n $"${NFT}: $NFT does not exist."; warning; echo
    exit 5
fi

start() {
    # Do not start if there is no config file.
    [ ! -f "$NFTABLES_CONFIG" ] && return 6

    echo -n $"Applying rules to Netfilter tables: "

    $NFT -f $NFTABLES_CONFIG
    if [ $? -eq 0 ]; then
	success; echo
    else
	failure; echo; return 1
    fi

    touch $VAR_SUBSYS_NFTABLES
    return $ret
}

stop() {
    echo -n $"Flushing Netfilter tables: "
    ret=0

    $NFT flush ruleset
    if [ $? -eq 0 ]; then
	success; echo
    else
	failure; echo; return 1
    fi

    rm -f $VAR_SUBSYS_NFTABLES
    return $ret
}

reload() {
    # Do not start if there is no config file.
    [ ! -f "$NFTABLES_CONFIG" ] && return 6

    echo -n $"Reloading rules to Netfilter tables: "

    $NFT 'flush ruleset; include "/etc/sysconfig/nftables.conf";'
    if [ $? -eq 0 ]; then
	success; echo
    else
	failure; echo; return 1
    fi

    touch $VAR_SUBSYS_NFTABLES
    return $ret
}

status() {
    if [ ! -f "$VAR_SUBSYS_NFTABLES" ]; then
	echo $"nftables is not running."
	return 3
    fi

	echo $"nftables is running."
    return 0
}


case "$1" in
    start)
	[ -f "$VAR_SUBSYS_NFTABLES" ] && exit 0
	start
	RETVAL=$?
	;;
    stop)
	[ ! -e "$VAR_SUBSYS_NFTABLES" ] && exit 0
	stop
	RETVAL=$?
	;;
    restart|reload|force-reload)
	reload
	RETVAL=$?
	;;
    condrestart|try-restart)
	[ ! -e "$VAR_SUBSYS_NFTABLES" ] && exit 0
	reload
	RETVAL=$?
	;;
    status)
	status
	RETVAL=$?
	;;
    *)
	echo $"Usage: nftables {start|stop|restart|condrestart|status}"
	RETVAL=2
	;;
esac

exit $RETVAL
