#!/bin/bash
# Setup firewall rules

set -e

echo "Configuring firewall (UFW)..."

# Enable UFW
ufw --force enable

# Allow SSH
ufw allow 22/tcp comment 'SSH'

# Allow HTTP/HTTPS (if direct connection)
read -p "Do you have a direct public IP? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    ufw allow 80/tcp comment 'HTTP'
    ufw allow 443/tcp comment 'HTTPS'
fi

# Allow Cloudflare IP ranges (if using direct connection)
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Adding Cloudflare IP ranges..."
    ufw allow from 173.245.48.0/20 comment 'Cloudflare'
    ufw allow from 103.21.244.0/22 comment 'Cloudflare'
    ufw allow from 103.22.200.0/22 comment 'Cloudflare'
    ufw allow from 103.31.4.0/22 comment 'Cloudflare'
    ufw allow from 141.101.64.0/18 comment 'Cloudflare'
    ufw allow from 108.162.192.0/18 comment 'Cloudflare'
    ufw allow from 190.93.240.0/20 comment 'Cloudflare'
    ufw allow from 188.114.96.0/20 comment 'Cloudflare'
    ufw allow from 197.234.240.0/22 comment 'Cloudflare'
    ufw allow from 198.41.128.0/17 comment 'Cloudflare'
    ufw allow from 162.158.0.0/15 comment 'Cloudflare'
    ufw allow from 104.16.0.0/13 comment 'Cloudflare'
    ufw allow from 104.24.0.0/14 comment 'Cloudflare'
    ufw allow from 172.64.0.0/13 comment 'Cloudflare'
    ufw allow from 131.0.72.0/22 comment 'Cloudflare'
fi

# Show status
ufw status verbose

echo ""
echo "Firewall configured!"

