#!/usr/bin/env bash
# Pull the IRDB blocklist and update an HAProxy ACL file in-place.
#
# Usage (cron):
#     IRDB_URL=http://localhost:8081 IRDB_TOKEN=irdb_con_... \
#         OUTPUT=/etc/haproxy/irdb-blocked.lst \
#         examples/consumers/haproxy-acl.sh
#
# In your haproxy.cfg:
#
#     frontend http_front
#         bind *:80
#         acl irdb_blocked src -f /etc/haproxy/irdb-blocked.lst
#         http-request deny if irdb_blocked
#         default_backend app
#
# This script uses HAProxy's runtime API (`set acl`) when available
# to update without a reload; otherwise it falls back to writing the
# file and emitting a hint that the operator should reload.
set -euo pipefail

: "${IRDB_URL:?must be set}"
: "${IRDB_TOKEN:?must be set}"
OUTPUT="${OUTPUT:-/etc/haproxy/irdb-blocked.lst}"
TIMEOUT="${IRDB_TIMEOUT:-30}"
HAPROXY_SOCKET="${HAPROXY_SOCKET:-/run/haproxy/admin.sock}"

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

curl -fsS --max-time "$TIMEOUT" \
    -H "Authorization: Bearer $IRDB_TOKEN" \
    -H "Accept: text/plain" \
    "$IRDB_URL/api/v1/blocklist" > "$TMP"

if [ -f "$OUTPUT" ] && cmp -s "$OUTPUT" "$TMP"; then
    echo "irdb-blocklist unchanged"
    exit 0
fi

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

if [ -S "$HAPROXY_SOCKET" ] && command -v socat >/dev/null 2>&1; then
    # Replace the ACL contents at runtime, no reload required.
    {
        echo "clear acl irdb_blocked"
        while IFS= read -r entry; do
            [ -z "$entry" ] && continue
            echo "add acl irdb_blocked $entry"
        done < "$OUTPUT"
        echo "show acl irdb_blocked | head -1"
    } | socat - "UNIX-CONNECT:$HAPROXY_SOCKET" >/dev/null
    echo "irdb-blocklist updated via haproxy socket"
else
    echo "irdb-blocklist written to $OUTPUT — reload haproxy to pick it up:"
    echo "    systemctl reload haproxy"
fi
