#!/bin/bash

# Homelab Update Script
# Updates Mastodon, Mattermost, Matrix Synapse, and system packages

echo "=== Homelab Update Script ==="
echo "Started at: $(date)"
echo ""

# Update Mastodon
echo "[1/5] Updating Mastodon..."
cd /opt/mastodon
docker compose pull
docker compose down
docker compose run --rm web bundle exec rails db:migrate
docker compose up -d
echo "✅ Mastodon updated!"
echo ""

# Update Mattermost
echo "[2/5] Updating Mattermost..."
cd /opt/mattermost
docker compose pull
docker compose down
docker compose up -d
echo "✅ Mattermost updated!"
echo ""

# Update Matrix Synapse
echo "[3/5] Updating Matrix Synapse..."
cd /opt/synapse
source venv/bin/activate

# Get current version
CURRENT_VERSION=$(python -m synapse.app.homeserver --version 2>&1 | head -1)
echo "Current version: $CURRENT_VERSION"

# Upgrade
pip install --upgrade matrix-synapse

# Get new version
NEW_VERSION=$(python -m synapse.app.homeserver --version 2>&1 | head -1)
echo "New version: $NEW_VERSION"

# Restart both Synapse instances
echo "Restarting Synapse instances..."
pkill -f 'synapse.app.homeserver' || true
sleep 2

# Start mx.vish.gg (primary)
sudo -u synapse /opt/synapse/venv/bin/python -m synapse.app.homeserver \
  --config-path=/opt/synapse-mx/homeserver.yaml --daemonize
echo "  - mx.vish.gg started on port 8018"

# Start legacy vish
sudo -u synapse /opt/synapse/venv/bin/python -m synapse.app.homeserver \
  --config-path=/opt/synapse/homeserver.yaml --daemonize
echo "  - vish (legacy) started on port 8008"

deactivate
echo "✅ Matrix Synapse updated!"
echo ""

# Update TURN server
echo "[4/5] Updating TURN server (coturn)..."
sudo apt-get update -qq
sudo apt-get install -y coturn 2>/dev/null && echo "✅ Coturn updated!" || echo "⚠️ Coturn update skipped"
sudo systemctl restart coturn 2>/dev/null || true
echo ""

# Update system packages
echo "[5/5] Updating system packages..."
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get autoremove -y
echo "✅ System packages updated!"
echo ""

# Verification
echo "=== Verification ==="
echo ""
echo "Mastodon:"
docker compose -f /opt/mastodon/docker-compose.yml ps --format "table {{.Name}}\t{{.Status}}" 2>/dev/null | head -5

echo ""
echo "Mattermost:"
docker ps --filter "name=mattermost" --format "table {{.Names}}\t{{.Status}}"

echo ""
echo "Matrix Synapse:"
curl -s http://localhost:8018/_matrix/federation/v1/version 2>/dev/null && echo " (mx.vish.gg)" || echo "❌ mx.vish.gg not responding"
curl -s http://localhost:8008/_matrix/federation/v1/version 2>/dev/null && echo " (vish legacy)" || echo "❌ vish not responding"

echo ""
echo "=== Update Complete ==="
echo "Finished at: $(date)"
