#!/bin/sh
#
# crowdsec	CrowdSec behaviour detection engine
#
# chkconfig:	345 20 08
# description:	crowdsec parses logs, matches them against Hub scenarios \
#		and serves decisions to bouncers over the local API.
# processname:	crowdsec
# config:	/etc/crowdsec/config.yaml
# pidfile:	/var/run/crowdsec.pid

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

# Get network config
. /etc/sysconfig/network

SERVICE=crowdsec
LOCKFILE=/var/lock/subsys/$SERVICE
PIDFILE=/var/run/$SERVICE.pid
CONFIG=/etc/crowdsec/config.yaml
PROG=/usr/sbin/crowdsec

# 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"
		exit 1
	fi
else
	exit 0
fi

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

start() {
	if [ -f "$LOCKFILE" ]; then
		msg_already_running "CrowdSec"
		return
	fi
	if ! configtest; then
		msg_starting "CrowdSec"
		fail
		RETVAL=1
		return
	fi
	msg_starting "CrowdSec"
	# crowdsec 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"
		return
	fi
	msg_stopping "CrowdSec"
	killproc --pidfile "$PIDFILE" crowdsec
	rm -f "$LOCKFILE" "$PIDFILE" >/dev/null 2>&1
}

reload() {
	if [ ! -f "$LOCKFILE" ]; then
		msg_not_running "CrowdSec"
		RETVAL=7
		return
	fi
	if ! configtest; then
		msg_reloading "CrowdSec"
		fail
		RETVAL=1
		return
	fi
	msg_reloading "CrowdSec"
	killproc --pidfile "$PIDFILE" crowdsec -HUP
	RETVAL=$?
}

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

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

exit $RETVAL
