#!/bin/bash

# Fail2Ban Installation and Configuration Script
# Blocks incorrect logins permanently after the first failed attempt

set -e

echo "Updating package lists..."
sudo apt update

echo "Installing Fail2Ban..."
sudo apt install fail2ban -y

echo "Creating Fail2Ban configuration for permanent blocking..."

# Create jail.local configuration file
sudo bash -c 'cat > /etc/fail2ban/jail.local' <<EOF
[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
maxretry = 1
bantime = -1  # Permanent ban
findtime = 10m
EOF

echo "Enabling and starting Fail2Ban service..."
sudo systemctl enable fail2ban
sudo systemctl start fail2ban

echo "Checking Fail2Ban service status..."
sudo systemctl status fail2ban --no-pager

echo "Fail2Ban has been installed and configured successfully."
