#!/bin/bash
# =============================================================================
# Matrix Synapse + Element Web Update Script
# =============================================================================
# Run as root

set -e

echo "=========================================="
echo "Matrix Synapse + Element Update Script"
echo "=========================================="

# Check current versions
CURRENT_SYNAPSE=$(/opt/synapse/venv/bin/python -c "import synapse; print(synapse.__version__)" 2>/dev/null || echo "unknown")
CURRENT_ELEMENT=$(cat /opt/element/web/version 2>/dev/null || ls /opt/element/ | grep -oP 'v[\d.]+' | head -1 || echo "unknown")

echo "Current Synapse: $CURRENT_SYNAPSE"
echo "Current Element: $CURRENT_ELEMENT"

# Get latest versions
echo ""
echo "Checking for updates..."
LATEST_ELEMENT=$(curl -s https://api.github.com/repos/element-hq/element-web/releases/latest | jq -r '.tag_name')
echo "Latest Element: $LATEST_ELEMENT"

read -p "Proceed with update? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Update cancelled."
    exit 0
fi

# Backup first
echo ""
echo "[1/4] Creating backup..."
if [ -f ./backup-matrix.sh ]; then
    ./backup-matrix.sh
elif [ -f /opt/matrix-scripts/backup-matrix.sh ]; then
    /opt/matrix-scripts/backup-matrix.sh
else
    echo "Backup script not found, skipping..."
fi

# Update Synapse
echo ""
echo "[2/4] Updating Synapse..."
systemctl stop synapse
cd /opt/synapse
sudo -u synapse bash << 'UPDATE_SYNAPSE'
source venv/bin/activate
pip install --upgrade matrix-synapse psycopg2-binary lxml 'prometheus-client<0.21'
UPDATE_SYNAPSE

# Run database migrations
echo ""
echo "[3/4] Running database migrations..."
sudo -u synapse /opt/synapse/venv/bin/python -m synapse.app.homeserver \
    --config-path /opt/synapse/homeserver.yaml \
    --generate-keys-if-missing

# Update Element Web
echo ""
echo "[4/4] Updating Element Web..."
cd /opt/element
if [ -n "$LATEST_ELEMENT" ] && [ "$LATEST_ELEMENT" != "null" ]; then
    # Backup old config
    cp web/config.json /tmp/element_config_backup.json

    # Download new version
    wget -q "https://github.com/element-hq/element-web/releases/download/$LATEST_ELEMENT/element-$LATEST_ELEMENT.tar.gz"

    # Remove old, extract new
    rm -rf web
    tar xzf "element-$LATEST_ELEMENT.tar.gz"
    mv "element-$LATEST_ELEMENT" web
    rm "element-$LATEST_ELEMENT.tar.gz"

    # Restore config
    cp /tmp/element_config_backup.json web/config.json
    echo "Element updated to $LATEST_ELEMENT"
else
    echo "Could not determine latest Element version, skipping Element update"
fi

# Start services
echo ""
echo "Starting services..."
systemctl start synapse
systemctl restart nginx

# Verify
sleep 3
NEW_SYNAPSE=$(/opt/synapse/venv/bin/python -c "import synapse; print(synapse.__version__)" 2>/dev/null || echo "unknown")

echo ""
echo "=========================================="
echo "✅ Update Complete!"
echo "=========================================="
echo ""
echo "Synapse: $CURRENT_SYNAPSE → $NEW_SYNAPSE"
echo "Element: $CURRENT_ELEMENT → $LATEST_ELEMENT"
echo ""
echo "Please verify your instance is working correctly."
