#!/usr/bin/env bash
set -euo pipefail

# Sync Stripe webhook source IP ranges into an nginx include file.
# Requires: curl, jq
#
# Usage:
#   scripts/sync-stripe-webhook-ips.sh \
#     --out /etc/nginx/snippets/stripe-webhook-allowlist.conf \
#     --reload "systemctl reload nginx"

OUT_FILE="/etc/nginx/snippets/stripe-webhook-allowlist.conf"
RELOAD_CMD=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --out)
      OUT_FILE="$2"; shift 2 ;;
    --reload)
      RELOAD_CMD="$2"; shift 2 ;;
    *)
      echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

TMP_JSON="$(mktemp)"
TMP_CONF="$(mktemp)"
TMP_IPS="$(mktemp)"
trap 'rm -f "$TMP_JSON" "$TMP_CONF" "$TMP_IPS"' EXIT

curl -fsSL "https://stripe.com/files/ips/ips_webhooks.json" -o "$TMP_JSON"

jq -r '.WEBHOOKS[]' "$TMP_JSON" > "$TMP_IPS"

{
  echo "# Auto-generated by sync-stripe-webhook-ips.sh"
  echo "# Source: https://stripe.com/files/ips/ips_webhooks.json"
  echo "# Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  while IFS= read -r cidr; do
    [[ -n "$cidr" ]] && echo "allow $cidr;"
  done < "$TMP_IPS"
  echo "deny all;"
} > "$TMP_CONF"

install -D -m 0644 "$TMP_CONF" "$OUT_FILE"
echo "Wrote $OUT_FILE"

if [[ -n "$RELOAD_CMD" ]]; then
  eval "$RELOAD_CMD"
  echo "Reloaded nginx"
fi
