#!/bin/bash
# Writes /etc/nginx/conf.d/cloudflare-realip.conf so nginx (and therefore
# Laravel) sees each visitor's real IP instead of Cloudflare's. Only trusted
# when the connection really comes from a Cloudflare range.
set -Eeuo pipefail
OUT=/etc/nginx/conf.d/cloudflare-realip.conf
TMP=$(mktemp)
{
    echo "# Generated $(date -Is) by greenathon-cloudflare-ips. Do not edit."
    for u in https://www.cloudflare.com/ips-v4 https://www.cloudflare.com/ips-v6; do
        curl -fsS --max-time 20 "$u" | grep -E '^[0-9a-f.:/]+$' | sed 's/.*/set_real_ip_from &;/'
    done
    echo "real_ip_header CF-Connecting-IP;"
} > "$TMP"
[[ $(grep -c set_real_ip_from "$TMP") -ge 10 ]] || { echo "Cloudflare list looks wrong; keeping the old file." >&2; rm -f "$TMP"; exit 1; }
install -m 644 "$TMP" "$OUT" && rm -f "$TMP"
nginx -t -q && systemctl reload nginx
echo "$(date -Is) updated $(grep -c set_real_ip_from "$OUT") Cloudflare ranges"
