#!/bin/bash
set -e

# First add all Cloudflare IP rules for 80 and 443 BEFORE removing open rules
CF_IPS="173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22"

for ip in $CF_IPS; do
    ufw allow from $ip to any port 80 proto tcp comment "Cloudflare" 2>/dev/null
    ufw allow from $ip to any port 443 proto tcp comment "Cloudflare" 2>/dev/null
done

# Also allow mirror and dev servers direct access for health checks
ufw allow from 46.225.155.116 to any port 80 proto tcp comment "Mirror"
ufw allow from 46.225.155.116 to any port 443 proto tcp comment "Mirror"
ufw allow from 204.168.159.197 to any port 80 proto tcp comment "Dev"
ufw allow from 204.168.159.197 to any port 443 proto tcp comment "Dev"

echo "Cloudflare + server rules added"

# Now delete the open 80/443 and stale rules
# Must delete by rule spec, not number (numbers shift)
ufw delete allow 80/tcp 2>/dev/null || true
ufw delete allow 443/tcp 2>/dev/null || true
ufw delete allow 40000:40100/tcp 2>/dev/null || true

echo "Open rules removed"
echo "Done"
