#!/usr/bin/env bash
# configure-firewall-rule.sh — add an IP allow-list, a rate limit, and an
# email DLP rule to an existing MCP. Demonstrates the read-mutate-write
# pattern for /api/mcp/:id/rules.
#
# Usage:
#   AIRONCLAW_TOKEN=... ./configure-firewall-rule.sh <mcp-id>

set -euo pipefail

MCP_ID="${1:?usage: configure-firewall-rule.sh <mcp-id>}"
BASE="${AIRONCLAW_BASE_URL:-https://dashboard.aironclaw.com}"
TOKEN="${AIRONCLAW_TOKEN:?AIRONCLAW_TOKEN must be set}"

CURL=(curl -fsS -H "Authorization: Bearer ${TOKEN}")
JSON_HDR=(-H "Content-Type: application/json")

# 1. Fetch the current rules so we can append (a PUT replaces the whole array)
echo ">>> fetching current rules"
CURRENT=$("${CURL[@]}" "${BASE}/api/mcp/${MCP_ID}/rules" | jq '.rules')

# 2. Build the new rules
NEW_RULES=$(jq -n '
  [
    {
      rule_type: "ip_acl",
      tools: ["*"],
      action: "allow",
      cidrs: ["203.0.113.0/24", "10.0.0.0/8"]
    },
    {
      rule_type: "rate_limit",
      tools: ["*"],
      name: "global-per-key",
      match_key: "api_key",
      threshold: 100,
      timespan: 60,
      ban_after_n_exceeded: 50,
      ban_timespan: 3600
    },
    {
      rule_type: "response_replace",
      tools: ["*"],
      pattern: "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}",
      replacement: "[REDACTED-EMAIL]",
      regex_flags: "i",
      dlp_rule_id: "email_v1"
    }
  ]
')

# 3. Merge and PUT
MERGED=$(echo "$CURRENT" | jq --argjson new "$NEW_RULES" '. + $new')
echo ">>> writing $(echo "$MERGED" | jq 'length') rules"
"${CURL[@]}" "${JSON_HDR[@]}" -X PUT \
  "${BASE}/api/mcp/${MCP_ID}/rules" \
  -d "$(jq -nc --argjson r "$MERGED" '{rules:$r}')" | jq '.rules | length as $n | "stored \($n) rules"'
