#!/bin/bash

# MaxScale REST API Configuration
MAXSCALE_HOST=${1:-localhost}
MAXSCALE_PORT=8989
MONITOR=${2:-MariaDB-Monitor}
USER="admin"
PASSWORD="mariadb"

echo "Fetching monitor config from MaxScale at $MAXSCALE_HOST:$MAXSCALE_PORT..."
echo "Monitor: $MONITOR"
echo "----------------------------------------------------------------------"

RESPONSE=$(curl -s -u "$USER:$PASSWORD" "http://$MAXSCALE_HOST:$MAXSCALE_PORT/v1/monitors/$MONITOR")

if [ $? -ne 0 ] || [ -z "$RESPONSE" ]; then
    echo "Error: Could not connect to MaxScale API."
    exit 1
fi

if command -v jq >/dev/null 2>&1; then
    echo "$RESPONSE" | jq -r '
      .data |
      "Monitor:  \(.id)",
      "Module:   \(.attributes.module)",
      "State:    \(.attributes.state)",
      "",
      "--- Parameters ---",
      (.attributes.parameters | to_entries[] | "  \(.key) = \(.value)"),
      "",
      "--- Monitored Servers ---",
      (.relationships.servers.data[]? | "  \(.id)")
    '
else
    echo "Note: 'jq' not found. Using python3 for basic formatting."
    echo "$RESPONSE" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)['data']
    attr = data['attributes']

    print(f\"Monitor:  {data['id']}\")
    print(f\"Module:   {attr.get('module', 'unknown')}\")
    print(f\"State:    {attr.get('state', 'unknown')}\")

    print('')
    print('--- Parameters ---')
    for k, v in sorted(attr.get('parameters', {}).items()):
        print(f'  {k} = {v}')

    print('')
    print('--- Monitored Servers ---')
    servers = data.get('relationships', {}).get('servers', {}).get('data', [])
    if servers:
        for s in servers:
            print(f\"  {s['id']}\")
    else:
        print('  (none)')
except Exception as e:
    print(f'Error parsing response: {e}')
    print('Raw response:')
    print(json.dumps(json.loads(sys.stdin.read()), indent=2))
"
fi
