#!/bin/bash

#######
## Script for an Icinga2 event command to start the fail2ban service if the fail2ban check returns a critical error for a certain time. 
## Author: Sebastian Klee
## E-Mail: s.klee@timmehosting.de
## Version: 1.0
## Date: 16.12.2021
## Notice: Parts of the code are from https://icinga.com/docs/icinga-2/latest/doc/03-monitoring-basics/#event-commands
#######



while getopts "s:t:a:S:" opt; do
  case $opt in
    s)
      servicestate=$OPTARG
      ;;
    t)
      servicestatetype=$OPTARG
      ;;
    a)
      serviceattempt=$OPTARG
      ;;
    S)
      service=$OPTARG
      ;;
  esac
done

if ( [ -z $servicestate ] || [ -z $servicestatetype ] || [ -z $serviceattempt ] || [ -z $service ] ); then
  echo "USAGE: $0 -s servicestate -t servicestatetype -a serviceattempt -S service"
  exit 3;
else
 # Only restart on the third attempt of a critical event
  if ( [ $servicestate == "CRITICAL" ] && [ $servicestatetype == "SOFT" ] && [ $serviceattempt -eq 3 ] ); then

     sock_file="/var/run/fail2ban/fail2ban.sock"
     if [[ -f $sock_file ]]; then
       rm $sock_file
     fi

     service_bin="/usr/bin/systemctl"
     if [[ -f $service_bin ]]; then
       /usr/bin/systemctl restart fail2ban
     else
       /etc/init.d/fail2ban restart
     fi

  fi
fi

