#!/bin/bash

# Production Migration Runbook
# Execute these commands on production server in maintenance window
# Total estimated time: 15-30 minutes

set -e  # Exit on any error

echo "=== PRODUCTION MIGRATION RUNBOOK ==="
echo "Started at: $(date)"
echo "Executed by: $(whoami)"
echo ""

# Step 1: Pre-flight checks
echo "=== STEP 1: PRE-FLIGHT CHECKS ==="
echo "1.1 Verify backups exist and are recent:"
ls -la /var/backups/pos-*/ | tail -5

echo "1.2 Check current git status:"
git status
git log --oneline -5

echo "1.3 Check PHP and Node versions:"
php --version | head -1
node --version
npm --version

echo "1.4 Check disk space:"
df -h /

echo "1.5 Check memory:"
free -h

echo ""

# Step 2: Put site in maintenance mode
echo "=== STEP 2: ENTER MAINTENANCE MODE ==="
echo "Putting site in maintenance mode..."
php artisan down --render="errors::503" --message="System maintenance in progress. Please try again in 15-30 minutes."

echo "Maintenance mode activated. Site should show maintenance page."
echo ""

# Step 3: Deploy new code
echo "=== STEP 3: DEPLOY CODE ==="
echo "3.1 Pull latest code:"
git pull origin main  # Adjust branch name as needed
git log --oneline -3

echo "3.2 Install PHP dependencies:"
composer install --no-dev --optimize-autoloader --no-interaction

echo "3.3 Install Node dependencies:"
npm ci --no-audit --no-fund

echo "3.4 Build assets:"
npm run build

echo "3.5 Clear old caches:"
php artisan config:clear
php artisan route:clear
php artisan view:clear

echo ""

# Step 4: Database migration
echo "=== STEP 4: DATABASE MIGRATION ==="
echo "4.1 Check migration status:"
php artisan migrate:status

echo "4.2 Run migrations:"
php artisan migrate --force

echo "4.3 Run any necessary seeders:"
# Add specific seeders here if needed
# php artisan db:seed --class=YourSeeder --force

echo "4.4 Verify migration completion:"
php artisan migrate:status | grep -E "(Pending|Ran)"

echo ""

# Step 5: Post-migration setup
echo "=== STEP 5: POST-MIGRATION SETUP ==="
echo "5.1 Warm up caches:"
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "5.2 Restart services:"
# Adjust these commands based on your server setup
sudo systemctl reload php-fpm  # or nginx restart
sudo systemctl restart supervisor  # for queue workers

echo ""

# Step 6: Smoke tests
echo "=== STEP 6: SMOKE TESTS ==="
echo "6.1 Check application health:"
curl -s -o /dev/null -w "%{http_code}" https://your-domain.com/health  # If you have a health endpoint

echo "6.2 Test key pages (should return maintenance page):"
curl -s -o /dev/null -w "%{http_code}" https://your-domain.com/

echo ""

# Step 7: Bring site live
echo "=== STEP 7: BRING SITE LIVE ==="
echo "Removing maintenance mode..."
php artisan up

echo "Site is now live!"
echo ""

# Step 8: Post-deploy verification
echo "=== STEP 8: POST-DEPLOY VERIFICATION ==="
echo "8.1 Monitor logs for errors:"
tail -f storage/logs/laravel-$(date +%Y-%m-%d).log &
LOG_PID=$!

echo "8.2 Test login functionality (manual step):"
echo "   - Open browser to https://your-domain.com"
echo "   - Login as Super Admin: tsdcambodia@gmail.com / 123456"
echo "   - Login as Store Admin: admin@example.com / 123456"
echo "   - Verify POS screen loads"
echo "   - Test creating a basic order"
echo "   - Test Purchase Order functionality"

echo ""
echo "8.3 Stop log monitoring (after verification):"
kill $LOG_PID

echo ""
echo "=== MIGRATION COMPLETED SUCCESSFULLY ==="
echo "Completed at: $(date)"
echo ""
echo "ROLLBACK COMMANDS (if needed):"
echo "  # Enter maintenance:"
echo "  php artisan down --render="errors::503""
echo ""
echo "  # Restore database:"
echo "  gunzip -c /var/backups/pos-{TIMESTAMP}/pos-database-{TIMESTAMP}.sql.gz | mysql -u USER -p DB_NAME"
echo ""
echo "  # Restore files:"
echo "  sudo tar -xzf /var/backups/pos-{TIMESTAMP}/pos-files-{TIMESTAMP}.tar.gz -C /"
echo ""
echo "  # Bring site back:"
echo "  php artisan up"
