#!/bin/bash

# AAF Systems Homepage - Docker Load Script
# This script loads and runs a packaged Docker image on the target computer

echo "🚀 AAF Systems Homepage Docker Load & Run"
echo "========================================="

IMAGE_NAME="aaf-systems-homepage"
PACKAGE_NAME="aaf-systems-homepage-docker.tar"
CONTAINER_NAME="aaf-systems-homepage"

# Check if Docker is running
if ! sudo docker info > /dev/null 2>&1; then
    echo "❌ Docker is not running. Please start Docker and try again."
    exit 1
fi

# Check if package file exists
if [ ! -f "$PACKAGE_NAME" ]; then
    echo "❌ Package file '$PACKAGE_NAME' not found in current directory"
    echo "Please make sure the .tar file is in the same directory as this script"
    exit 1
fi

echo "📦 Loading Docker image from $PACKAGE_NAME..."
sudo docker load -i $PACKAGE_NAME

if [ $? -ne 0 ]; then
    echo "❌ Failed to load Docker image"
    exit 1
fi

echo "🛑 Stopping any existing container..."
sudo docker stop $CONTAINER_NAME 2>/dev/null || true
sudo docker rm $CONTAINER_NAME 2>/dev/null || true

echo "🚀 Starting container on port 8080..."
sudo docker run -d -p 8080:8080 --name $CONTAINER_NAME $IMAGE_NAME

if [ $? -eq 0 ]; then
    echo "✅ Container started successfully!"
    echo ""
    echo "🌐 Application is running at: http://localhost:8080"
    echo ""
    echo "📋 Useful Commands:"
    echo "=================="
    echo "View logs:     sudo docker logs $CONTAINER_NAME"
    echo "Stop container: sudo docker stop $CONTAINER_NAME"
    echo "Remove container: sudo docker rm $CONTAINER_NAME"
    echo "Check status:  sudo docker ps"
else
    echo "❌ Failed to start container"
    exit 1
fi
