#!/bin/bash
# =============================================================================
# Matrix Synapse + Element Web Verification Script
# =============================================================================
# Run as root or with sudo

echo "=========================================="
echo "Matrix/Element Health Check"
echo "=========================================="
echo ""

FAILED=0
WARN=0

# Load domain from secrets if available
if [ -f /root/.matrix_secrets ]; then
    source /root/.matrix_secrets
    echo "Domain: ${DOMAIN:-unknown}"
fi

echo ""
echo "[Service Status]"
for svc in synapse nginx coturn postgresql; do
    STATUS=$(systemctl is-active $svc 2>/dev/null || echo "not-found")
    if [ "$STATUS" = "active" ]; then
        echo "  ✓ $svc: running"
    elif [ "$STATUS" = "not-found" ]; then
        echo "  - $svc: not installed"
    else
        echo "  ✗ $svc: $STATUS"
        FAILED=1
    fi
done

echo ""
echo "[Matrix API]"
# Client API
if curl -sf http://localhost:8008/_matrix/client/versions > /dev/null 2>&1; then
    VERSION_COUNT=$(curl -s http://localhost:8008/_matrix/client/versions | python3 -c "import sys,json; print(len(json.load(sys.stdin).get('versions',[])))" 2>/dev/null || echo "0")
    echo "  ✓ Client API: responding ($VERSION_COUNT protocol versions)"
else
    echo "  ✗ Client API: not responding"
    FAILED=1
fi

# Federation API
FED_RESULT=$(curl -sf http://localhost:8008/_matrix/federation/v1/version 2>/dev/null)
if [ -n "$FED_RESULT" ]; then
    SYNAPSE_VER=$(echo "$FED_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('server',{}).get('version','unknown'))" 2>/dev/null)
    echo "  ✓ Federation API: responding (Synapse $SYNAPSE_VER)"
else
    echo "  ✗ Federation API: not responding"
    FAILED=1
fi

echo ""
echo "[Well-Known Endpoints]"
# Check nginx port
LISTEN_PORT=$(grep -oP 'listen \K\d+' /etc/nginx/sites-enabled/matrix 2>/dev/null | head -1 || echo "8080")

SERVER_WK=$(curl -sf http://localhost:$LISTEN_PORT/.well-known/matrix/server 2>/dev/null)
if [ -n "$SERVER_WK" ]; then
    echo "  ✓ /.well-known/matrix/server: $SERVER_WK"
else
    echo "  ✗ /.well-known/matrix/server: not configured"
    WARN=1
fi

CLIENT_WK=$(curl -sf http://localhost:$LISTEN_PORT/.well-known/matrix/client 2>/dev/null)
if [ -n "$CLIENT_WK" ]; then
    echo "  ✓ /.well-known/matrix/client: configured"
else
    echo "  ✗ /.well-known/matrix/client: not configured"
    WARN=1
fi

echo ""
echo "[Element Web]"
if curl -sf http://localhost:$LISTEN_PORT/ > /dev/null 2>&1; then
    echo "  ✓ Element Web: accessible on port $LISTEN_PORT"
else
    echo "  ✗ Element Web: not accessible"
    FAILED=1
fi

# Check Element config
if [ -f /opt/element/web/config.json ]; then
    HOMESERVER=$(python3 -c "import json; print(json.load(open('/opt/element/web/config.json')).get('default_server_config',{}).get('m.homeserver',{}).get('base_url','not set'))" 2>/dev/null)
    echo "  ✓ Element config: homeserver=$HOMESERVER"
else
    echo "  ✗ Element config: /opt/element/web/config.json not found"
    WARN=1
fi

echo ""
echo "[TURN Server]"
if systemctl is-active --quiet coturn; then
    TURN_PORT=$(grep -oP '^listening-port=\K\d+' /etc/turnserver.conf 2>/dev/null | head -1 || echo "3479")
    echo "  ✓ Coturn: running on port $TURN_PORT"
else
    echo "  - Coturn: not running (voice/video calls may not work behind NAT)"
    WARN=1
fi

echo ""
echo "[Database]"
if systemctl is-active --quiet postgresql; then
    DB_SIZE=$(sudo -u postgres psql -t -c "SELECT pg_size_pretty(pg_database_size('synapse'));" 2>/dev/null | xargs)
    echo "  ✓ PostgreSQL: running (synapse db: ${DB_SIZE:-unknown})"
else
    echo "  ✗ PostgreSQL: not running"
    FAILED=1
fi

echo ""
echo "=========================================="
if [ $FAILED -eq 0 ] && [ $WARN -eq 0 ]; then
    echo "✅ All checks passed!"
elif [ $FAILED -eq 0 ]; then
    echo "⚠️  Passed with warnings"
else
    echo "❌ Some checks failed"
fi
echo "=========================================="

exit $FAILED
