# +---------------------------------------------------+
# Configure Fail2Ban
# +---------------------------------------------------+

function func_fail2ban() {
    func_echo-header

    local ASK
    local flag

    echo -e "$green[eFa]$clean Fail2Ban protects you from attempts to access SSH and Postfix"

    flag=0
    while [ $flag -eq 0 ]; do
        echo -e ""
        echo -e -n "$green[eFa]$clean Would you like to $green Enable $clean Fail2Ban? [Y/n/c]: "
        read ASK
        if [[ $ASK =~ ^[yY]$ || -z $ASK ]]; then
            flag=1

            if [[ -f /etc/fail2ban/jail.d/efa.local.disabled ]]; then
                if [[ ! -f /etc/fail2ban/jail.d/efa.local ]]; then
                    mv /etc/fail2ban/jail.d/efa.local.disabled /etc/fail2ban/jail.d/efa.local
                fi
            else
                cat > /etc/fail2ban/jail.d/efa.local << 'EOF'
[sshd]
enabled = true

[postfix-sasl]
enabled = true
filter = postfix[mode=auth]

[mailwatch]
enabled = true
port    = http,https
logpath = /var/log/php-fpm/www-error.log
EOF

                cat > /etc/fail2ban/filter.d/mailwatch.conf << 'EOF'
[Definition]

failregex = ^\[.*?\] MailWatch failed login attempt from\: \[<HOST>\] for User: .*?$

ignoreregex =
EOF

            fi

            systemctl enable fail2ban
            systemctl restart fail2ban
            
            echo -e "$green[eFa]$clean Fail2Ban is now enabled."

            pause
        elif [[ $ASK =~ ^[nN]$ ]]; then
            flag=1
            mv /etc/fail2ban/jail.d/efa.local /etc/fail2ban/jail.d/efa.local.disabled
            systemctl disable fail2ban
            systemctl stop fail2ban

            echo -e "$green[eFa]$clean Fail2Ban is now disabled"
            pause
        elif [[ $ASK =~ ^[cC]$ ]]; then
            flag=1
            echo -e "$green[eFa]$clean No action taken"
            pause
            else
            echo -e "Choice $green\"$ASK\"$clean is not a valid choice."
            echo -e ""
        fi
    done
}

# +----------------------------------------------