#!/bin/bash

# Production Rollback Script
# Execute this if migration fails and you need to rollback
# Usage: ./production_rollback.sh [backup_timestamp]

set -e  # Exit on any error

if [ -z "$1" ]; then
    echo "ERROR: Please provide backup timestamp"
    echo "Usage: $0 <backup_timestamp>"
    echo ""
    echo "Available backups:"
    ls -la /var/backups/ | grep pos- | head -5
    exit 1
fi

BACKUP_TIMESTAMP="$1"
BACKUP_DIR="/var/backups/pos-$BACKUP_TIMESTAMP"
DB_BACKUP="$BACKUP_DIR/pos-database-$BACKUP_TIMESTAMP.sql.gz"
FILES_BACKUP="$BACKUP_DIR/pos-files-$BACKUP_TIMESTAMP.tar.gz"

echo "=== PRODUCTION ROLLBACK SCRIPT ==="
echo "Started at: $(date)"
echo "Backup timestamp: $BACKUP_TIMESTAMP"
echo "Executed by: $(whoami)"
echo ""

# Verify backups exist
echo "=== VERIFYING BACKUPS ==="
if [ ! -f "$DB_BACKUP" ]; then
    echo "ERROR: Database backup not found: $DB_BACKUP"
    exit 1
fi

if [ ! -f "$FILES_BACKUP" ]; then
    echo "ERROR: Files backup not found: $FILES_BACKUP"
    exit 1
fi

echo "Backups verified:"
ls -lh "$DB_BACKUP" "$FILES_BACKUP"
echo ""

# Step 1: Enter maintenance mode
echo "=== STEP 1: ENTER MAINTENANCE MODE ==="
php artisan down --render="errors::503" --message="System rollback in progress. Please try again in 10-15 minutes."
echo "Maintenance mode activated."
echo ""

# Step 2: Restore database
echo "=== STEP 2: DATABASE RESTORE ==="
echo "Restoring database from: $DB_BACKUP"
echo "This may take several minutes depending on database size..."

# Get database connection details from .env
DB_HOST=$(grep DB_HOST .env | cut -d'=' -f2 | tr -d '"')
DB_DATABASE=$(grep DB_DATABASE .env | cut -d'=' -f2 | tr -d '"')
DB_USERNAME=$(grep DB_USERNAME .env | cut -d'=' -f2 | tr -d '"')
DB_PASSWORD=$(grep DB_PASSWORD .env | cut -d'=' -f2 | tr -d '"')

if [ -z "$DB_HOST" ] || [ -z "$DB_DATABASE" ] || [ -z "$DB_USERNAME" ]; then
    echo "ERROR: Could not extract database credentials from .env"
    exit 1
fi

# Restore database
gunzip -c "$DB_BACKUP" | mysql \
    --host="$DB_HOST" \
    --user="$DB_USERNAME" \
    --password="$DB_PASSWORD" \
    "$DB_DATABASE"

echo "Database restore completed."
echo ""

# Step 3: Restore files
echo "=== STEP 3: FILES RESTORE ==="
echo "Restoring files from: $FILES_BACKUP"
echo "This may take several minutes..."

# Create backup of current files (just in case)
ROLLBACK_BACKUP="/tmp/rollback-pre-restore-$(date +%Y%m%d-%H%M%S)"
echo "Creating pre-restore backup at: $ROLLBACK_BACKUP"
sudo tar -czf "$ROLLBACK_BACKUP.tar.gz" \
    storage/ \
    public/ \
    .env \
    composer.lock \
    package-lock.json

# Restore files
sudo tar -xzf "$FILES_BACKUP" -C /

echo "Files restore completed."
echo ""

# Step 4: Clear caches and restart services
echo "=== STEP 4: CLEAR CACHES AND RESTART ==="
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear

# Restart services (adjust based on your setup)
sudo systemctl reload php-fpm
sudo systemctl restart supervisor

echo "Services restarted."
echo ""

# Step 5: Bring site live
echo "=== STEP 5: BRING SITE LIVE ==="
php artisan up

echo "Site is now live!"
echo ""

# Step 6: Verification
echo "=== STEP 6: VERIFICATION ==="
echo "6.1 Check application responds:"
curl -s -o /dev/null -w "HTTP Status: %{http_code}\n" https://your-domain.com/

echo "6.2 Monitor logs for errors:"
echo "  tail -f storage/logs/laravel-$(date +%Y-%m-%d).log"

echo ""
echo "=== ROLLBACK COMPLETED ==="
echo "Completed at: $(date)"
echo ""
echo "Please verify the application is working correctly:"
echo "1. Login as Super Admin and Store Admin"
echo "2. Test POS functionality"
echo "3. Check for any error messages in logs"
echo ""
echo "If rollback was successful, you can remove the pre-restore backup:"
echo "  rm $ROLLBACK_BACKUP.tar.gz"
