#!/bin/sh
#
# crowdsec-firewall-bouncer	CrowdSec firewall bouncer
#
# chkconfig:	345 21 07
# description:	crowdsec-firewall-bouncer pulls decisions from the CrowdSec \
#		local API and blocks the addresses with nftables or iptables.
# processname:	crowdsec-firewall-bouncer
# config:	/etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml
# pidfile:	/var/run/crowdsec-firewall-bouncer.pid

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

# Get network config
. /etc/sysconfig/network

SERVICE=crowdsec-firewall-bouncer
LOCKFILE=/var/lock/subsys/$SERVICE
PIDFILE=/var/run/$SERVICE.pid
CONFIG=/etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml
PROG=/usr/sbin/crowdsec-firewall-bouncer

# Check that networking is up
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "CrowdSec firewall bouncer"
		exit 1
	fi
else
	exit 0
fi

configtest() {
	$PROG -c "$CONFIG" -t
}

start() {
	if [ -f "$LOCKFILE" ]; then
		msg_already_running "CrowdSec firewall bouncer"
		return
	fi
	if ! configtest; then
		msg_starting "CrowdSec firewall bouncer"
		fail
		RETVAL=1
		return
	fi
	msg_starting "CrowdSec firewall bouncer"
	# the bouncer runs in the foreground (systemd Type=notify); sysv has to
	# background it and track the pid itself.
	/sbin/start-stop-daemon --start --quiet --background \
		--make-pidfile --pidfile "$PIDFILE" \
		--exec $PROG -- -c "$CONFIG" && ok || fail
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch "$LOCKFILE"
}

stop() {
	if [ ! -f "$LOCKFILE" ]; then
		msg_not_running "CrowdSec firewall bouncer"
		return
	fi
	msg_stopping "CrowdSec firewall bouncer"
	killproc --pidfile "$PIDFILE" crowdsec-firewall-bouncer
	rm -f "$LOCKFILE" "$PIDFILE" >/dev/null 2>&1
}

condrestart() {
	if [ -f "$LOCKFILE" ]; then
		stop
		start
	else
		msg_not_running "CrowdSec firewall bouncer"
		RETVAL=$1
	fi
}

RETVAL=0
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  configtest)
	configtest
	RETVAL=$?
	;;
  status)
	status --pidfile "$PIDFILE" crowdsec-firewall-bouncer
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|configtest|status}"
	exit 3
esac

exit $RETVAL
