#!/usr/bin/env bash
# fail2ban action shim: post the banned IP to IRDB.
#
# Wire it up by dropping a fail2ban action file in /etc/fail2ban/action.d/:
#
#     [Definition]
#     actionban = /usr/local/bin/irdb-fail2ban.sh <ip> brute_force '{"jail":"<name>"}'
#     actionunban = true
#
#     [Init]
#     name = default
#
# And set IRDB_URL + IRDB_TOKEN in fail2ban's environment (typically
# /etc/default/fail2ban or a systemd drop-in).
#
# This script is intentionally tiny — fail2ban actions execute often,
# in restricted environments, and any sleep/retry logic belongs in a
# higher layer.
set -euo pipefail

IP="${1:?ip required}"
CATEGORY="${2:?category required}"
METADATA="${3:-{\}}"

: "${IRDB_URL:?must be set}"
: "${IRDB_TOKEN:?must be set}"

# Best-effort: 5 second timeout, no retries. fail2ban won't block on
# the action; if IRDB is briefly unreachable we lose this report
# rather than holding the ban.
exec curl -fsS --max-time 5 -X POST \
    -H "Authorization: Bearer $IRDB_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"ip\":\"$IP\",\"category\":\"$CATEGORY\",\"metadata\":$METADATA}" \
    "$IRDB_URL/api/v1/report" >/dev/null
