#!/bin/bash
#
# chkconfig: 345 92 08
# description: Fail2ban daemon
#              http://fail2ban.sourceforge.net/wiki/index.php/Main_Page
# process name: fail2ban-server
#
#

# 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() {
    echo -n $"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 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() {
    echo -n $"Stopping fail2ban: "
    getpid
    if [ -z "$pid" ]; then
        rm -f $PIDFILE
        echo_passed
        return 0
    fi

    $FAIL2BAN 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
                echo "Fail2ban (pid $pid) is running..."
                $FAIL2BAN status
        else
                RETVAL=1
                echo "Fail2ban is stopped"
        fi
        ;;
  restart)
        stop
        start
        ;;
  condrestart)
        getpid
        if [ -n "$pid" ] ; then
                stop
                start
        else
                echo "Fail2ban is stopped, skip restarting"
        fi
        ;;
  reload)
        fail2ban-client reload
        ;;
  condreload)
        getpid
        if [ -n "$pid" ] ; then
                fail2ban-client reload
        else
                echo "Fail2ban is stopped, skip reloading"
        fi
        ;;
  *)
        echo $"Command '$1' is unknown. Usage: $0 {start|stop|status|restart|condreload}"
        exit 1
        ;;
esac

exit $RETVAL
