#!/bin/bash
# CP Panel: refresh Cloudflare IP ranges so Apache/PHP see the REAL visitor IP (mod_remoteip).
# Runs at install and weekly from /etc/cron.weekly/mzt-cf-ips.
set -u
OUT=/etc/apache2/conf-available/mzt-cloudflare.conf
FALLBACK4="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"
FALLBACK6="2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32"
v4=$(curl -fsS --max-time 10 https://www.cloudflare.com/ips-v4 2>/dev/null | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$' | tr '\n' ' ')
v6=$(curl -fsS --max-time 10 https://www.cloudflare.com/ips-v6 2>/dev/null | grep -E '^[0-9a-f:]+/[0-9]+$' | tr '\n' ' ')
[ -n "$v4" ] || v4=$FALLBACK4
[ -n "$v6" ] || v6=$FALLBACK6
TMP=$(mktemp)
{
  echo "# Cloudflare real visitor IP — generated by mzt-cf-ips, do not edit"
  echo "RemoteIPHeader CF-Connecting-IP"
  for r in $v4 $v6; do echo "RemoteIPTrustedProxy $r"; done
  echo '# Cloudflare "Flexible" SSL: tell PHP the visitor is on https'
  echo 'SetEnvIf X-Forwarded-Proto "^https$" HTTPS=on'
} > "$TMP"
if ! cmp -s "$TMP" "$OUT"; then
  mv "$TMP" "$OUT"; chmod 644 "$OUT"
  a2enconf -q mzt-cloudflare >/dev/null 2>&1
  if apache2ctl configtest >/dev/null 2>&1; then systemctl reload apache2 >/dev/null 2>&1 || true; fi
else
  rm -f "$TMP"
fi
