#!/bin/bash

# Emergency Rollback Script for Production
# Usage: ./scripts/rollback.sh [backup_tag]

set -e

echo "🚨 EMERGENCY ROLLBACK INITIATED"

# Change to project directory
cd "$(dirname "$0")/.."

# Check if backup tag provided
if [ -n "$1" ]; then
    BACKUP_TAG="$1"
    echo "🔄 Rolling back to specific backup: $BACKUP_TAG"
else
    # Get the latest backup
    BACKUP_TAG=$(docker images --format "table {{.Repository}}:{{.Tag}}" | grep "vitron-frontend-backup" | head -1 | awk '{print $1}')
    if [ -z "$BACKUP_TAG" ]; then
        echo "❌ No backup images found!"
        echo "Available images:"
        docker images | grep vitron
        exit 1
    fi
    echo "🔄 Rolling back to latest backup: $BACKUP_TAG"
fi

# Stop current service
echo "🛑 Stopping current deployment..."
docker-compose -f docker-compose.yml down || true

# Tag backup as production image
echo "🏷️  Tagging backup as production image..."
docker tag "$BACKUP_TAG" vitron-frontend-prod:latest

# Start rollback service
echo "🔨 Starting rollback service..."
docker-compose -f docker-compose.yml up -d --no-build

# Wait for service
echo "⏳ Waiting for rollback service..."
sleep 30

# Health check
echo "🏥 Health check on rollback service..."
HEALTH_RETRIES=0
MAX_HEALTH_RETRIES=5

while [ $HEALTH_RETRIES -lt $MAX_HEALTH_RETRIES ]; do
    if docker exec vitron-frontend-prod wget --no-verbose --tries=1 --spider --timeout=10 http://localhost:3000/ 2>/dev/null; then
        echo "✅ Rollback service healthy!"
        break
    else
        echo "⏳ Health check attempt $((HEALTH_RETRIES + 1))/$MAX_HEALTH_RETRIES failed, retrying..."
        sleep 10
        HEALTH_RETRIES=$((HEALTH_RETRIES + 1))
    fi
done

if [ $HEALTH_RETRIES -eq $MAX_HEALTH_RETRIES ]; then
    echo "❌ Rollback service failed health check!"
    echo "🛑 Stopping rollback attempt..."
    docker-compose -f docker-compose.yml down
    exit 1
fi

# Final verification
echo "🏥 Final verification..."
sleep 10

if curl -f -s --max-time 10 https://vitrown.com/ > /dev/null; then
    echo "✅ ROLLBACK COMPLETED SUCCESSFULLY!"
    echo "🌐 Site is now accessible at https://vitrown.com"
    echo "📋 Rolled back to: $BACKUP_TAG"
else
    echo "❌ Final verification failed!"
    echo "🔍 Check Traefik configuration and DNS settings"
    exit 1
fi