#!/usr/bin/env bash
# Pull the IRDB blocklist and write an nginx `deny` include file.
# Reload nginx atomically only if the file changed.
#
# Usage (cron):
#     IRDB_URL=http://localhost:8081 IRDB_TOKEN=irdb_con_... \
#         OUTPUT=/etc/nginx/conf.d/irdb-deny.conf \
#         examples/consumers/nginx-deny-include.sh
#
# In your nginx config, include the file inside a `server {}` block:
#
#     server {
#         ...
#         include /etc/nginx/conf.d/irdb-deny.conf;
#     }
#
# The script is idempotent: if the new file content matches what's
# already on disk, nginx is left alone.
set -euo pipefail

: "${IRDB_URL:?must be set}"
: "${IRDB_TOKEN:?must be set}"
OUTPUT="${OUTPUT:-/etc/nginx/conf.d/irdb-deny.conf}"
TIMEOUT="${IRDB_TIMEOUT:-30}"

TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT

# Header makes the include file self-describing.
{
    echo "# Generated by examples/consumers/nginx-deny-include.sh"
    echo "# Updated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
} > "$TMP"

curl -fsS --max-time "$TIMEOUT" \
    -H "Authorization: Bearer $IRDB_TOKEN" \
    -H "Accept: text/plain" \
    "$IRDB_URL/api/v1/blocklist" \
    | while IFS= read -r line; do
        [ -z "$line" ] && continue
        echo "deny $line;"
    done >> "$TMP"

# Only reload nginx if the file actually changed.
if [ -f "$OUTPUT" ] && cmp -s "$OUTPUT" "$TMP"; then
    echo "irdb-blocklist unchanged; nginx not reloaded"
    exit 0
fi

mv "$TMP" "$OUTPUT"
trap - EXIT

# `nginx -t` first so we never reload onto a syntax error.
nginx -t
nginx -s reload
echo "irdb-blocklist written to $OUTPUT; nginx reloaded"
