#!/bin/bash

# Docker auto-update script for Mawidi site with docker-compose
# Run this after making changes to automatically rebuild and restart Docker

echo "🔄 Starting Docker update process..."

# Change to project root
cd "$(dirname "$0")/.." || exit 1

# Check if docker-compose is available
if ! command -v docker-compose &> /dev/null; then
    echo "Using docker compose (v2) instead of docker-compose..."
    COMPOSE_CMD="docker compose"
else
    COMPOSE_CMD="docker-compose"
fi

# Build and start services
echo "📦 Building Docker image with docker-compose..."
$COMPOSE_CMD build --no-cache mawidi-app

if [ $? -eq 0 ]; then
    echo "✅ Docker image built successfully"

    # Stop existing services
    echo "🛑 Stopping existing containers..."
    $COMPOSE_CMD down

    # Start production service
    echo "🚀 Starting production container..."
    $COMPOSE_CMD up -d mawidi-app

    if [ $? -eq 0 ]; then
        echo "✅ Container started successfully!"
        echo "🌐 Site available at: http://localhost:9000"

        # Wait for container to be ready
        echo "⏳ Waiting for container to be ready..."
        sleep 5

        # Check container status
        if $COMPOSE_CMD ps | grep -q "mawidi-app.*Up"; then
            echo "✅ Container is running and healthy"
            $COMPOSE_CMD logs --tail=10 mawidi-app
        else
            echo "❌ Container failed to start properly"
            $COMPOSE_CMD logs mawidi-app
            exit 1
        fi
    else
        echo "❌ Failed to start container"
        exit 1
    fi
else
    echo "❌ Docker build failed"
    exit 1
fi

echo "🎉 Docker update complete!"