#!/usr/bin/env bash
set -euo pipefail

# Fail2ban + UFW Quick Setup for Debian/Ubuntu
# Usage: curl -fsSL https://aaran.cloud/assets/scripts/install-fail2ban-ufw.sh | bash

if [ "$(id -u)" -ne 0 ]; then
  echo "Run as root or with sudo." >&2
  exit 1
fi

apt-get update -qq
apt-get install -y -qq fail2ban ufw

# Configure UFW defaults
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp comment 'SSH'
ufw allow 80/tcp comment 'HTTP'
ufw allow 443/tcp comment 'HTTPS'

# Enable UFW non-interactively
ufw --force enable

# Configure Fail2ban for SSH
cat > /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5
backend = systemd

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
EOF

# Ensure fail2ban starts on boot and restart
systemctl enable --now fail2ban
systemctl restart fail2ban

echo "UFW status:"
ufw status verbose

echo ""
echo "Fail2ban status:"
fail2ban-client status sshd || true

echo ""
echo "Done. Fail2ban + UFW are active."
