#!/bin/bash

# Default API key
DEFAULT_API_KEY="your-default-api-key-value"
API_ENDPOINT="https://api.notifery.com/event"
MAX_MESSAGE_CHARS=2000
# Zone-specific API keys
declare -A ZONE_API_KEYS
# ZONE_API_KEYS["super-cool-server"]="zone-api-key-value"
# Add more zones as needed: ZONE_API_KEYS["zone-alias"]="api-key-value"

if [ $# -lt 3 ]; then
  echo "Usage: \"<title>\" <id#tag> \"<command>\""
  exit 1
fi

TITLE="$1"
ZONE_GROUP="$2"
COMMAND="$3"

ZONE=$(echo "$ZONE_GROUP" | cut -d '#' -f 1)
GROUP=$(echo "$ZONE_GROUP" | cut -d '#' -f 2)

if [ "$GROUP" == "$ZONE" ]; then
  GROUP=""
fi

# Get zone-specific API key or fall back to default
API_KEY="${ZONE_API_KEYS[$ZONE]:-$DEFAULT_API_KEY}"

output=$(bash -c "$COMMAND" 2>&1)
status=$?

# Check and truncate to MAX_CHARS if necessary
if [ "${#output}" -gt "$MAX_MESSAGE_CHARS" ]; then
  truncated_output="${output:0:MAX_MESSAGE_CHARS}"
  truncated_output+="
[Output truncated after $MAX_MESSAGE_CHARS chars]"
else
  truncated_output="$output"
fi

escaped_output=$(jq -Rs . <<<"$truncated_output")

json_payload=$(jq -n \
  --arg zone "$ZONE" \
  --arg group "$GROUP" \
  --arg title "$TITLE" \
  --arg message "$escaped_output" \
  --argjson code "$status" \
  '{"zone": $zone, "title": $title, "group": $group, "message": $message, "code": $code}')

curl --silent --output /dev/null -X POST -H "Content-Type: application/json" -H "x-api-key: $API_KEY" -d "$json_payload" "$API_ENDPOINT"