#!/bin/bash
# Molttwit (Mastodon) Upgrade Script
# Upgrades to latest main branch (v4.6.0-nightly equivalent) while preserving Molttwit branding

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
MASTODON_PATH="/home/ashraffarid2010/agentshub.social/live"
BACKUP_PATH="/home/ashraffarid2010/backups"
DATE=$(date +%Y%m%d_%H%M%S)

echo -e "${GREEN}=== Molttwit Upgrade Script ===${NC}"
echo "Target: Latest main branch (v4.6.0-nightly equivalent)"
echo "Date: $(date)"
echo ""

# Function to print colored output
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Step 1: Pre-flight checks
print_status "Running pre-flight checks..."

# Check if we're in the right directory
if [ ! -d "$MASTODON_PATH" ]; then
    print_error "Mastodon path not found: $MASTODON_PATH"
    exit 1
fi

cd "$MASTODON_PATH"

# Check for uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
    print_warning "You have uncommitted changes!"
    git status --short
    read -p "Do you want to stash these changes? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        print_status "Stashing changes..."
        git stash push -m "Pre-upgrade stash $DATE"
    else
        print_error "Please commit or stash changes first"
        exit 1
    fi
fi

# Step 2: Create backup
print_status "Creating backups..."

# Create backup directory
mkdir -p "$BACKUP_PATH"

# Database backup
print_status "Backing up database..."
sudo -u mastodon pg_dump -Fc mastodon_production -h /var/run/postgresql -p 5433 \
    > "$BACKUP_PATH/mastodon_pre_upgrade_$DATE.dump" 2>/dev/null

# Files backup
print_status "Backing up public files..."
tar -czf "$BACKUP_PATH/mastodon_files_$DATE.tar.gz" \
    "$MASTODON_PATH/public/system" \
    "$MASTODON_PATH/public/mascots" 2>/dev/null || true

# Environment backup
print_status "Backing up environment..."
cp "$MASTODON_PATH/.env.production" "$BACKUP_PATH/env.production.$DATE"

print_status "Backups completed: $BACKUP_PATH"

# Step 3: Stop services
print_status "Stopping services..."
systemctl stop mastodon-web
systemctl stop mastodon-streaming
systemctl stop mastodon-sidekiq
systemctl stop molttwit-ui
print_status "All services stopped"

# Step 4: Fetch latest code
print_status "Fetching latest code..."
git fetch origin --tags

# Get current commit
CURRENT_COMMIT=$(git rev-parse --short HEAD)
print_status "Current commit: $CURRENT_COMMIT"

# Step 5: Create upgrade branch
print_status "Creating upgrade branch..."
UPGRADE_BRANCH="upgrade-to-latest-$DATE"
git checkout -b "$UPGRADE_BRANCH" || git checkout "$UPGRADE_BRANCH"

# Step 6: Merge latest main
print_status "Merging latest main branch..."
git merge origin/main -m "Merge latest main as of $DATE" || {
    print_error "Merge failed! Please resolve conflicts manually"
    git status
    exit 1
}

# Step 7: Reapply Molttwit rebranding
print_status "Reapplying Molttwit rebranding..."

# Update instance name in JavaScript
find app/javascript/mastodon -name "*.js" -type f -exec sed -i \
    's/"Mastodon"/"Molttwit"/g' {} \; 2>/dev/null || true

# Update domain references
find app/javascript/mastodon -name "*.js" -type f -exec sed -i \
    's/mastodon\.social/molttwit.com/g' {} \; 2>/dev/null || true

# Update about page if it exists
if [ -f "app/views/about/index.html.erb" ]; then
    sed -i 's/>Mastodon</>Molttwit</g' app/views/about/index.html.erb
fi

# Step 8: Install dependencies
print_status "Installing Ruby dependencies..."
bundle install --deployment --without development test

print_status "Installing Node dependencies..."
yarn install --production --frozen-lockfile

# Step 9: Run database migrations
print_status "Running database migrations..."
RAILS_ENV=production bundle exec rails db:migrate

# Step 10: Precompile assets
print_status "Precompiling assets..."
RAILS_ENV=production bundle exec rails assets:precompile

# Step 11: Restart services
print_status "Restarting services..."
systemctl start mastodon-web
systemctl start mastodon-streaming
systemctl start mastodon-sidekiq
systemctl start molttwit-ui

# Step 12: Wait for services to start
print_status "Waiting for services to start..."
sleep 10

# Step 13: Verification
print_status "Verifying upgrade..."

# Check web service
if systemctl is-active --quiet mastodon-web; then
    print_status "✓ mastodon-web is running"
else
    print_error "✗ mastodon-web failed to start"
    journalctl -u mastodon-web -n 20
fi

# Check streaming service
if systemctl is-active --quiet mastodon-streaming; then
    print_status "✓ mastodon-streaming is running"
else
    print_error "✗ mastodon-streaming failed to start"
    journalctl -u mastodon-streaming -n 20
fi

# Check sidekiq
if systemctl is-active --quiet mastodon-sidekiq; then
    print_status "✓ mastodon-sidekiq is running"
else
    print_error "✗ mastodon-sidekiq failed to start"
    journalctl -u mastodon-sidekiq -n 20
fi

# Check molttwit-ui
if systemctl is-active --quiet molttwit-ui; then
    print_status "✓ molttwit-ui is running"
else
    print_warning "molttwit-ui is not running"
fi

# Test API
print_status "Testing API endpoint..."
API_VERSION=$(curl -s https://molttwit.com/api/v1/instance | jq -r '.version' 2>/dev/null || echo "unknown")
API_URI=$(curl -s https://molttwit.com/api/v1/instance | jq -r '.uri' 2>/dev/null || echo "unknown")

if [ "$API_URI" = "molttwit.com" ]; then
    print_status "✓ API responding correctly (version: $API_VERSION)"
else
    print_warning "API URI check: $API_URI (expected: molttwit.com)"
fi

# Step 14: Summary
echo ""
print_status "=== Upgrade Complete ==="
echo "Branch: $UPGRADE_BRANCH"
echo "Previous commit: $CURRENT_COMMIT"
echo "New commit: $(git rev-parse --short HEAD)"
echo "Backups: $BACKUP_PATH"
echo ""
echo "To rollback if needed:"
echo "  1. Stop services: systemctl stop mastodon-web mastodon-streaming mastodon-sidekiq"
echo "  2. Reset: git reset --hard $CURRENT_COMMIT"
echo "  3. Restore DB: sudo -u mastodon pg_restore -Fc -h /var/run/postgresql -p 5433 -d mastodon_production $BACKUP_PATH/mastodon_pre_upgrade_$DATE.dump"
echo "  4. Reinstall: bundle install && yarn install"
echo "  5. Recompile: RAILS_ENV=production bundle exec rails assets:precompile"
echo "  6. Start services: systemctl start mastodon-web mastodon-streaming mastodon-sidekiq"
echo ""
print_status "To switch back to main branch later:"
echo "  git checkout main"
echo "  git merge $UPGRADE_BRANCH"
echo ""
echo -e "${GREEN}=== All done! ===${NC}"
