#!/bin/bash
# Mastodon Update Script
# Updates Mastodon to the latest stable version (or specified version)
# Run as root

set -e

TARGET_VERSION="${1:-}"
MASTODON_DIR="/home/mastodon/live"

echo "=========================================="
echo "Mastodon Update Script"
echo "=========================================="

# Check current version
CURRENT_VERSION=$(cd $MASTODON_DIR && git describe --tags 2>/dev/null || echo "unknown")
echo "Current version: $CURRENT_VERSION"

# Get latest version if not specified
if [ -z "$TARGET_VERSION" ]; then
    echo "Fetching latest version..."
    cd $MASTODON_DIR
    sudo -u mastodon git fetch --tags
    TARGET_VERSION=$(git tag -l 'v*' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1)
fi

echo "Target version: $TARGET_VERSION"

if [ "$CURRENT_VERSION" = "$TARGET_VERSION" ]; then
    echo "Already at version $TARGET_VERSION. Nothing to do."
    exit 0
fi

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

# Create backup first
echo ""
echo "[1/7] Creating backup before update..."
/home/mastodon/scripts/backup-mastodon.sh || echo "Backup script not found, skipping..."

# Stop services
echo ""
echo "[2/7] Stopping Mastodon services..."
systemctl stop mastodon-web mastodon-sidekiq mastodon-streaming

# Update code
echo ""
echo "[3/7] Updating Mastodon code..."
cd $MASTODON_DIR
sudo -u mastodon git fetch --all
sudo -u mastodon git checkout $TARGET_VERSION

# Update Ruby dependencies
echo ""
echo "[4/7] Updating Ruby dependencies..."
sudo -u mastodon bash -lc "cd ~/live && bundle install"

# Update Node dependencies
echo ""
echo "[5/7] Updating Node dependencies..."
sudo -u mastodon bash -lc "cd ~/live && yarn install --immutable"

# Run database migrations
echo ""
echo "[6/7] Running database migrations..."
sudo -u mastodon bash -lc "cd ~/live && RAILS_ENV=production bundle exec rails db:migrate"

# Precompile assets
echo ""
echo "[7/7] Precompiling assets (this may take a few minutes)..."
sudo -u mastodon bash -lc "cd ~/live && RAILS_ENV=production bundle exec rails assets:precompile"

# Fix SELinux contexts
chcon -R -t httpd_sys_content_t /home/mastodon/live/public

# Start services
echo ""
echo "Starting Mastodon services..."
systemctl start mastodon-web mastodon-sidekiq mastodon-streaming

# Verify
sleep 5
echo ""
echo "Checking service status..."
systemctl is-active mastodon-web mastodon-sidekiq mastodon-streaming

NEW_VERSION=$(cd $MASTODON_DIR && git describe --tags 2>/dev/null || echo "unknown")

echo ""
echo "=========================================="
echo "✅ Update Complete!"
echo "=========================================="
echo ""
echo "Previous version: $CURRENT_VERSION"
echo "New version: $NEW_VERSION"
echo ""
echo "Please verify your instance is working correctly."
echo "Check the release notes for any manual steps:"
echo "https://github.com/mastodon/mastodon/releases/tag/$TARGET_VERSION"
echo ""
