#!/bin/bash
set -euo pipefail

# MorphBox Docker Launcher

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info() { echo -e "${GREEN}[INFO]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
WEB_DIR="$SCRIPT_DIR/web"
CONTAINER_NAME="morphbox-vm"
IMAGE_NAME="morphbox:latest"

# Check if Docker is installed
if ! command -v docker > /dev/null; then
    error "Docker is not installed. Please install Docker first"
fi

# Build Docker image if it doesn't exist
if ! docker image inspect "$IMAGE_NAME" &> /dev/null; then
    info "Building MorphBox Docker image..."
    docker build -t "$IMAGE_NAME" "$SCRIPT_DIR" || error "Failed to build Docker image"
fi

# Check if container exists
if docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    # Check if it's running
    if ! docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
        info "Starting existing MorphBox container..."
        docker start "$CONTAINER_NAME"
    else
        info "MorphBox container is already running"
    fi
else
    info "Creating MorphBox container..."
    docker run -d \
        --name "$CONTAINER_NAME" \
        -p 2222:22 \
        -v "$PWD:/workspace" \
        "$IMAGE_NAME" || error "Failed to create container"
fi

# Wait for SSH to be ready
info "Waiting for container SSH to be ready..."
for i in {1..30}; do
    if ssh -p 2222 -o StrictHostKeyChecking=no -o ConnectTimeout=1 morphbox@localhost true 2>/dev/null; then
        break
    fi
    sleep 1
done

# Get container info
CONTAINER_SSH_PORT=2222
CONTAINER_SSH_HOST="localhost"

info "Container is running with SSH on port ${CONTAINER_SSH_PORT}"

# Create environment file with container connection info
cat > "$WEB_DIR/.env.local" << EOF
# MorphBox Container Connection
MORPHBOX_VM_HOST=${CONTAINER_SSH_HOST}
MORPHBOX_VM_PORT=${CONTAINER_SSH_PORT}
MORPHBOX_VM_USER=morphbox
EOF

# Now start the web interface
exec "$SCRIPT_DIR/morphbox-start" "$@"