#! /bin/bash
#
# fail2ban          Start/Stop the fail2ban daemon.
#
# chkconfig: 2345 90 49
# description: Fail2Ban scans log files and bans IP \
#		that makes too many password failures.
#		of the collected data.
# processname: fail2ban-server
# config: /etc/fail2ban/fail2ban
# pidfile: /var/run/fail2ban/fail2ban.pid
#
### BEGIN INIT INFO
# Provides:		fail2ban
# Required-Start:	$local_fs $remote_fs
# Required-Stop:	$local_fs $remote_fs
# Should-Start:		$time $network $syslog iptables shorewall
# Should-Stop:		$network $syslog iptables shorewall
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	fail2ban
# Description:		Fail2Ban scans log files and bans IP \
#			that makes too many password failures.
#			of the collected data.
### END INIT INFO

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

# Check that the config file exists
[ -f /etc/fail2ban/fail2ban.conf ] || exit 0

FAIL2BAN="/usr/bin/fail2ban-client"

RETVAL=0

PIDFILE=/var/run/fail2ban/fail2ban.pid

getpid() {
    pid=$(cat $PIDFILE 2>/dev/null)
    test -d /proc/$pid 2>/dev/null && return
    pid=
}

start() {
    gprintf "Starting fail2ban: "
    getpid
    if [ -n "$pid" ]; then
        echo_passed
        return $RETVAL
    else
        rm -rf /var/run/fail2ban/fail2ban.sock # in case of unclean shutdown
        $FAIL2BAN -x -q start > /dev/null
        RETVAL=$?
    fi
    if [ $RETVAL -eq 0 ]; then
        touch /var/lock/subsys/fail2ban
        echo_success
    else
        echo_failure
    fi
    echo
    return $RETVAL
}

stop() {
    gprintf "Stopping fail2ban: "
    getpid
    if [ -z "$pid" ]; then
        rm -f $PIDFILE
        echo_passed
        return 0
    fi

    $FAIL2BAN -q stop > /dev/null
    sleep 1
    getpid
    if [ -z "$pid" ]; then
        rm -f /var/lock/subsys/fail2ban
        echo_success
    else
        RETVAL=1
        echo_failure
    fi
    echo
    return $RETVAL
}

# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        getpid
        if [ -n "$pid" ]; then
                gprintf "Fail2ban (pid %s) is running...\n" "$pid"
                $FAIL2BAN status
        else
                RETVAL=1
                gprintf "Fail2ban is stopped\n"
        fi
        ;;
  restart)
        stop
        start
        ;;
  condrestart)
        getpid
        if [ -n "$pid" ] ; then
                stop
                start
        else
                gprintf "Fail2ban is stopped, skip restarting\n"
        fi
        ;;
  reload)
        fail2ban-client reload
        ;;
  condreload)
        getpid
        if [ -n "$pid" ] ; then
                fail2ban-client reload
        else
                gprintf "Fail2ban is stopped, skip reloading\n"
        fi
        ;;
  *)
        gprintf "Command '%s' is unknown. Usage: %s {start|stop|status|restart|condreload}\n" "$1" "$0"
        exit 1
        ;;
esac

exit $RETVAL
