#!/usr/bin/env bash
# Install /etc/whp/trusted-proxies.conf if it doesn't already exist.
#
# WHP's get_client_ip() now requires REMOTE_ADDR to be in this CIDR
# allowlist before it will honor X-Forwarded-For or CF-Connecting-IP.
# This closes a header-spoofing bypass of the brute-force lockout and
# session IP-pin.
#
# Idempotent: re-running is a no-op if the file already exists.
# Self-contained: embeds the default config; doesn't require the source
# repo to be in sync (update.sh on staging may run with a stale /root/whp).

set -euo pipefail

ETC_DIR="/etc/whp"
TARGET="${ETC_DIR}/trusted-proxies.conf"

mkdir -p "${ETC_DIR}"

if [ -f "${TARGET}" ]; then
    echo "trusted-proxies.conf already exists at ${TARGET} — leaving as-is"
    exit 0
fi

# Try the in-repo source first, then the extracted-tarball sibling, then
# fall back to the embedded heredoc below.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CANDIDATES=(
    "/root/whp/configs/trusted-proxies.conf.default"
    "${SCRIPT_DIR}/../../../configs/trusted-proxies.conf.default"
)

INSTALLED_FROM=""
for src in "${CANDIDATES[@]}"; do
    if [ -f "${src}" ]; then
        cp "${src}" "${TARGET}"
        INSTALLED_FROM="${src}"
        break
    fi
done

if [ -z "${INSTALLED_FROM}" ]; then
    cat > "${TARGET}" <<'CONF'
# /etc/whp/trusted-proxies.conf
#
# CIDR allowlist of trusted reverse proxies. WHP's get_client_ip() will
# only honor CF-Connecting-IP / X-Forwarded-For when REMOTE_ADDR matches
# one of these CIDRs. Otherwise headers from untrusted clients are
# ignored, preventing IP spoofing that bypasses brute-force lockout and
# the nonce IP-pin.
#
# Format: one CIDR per line; lines starting with # are comments.
#
# Defaults below cover the standard WHP topology where Apache, PHP-FPM,
# HAProxy, and Cloudflare's Argo tunnel all run on the same host or its
# private network. Adjust as needed for your deployment.

127.0.0.0/8       # IPv4 loopback (Apache <-> PHP-FPM, local probes)
::1/128           # IPv6 loopback
172.16.0.0/12     # Default Docker bridge networks
10.0.0.0/8        # Private LAN (HAProxy, internal services)
# 192.168.0.0/16  # Uncomment if your private LAN uses 192.168.x.x

# Cloudflare ranges — uncomment if traffic arrives via Cloudflare
# (refresh from https://www.cloudflare.com/ips/ periodically):
# 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
CONF
    INSTALLED_FROM="(embedded fallback)"
fi

chmod 0644 "${TARGET}"

echo "Installed ${TARGET} from ${INSTALLED_FROM}"
echo ""
echo "Review and uncomment any CIDR ranges that match your actual proxy"
echo "topology (HAProxy, Cloudflare, etc.)."
