#!/bin/bash
# =============================================================================
# Matrix Synapse Fix/Repair Script
# Diagnoses and fixes common issues
# =============================================================================
# Run as root

echo "=========================================="
echo "Matrix Synapse Fix/Repair Tool"
echo "=========================================="

# Check root
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi

FIXED=0
ERRORS=0

# 1. Check and fix YAML configuration
echo ""
echo "[1/6] Checking Synapse configuration..."
if [ -f /opt/synapse/homeserver.yaml ]; then
    if python3 -c "import yaml; yaml.safe_load(open('/opt/synapse/homeserver.yaml'))" 2>/dev/null; then
        echo "  ✓ homeserver.yaml is valid YAML"
    else
        echo "  ✗ homeserver.yaml has YAML errors!"
        echo "  Creating backup at /opt/synapse/homeserver.yaml.broken"
        cp /opt/synapse/homeserver.yaml /opt/synapse/homeserver.yaml.broken

        # Try to fix common issues
        echo "  Attempting automatic fix..."
        # Remove duplicate keys and fix indentation issues
        python3 << 'PYFIX'
import yaml
import re

try:
    with open('/opt/synapse/homeserver.yaml', 'r') as f:
        content = f.read()

    # Try to parse and re-write
    # First, try to fix common issues
    lines = content.split('\n')
    fixed_lines = []
    in_list = False

    for line in lines:
        # Skip empty turn_uris followed by list items not indented under it
        if line.strip() == 'turn_uris:':
            in_list = True
            fixed_lines.append(line)
        elif in_list and line.strip().startswith('- "turn:'):
            fixed_lines.append('  ' + line.strip())
        elif in_list and line.strip().startswith('- "turns:'):
            fixed_lines.append('  ' + line.strip())
        elif in_list and not line.strip().startswith('-') and line.strip():
            in_list = False
            fixed_lines.append(line)
        else:
            fixed_lines.append(line)

    fixed_content = '\n'.join(fixed_lines)

    # Validate the fix
    yaml.safe_load(fixed_content)

    with open('/opt/synapse/homeserver.yaml', 'w') as f:
        f.write(fixed_content)

    print("  ✓ Configuration fixed automatically")
except Exception as e:
    print(f"  ✗ Auto-fix failed: {e}")
    print("  Please manually fix /opt/synapse/homeserver.yaml")
    print("  Backup saved at /opt/synapse/homeserver.yaml.broken")
PYFIX
        FIXED=$((FIXED + 1))
    fi
else
    echo "  ✗ homeserver.yaml not found!"
    ERRORS=$((ERRORS + 1))
fi

# 2. Check file permissions
echo ""
echo "[2/6] Checking file permissions..."
if [ -d /opt/synapse ]; then
    OWNER=$(stat -c '%U' /opt/synapse)
    if [ "$OWNER" = "synapse" ]; then
        echo "  ✓ /opt/synapse owned by synapse user"
    else
        echo "  ✗ Fixing ownership of /opt/synapse..."
        chown -R synapse:synapse /opt/synapse
        FIXED=$((FIXED + 1))
    fi

    # Check config file permissions
    if [ -f /opt/synapse/homeserver.yaml ]; then
        PERMS=$(stat -c '%a' /opt/synapse/homeserver.yaml)
        if [ "$PERMS" = "600" ] || [ "$PERMS" = "640" ]; then
            echo "  ✓ homeserver.yaml has correct permissions"
        else
            echo "  ✗ Fixing homeserver.yaml permissions..."
            chmod 600 /opt/synapse/homeserver.yaml
            FIXED=$((FIXED + 1))
        fi
    fi
fi

# 3. Check services
echo ""
echo "[3/6] Checking services..."
for svc in postgresql synapse nginx coturn; do
    if systemctl is-active --quiet $svc 2>/dev/null; then
        echo "  ✓ $svc is running"
    else
        echo "  ✗ $svc is not running, attempting to start..."
        systemctl start $svc 2>/dev/null
        sleep 2
        if systemctl is-active --quiet $svc; then
            echo "    ✓ $svc started successfully"
            FIXED=$((FIXED + 1))
        else
            echo "    ✗ Failed to start $svc"
            echo "    Check logs: journalctl -u $svc -n 50"
            ERRORS=$((ERRORS + 1))
        fi
    fi
done

# 4. Check database connection
echo ""
echo "[4/6] Checking database..."
if sudo -u postgres psql -c "SELECT 1" synapse > /dev/null 2>&1; then
    echo "  ✓ PostgreSQL connection successful"
else
    echo "  ✗ Cannot connect to synapse database"
    ERRORS=$((ERRORS + 1))
fi

# 5. Check nginx configuration
echo ""
echo "[5/6] Checking nginx configuration..."
if nginx -t 2>/dev/null; then
    echo "  ✓ Nginx configuration is valid"
else
    echo "  ✗ Nginx configuration has errors"
    nginx -t
    ERRORS=$((ERRORS + 1))
fi

# 6. Check API endpoints
echo ""
echo "[6/6] Checking API endpoints..."
sleep 1
if curl -sf http://localhost:8008/_matrix/client/versions > /dev/null 2>&1; then
    echo "  ✓ Matrix Client API responding"
else
    echo "  ✗ Matrix Client API not responding"
    echo "    Checking Synapse logs..."
    journalctl -u synapse -n 10 --no-pager 2>/dev/null | tail -5
    ERRORS=$((ERRORS + 1))
fi

LISTEN_PORT=$(grep -oP '^    listen \K\d+' /etc/nginx/sites-enabled/matrix 2>/dev/null | head -1 || echo "8080")
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"
    ERRORS=$((ERRORS + 1))
fi

# Summary
echo ""
echo "=========================================="
if [ $ERRORS -eq 0 ]; then
    if [ $FIXED -eq 0 ]; then
        echo "✅ All checks passed! No issues found."
    else
        echo "✅ Fixed $FIXED issue(s). All checks now pass."
        echo ""
        echo "You may want to restart services:"
        echo "  systemctl restart synapse nginx"
    fi
else
    echo "⚠️  Found $ERRORS error(s) that need manual attention."
    echo ""
    echo "Common fixes:"
    echo "  - Check logs: journalctl -u synapse -f"
    echo "  - Validate YAML: python3 -c \"import yaml; yaml.safe_load(open('/opt/synapse/homeserver.yaml'))\""
    echo "  - Restart services: systemctl restart postgresql synapse nginx coturn"
fi
echo "=========================================="

exit $ERRORS
