#!/bin/bash
# Fail2ban hook for ee-ips
# This hook generate a file /etc/fail2ban/jail.d/ee-ips.conf that define an ee_ips variable
# that could be use for instance to define an ignoreip directive value:
#
# ignoreip = 127.0.0.1/8 ::1 %(ee_ips)s
#
# cSpell:words ignoreip

set -e

if [[ ! -d /etc/fail2ban/jail.d ]] || ! which fail2ban-client > /dev/null 2>&1; then
    [[ "$1" != "detect" ]] && echo "Fail2ban seem not installed"
    exit 1
fi
[[ "$1" == "detect" ]] && exit 0

# shellcheck source=/dev/null
source /usr/share/ee-ips/data/ee-ips.bash

cat << EOF > /etc/fail2ban/jail.d/ee-ips.conf
# Auto-generated file by ee-ips debian package
# All changes will be override on next install/upgrade

[DEFAULT]
ee_ips = ${EE_IP4[*]} ${EE_IP6[*]}
EOF
echo "Fail2ban configuration file /etc/fail2ban/jail.d/ee-ips.conf updated"

fail2ban-client -t || exit 1

[[ "$( systemctl is-active fail2ban )" == "active" ]] && \
    systemctl reload fail2ban && \
    echo "Fail2ban configuration reloaded"
