#!/bin/bash

## Written by Steve Murphy
## 
#  Sometimes, if failban is not shut down via "service fail2ban stop",
## the script to process the removal of rules are not executed, and 
#  if the call in INPUT to fail2ban-ASTERISK, etc is not removed,
# then every time fail2ban starts, it will keep adding that call to INPUT.
# It may not be able to remove that chain because there are still
# calls to it, but it can flush that chain, and refill it at start time.
# This script will remove the leftover accumulated calls to the fail2ban
# chains in iptables, so the next restart will go smoothly.

# the need for this script will go away when we move to the ipt-recent
# methodology.

n=`iptables -L -n | grep -c \^fail2ban-ASTERISK`
if [ $n -gt 1 ]; then
   echo "whoa, you have $n refs to the fail2ban-ASTERISK chain."
   for (( y=1 ; $y < $n ; y++ )) ; do
      iptables -D INPUT -p all -j fail2ban-ASTERISK
   done
fi
n=`iptables -L -n | grep -c \^fail2ban-VSFTPD`
if [ $n -gt 1 ]; then
   echo "whoa, you have $n refs to the fail2ban-VSFTPD chain."
   for (( y=1 ; $y < $n ; y++ )) ; do
      iptables -D INPUT -p all -j fail2ban-VSFTPD
   done
fi
n=`iptables -L -n | grep -c \^fail2ban-SECURE`
if [ $n -gt 1 ]; then
   echo "whoa, you have $n refs to the fail2ban-SECURE chain."
   for (( y=1 ; $y < $n ; y++ )) ; do
      iptables -D INPUT -p all -j fail2ban-SECURE
   done
fi
