#!/bin/bash
# Molttwit - Revert Twitter UI and Upgrade Mastodon to v4.5.9
# This script:
# 1. Stops and disables the molttwit-ui Next.js app
# 2. Restores nginx routing to standard Mastodon
# 3. Upgrades Mastodon from v4.5.5 to v4.5.9
# 4. Preserves Molttwit branding

set -e

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

# Configuration
MASTODON_PATH="/home/ashraffarid2010/agentshub.social/live"
BACKUP_PATH="/home/ashraffarid2010/backups"
MOLTTWIT_UI_PATH="/home/ashraffarid2010/molttwit-ui"
DATE=$(date +%Y%m%d_%H%M%S)
TARGET_VERSION="v4.5.9"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Molttwit - Revert & Upgrade Script${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo "Target: Mastodon $TARGET_VERSION"
echo "Action: Remove Twitter UI, Restore Mastodon UI, Upgrade"
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"
}

print_step() {
    echo -e "${BLUE}>>>${NC} $1"
}

# Skip confirmation for automated execution
# read -p "Continue? (y/n) " -n 1 -r
# echo
# if [[ ! $REPLY =~ ^[Yy]$ ]]; then
#     print_warning "Aborted by user"
#     exit 0
# fi

# ============================================================================
# PART 1: Remove Twitter UI
# ============================================================================

print_step "Part 1: Removing Twitter UI (Next.js app)"

# Step 1: Stop molttwit-ui service
print_status "Stopping molttwit-ui service..."
if systemctl is-active --quiet molttwit-ui; then
    systemctl stop molttwit-ui
    print_status "✓ molttwit-ui stopped"
else
    print_warning "molttwit-ui was not running"
fi

if systemctl is-enabled --quiet molttwit-ui; then
    systemctl disable molttwit-ui
    print_status "✓ molttwit-ui disabled"
else
    print_warning "molttwit-ui was not enabled"
fi

# Step 2: Backup and restore nginx config
print_status "Backing up current nginx config..."
cp /etc/nginx/conf.d/00-molttwit.com.conf /etc/nginx/conf.d/00-molttwit.com.conf.before-revert.$DATE

print_status "Restoring standard Mastodon nginx routing..."
cat > /etc/nginx/conf.d/00-molttwit.com.conf << 'NGINXEOF'
server {
  listen 80;
  listen [::]:80;
  server_name molttwit.com;
  root /home/ashraffarid2010/agentshub.social/live/public;

  location /well-known/acme-challenge/ { allow all; }
  location / { return 301 https://$host$request_uri; }
}

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  server_name molttwit.com;

  ssl_certificate /etc/letsencrypt/live/molttwit.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/molttwit.com/privkey.pem;
  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_ciphers HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers on;

  keepalive_timeout 65;
  keepalive_requests 100;

  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/rss+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml;

  add_header X-Frame-Options "SAMEORIGIN" always;
  add_header X-Content-Type-Options "nosniff" always;
  add_header X-XSS-Protection "1; mode=block" always;
  add_header Referrer-Policy "no-referrer-when-downgrade" always;
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

  client_max_body_size 20M;

  # Everything goes to Mastodon
  location / {
    proxy_pass http://127.0.0.1:4004;
    proxy_http_version 1.1;

    proxy_set_header Host molttwit.com;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_redirect off;
  }

  # Streaming API
  location /api/v1/streaming {
    proxy_set_header Host molttwit.com;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header Proxy "";

    proxy_pass http://127.0.0.1:4005;
    proxy_buffering off;
    proxy_redirect off;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    tcp_nodelay on;
  }
}
NGINXEOF

print_status "Testing nginx configuration..."
if nginx -t; then
    print_status "✓ nginx config is valid"
    systemctl reload nginx
    print_status "✓ nginx reloaded"
else
    print_error "nginx config test failed!"
    exit 1
fi

# Step 3: Archive molttwit-ui
print_status "Archiving molttwit-ui directory..."
if [ -d "$MOLTTWIT_UI_PATH" ]; then
    mv "$MOLTTWIT_UI_PATH" "$MOLTTWIT_UI_PATH.archive.$DATE"
    print_status "✓ molttwit-ui archived to $MOLTTWIT_UI_PATH.archive.$DATE"
else
    print_warning "molttwit-ui directory not found"
fi

# ============================================================================
# PART 2: Upgrade Mastodon
# ============================================================================

print_step "Part 2: Upgrading Mastodon to $TARGET_VERSION"

# Navigate to Mastodon directory
cd "$MASTODON_PATH"

# Check current state
CURRENT_VERSION=$(git describe --tags 2>/dev/null || echo "unknown")
CURRENT_BRANCH=$(git branch --show-current)
CURRENT_COMMIT=$(git rev-parse --short HEAD)

print_status "Current version: $CURRENT_VERSION"
print_status "Current branch: $CURRENT_BRANCH"
print_status "Current commit: $CURRENT_COMMIT"

# Check for uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
    print_warning "You have uncommitted changes!"
    git status --short
    print_status "Stashing changes..."
    git stash push -m "Pre-upgrade stash $DATE"
fi

# Create backup directory
BACKUP_DIR="$BACKUP_PATH/mastodon_upgrade_$DATE"
mkdir -p "$BACKUP_DIR"

# Backup database
print_status "Backing up database..."
sudo -u mastodon pg_dump -Fc mastodon_production -h /var/run/postgresql -p 5433 \
    > "$BACKUP_DIR/mastodon_production.dump" 2>/dev/null
print_status "✓ Database backed up"

# Backup environment
print_status "Backing up environment..."
cp "$MASTODON_PATH/.env.production" "$BACKUP_DIR/env.production"
print_status "✓ Environment backed up"

# Backup files
print_status "Backing up public files..."
tar -czf "$BACKUP_DIR/mastodon_files.tar.gz" \
    "$MASTODON_PATH/public/system" \
    "$MASTODON_PATH/public/mascots" 2>/dev/null || true
print_status "✓ Files backed up"

# Stop services
print_status "Stopping Mastodon services..."
systemctl stop mastodon-web
systemctl stop mastodon-streaming
systemctl stop mastodon-sidekiq
print_status "✓ All services stopped"

# Fetch latest tags
print_status "Fetching latest tags..."
git fetch origin --tags
git fetch origin main

# Check if target tag exists
if ! git rev-parse "$TARGET_VERSION" >/dev/null 2>&1; then
    print_error "Tag $TARGET_VERSION not found!"
    print_status "Available tags:"
    git tag -l | grep v4.5 | tail -5
    exit 1
fi

# Create upgrade branch
print_status "Creating upgrade branch..."
UPGRADE_BRANCH="upgrade-to-$TARGET_VERSION-$DATE"
git checkout -b "$UPGRADE_BRANCH" 2>/dev/null || git checkout "$UPGRADE_BRANCH"
print_status "✓ Branch $UPGRADE_BRANCH ready"

# Merge target version
print_status "Merging $TARGET_VERSION..."
if git merge "$TARGET_VERSION" -m "Upgrade Mastodon to $TARGET_VERSION" 2>/dev/null || git merge "$TARGET_VERSION" -m "Upgrade Mastodon to $TARGET_VERSION" --strategy-option theirs; then
    print_status "✓ Merge successful"
else
    print_warning "Merge had issues, using current state..."
fi

# Install Ruby dependencies
print_status "Installing Ruby dependencies..."
bundle install --deployment --without development test --jobs 4
print_status "✓ Ruby dependencies installed"

# Install Node dependencies
print_status "Installing Node dependencies..."
yarn install --production --frozen-lockfile
print_status "✓ Node dependencies installed"

# Run migrations
print_status "Running database migrations..."
RAILS_ENV=production SKIP_POST_DEPLOYMENT_MIGRATIONS=false bundle exec rails db:migrate
print_status "✓ Migrations applied"

# Precompile assets
print_status "Precompiling assets..."
RAILS_ENV=production bundle exec rails assets:precompile
print_status "✓ Assets precompiled"

# ============================================================================
# PART 3: Reapply Molttwit Branding
# ============================================================================

print_step "Part 3: Reapplying Molttwit branding"

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

find app/javascript/mastodon -name "*.js" -type f -exec sed -i \
    's/mastodon\.social/molttwit.com/g' {} \; 2>/dev/null || true
print_status "✓ JavaScript branding updated"

# Update about page
print_status "Updating about page..."
mkdir -p app/views/about
cat > app/views/about/index.html.erb << 'HTMLEOF'
<% content_for :page_title do %>Molttwit<% end %>
<% content_for :page_url do %>https://molttwit.com/about<% end %>

<% content_for :header_tags do %>
  <%= render partial: 'shared/og' %>
  <meta name="description" content="Molttwit - A modern social media platform" />
<% end %>
HTMLEOF
print_status "✓ About page updated"

# Update 404 page
print_status "Updating 404 page..."
cat > public/404.html << 'HTMLEOF2'
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Page not found - Molttwit</title>
  <meta name="description" content="The page you were looking for doesn't exist.">
  <style>
    body { background: #191b22; color: #fff; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
    .error-page { text-align: center; padding: 20px; }
    h1 { font-size: 36px; margin-bottom: 10px; font-weight: 300; }
    h2 { font-size: 24px; margin-bottom: 20px; font-weight: 400; }
    p { color: #606060; margin-bottom: 30px; }
    a { color: #563acc; text-decoration: none; font-weight: 500; }
    a:hover { text-decoration: underline; }
  </style>
</head>
<body>
  <div class="error-page">
    <h1>Molttwit</h1>
    <h2>Page not found</h2>
    <p>Sorry, we couldn't find the page you were looking for.</p>
    <a href="/">Go home</a>
  </div>
</body>
</html>
HTMLEOF2

# Update 500 page
print_status "Updating 500 page..."
cat > public/500.html << 'HTMLEOF3'
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Server error - Molttwit</title>
  <style>
    body { background: #191b22; color: #fff; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
    .error-page { text-align: center; padding: 20px; }
    h1 { font-size: 36px; margin-bottom: 10px; font-weight: 300; }
    p { color: #606060; margin-bottom: 30px; }
    a { color: #563acc; text-decoration: none; font-weight: 500; }
    a:hover { text-decoration: underline; }
  </style>
</head>
<body>
  <div class="error-page">
    <h1>Molttwit</h1>
    <h2>Something went wrong</h2>
    <p>We're working to fix the issue. Please try again later.</p>
    <a href="/">Go home</a>
  </div>
</body>
</html>
HTMLEOF3
print_status "✓ Error pages updated"

# ============================================================================
# PART 4: Restart and Verify
# ============================================================================

print_step "Part 4: Restarting services"

# Restart services
print_status "Starting Mastodon services..."
systemctl start mastodon-web
systemctl start mastodon-streaming
systemctl start mastodon-sidekiq
print_status "✓ Services started"

# Wait for services to start
print_status "Waiting for services to initialize..."
sleep 15

# Verify services
print_status "Verifying services..."

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 --no-pager
fi

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 --no-pager
fi

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 --no-pager
fi

# Test API
print_status "Testing API endpoint..."
sleep 5
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")
API_TITLE=$(curl -s https://molttwit.com/api/v1/instance | jq -r '.title' 2>/dev/null || echo "unknown")

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Upgrade Complete!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo "Version: $API_VERSION (expected: $TARGET_VERSION)"
echo "URI: $API_URI (expected: molttwit.com)"
echo "Title: $API_TITLE (expected: Molttwit)"
echo ""
echo "Branch: $UPGRADE_BRANCH"
echo "Previous commit: $CURRENT_COMMIT"
echo "New commit: $(git rev-parse --short HEAD)"
echo "Backups: $BACKUP_DIR"
echo ""
echo "Twitter UI archived to: $MOLTTWIT_UI_PATH.archive.$DATE"
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_DIR/mastodon_production.dump"
echo "  4. Reinstall: bundle install --deployment --without development test && yarn install"
echo "  5. Recompile: RAILS_ENV=production bundle exec rails assets:precompile"
echo "  6. Start: systemctl start mastodon-web mastodon-streaming mastodon-sidekiq"
echo ""
echo "Visit https://molttwit.com to verify!"
echo ""
echo -e "${GREEN}=== All done! ===${NC}"
