#!/usr/bin/env bash
# Post a single abuse report to IRDB.
#
# Usage:
#     IRDB_URL=http://localhost:8081 IRDB_TOKEN=irdb_rep_... \
#         examples/reporters/curl.sh 203.0.113.42 brute_force
#
# Optional third arg: a JSON metadata object to attach to the report.
# Anything in metadata is opaque to the api beyond a 4 KB size cap.
set -euo pipefail

if [ "$#" -lt 2 ]; then
    echo "Usage: $0 <ip> <category> [<metadata-json>]" >&2
    exit 64
fi

IP="$1"
CATEGORY="$2"
METADATA="${3:-{\}}"

: "${IRDB_URL:?must be set, e.g. http://localhost:8081}"
: "${IRDB_TOKEN:?must be set, e.g. irdb_rep_...}"

# Build the JSON body. jq is the cleanest path; fall back to printf if
# jq is unavailable.
if command -v jq >/dev/null 2>&1; then
    BODY=$(jq -nc --arg ip "$IP" --arg cat "$CATEGORY" --argjson meta "$METADATA" \
        '{ip: $ip, category: $cat, metadata: $meta}')
else
    BODY=$(printf '{"ip":"%s","category":"%s","metadata":%s}' \
        "$IP" "$CATEGORY" "$METADATA")
fi

curl -fsS -X POST \
    -H "Authorization: Bearer $IRDB_TOKEN" \
    -H "Content-Type: application/json" \
    --data "$BODY" \
    "$IRDB_URL/api/v1/report"
