#!/bin/bash

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

echo "Fetching server list from MaxScale at $MAXSCALE_HOST:$MAXSCALE_PORT..."
echo "----------------------------------------------------------------------"

# Fetch servers from the REST API
# Using -u for basic auth (admin:mariadb)
# The output is JSON, we'll use a simple python command to format it if jq isn't available
RESPONSE=$(curl -s -u "$USER:$PASSWORD" "http://$MAXSCALE_HOST:$MAXSCALE_PORT/v1/servers")

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

# Check if jq is installed for pretty printing, otherwise use python3
if command -v jq >/dev/null 2>&1; then
    echo "$RESPONSE" | jq -r '.data[] | "Server: \(.id)\n  Address: \(.attributes.address)\n  State: \(.attributes.state)\n  Master: \(.attributes.master_id // "No")\n  ----------------------------------------------------------------------"'
else
    echo "Note: 'jq' not found. Using python3 for basic formatting."
    echo "$RESPONSE" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    for server in data['data']:
        attr = server['attributes']
        print(f\"Server: {server['id']}\")
        print(f\"  Address: {attr['address']}\")
        print(f\"  State: {attr.get('state', 'Unknown')}\")
        print(f\"  Master: {attr.get('master_id', 'No')}\")
        print('  ' + '-'*68)
except Exception as e:
    print('Raw JSON response:')
    print(json.dumps(json.loads(sys.stdin.read()), indent=2))
"
fi
