#!/bin/bash
# Test prepackaged containers (k484, atob)
# Builds containers and tests installation flow

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "📦 Testing Prepackaged Containers"
echo ""

# Determine container runtime
RUNTIME="auto"
if command -v podman >/dev/null 2>&1 && podman info >/dev/null 2>&1; then
    RUNTIME="podman"
elif command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
    RUNTIME="docker"
else
    echo "❌ No container runtime available!"
    exit 1
fi

echo "🐳 Using runtime: $RUNTIME"
echo ""

# Function to build and test a container
test_container() {
    local APP_ID="$1"
    local PACKAGE_DIR="$2"
    
    if [ ! -d "$PACKAGE_DIR" ]; then
        echo "⚠️  Skipping $APP_ID: package directory not found: $PACKAGE_DIR"
        return
    fi
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "Testing: $APP_ID"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    "$SCRIPT_DIR/test-container.sh" "$APP_ID" "$PACKAGE_DIR"
    
    echo ""
    sleep 2
}

# Test k484
if [ -d "$PROJECT_ROOT/../k484-package" ] || [ -d "$HOME/k484-package" ]; then
    K484_DIR="$PROJECT_ROOT/../k484-package"
    if [ ! -d "$K484_DIR" ]; then
        K484_DIR="$HOME/k484-package"
    fi
    test_container "k484" "$K484_DIR"
fi

# Test atob
if [ -d "$PROJECT_ROOT/../atob-package" ] || [ -d "$HOME/atob-package" ]; then
    ATOB_DIR="$PROJECT_ROOT/../atob-package"
    if [ ! -d "$ATOB_DIR" ]; then
        ATOB_DIR="$HOME/atob-package"
    fi
    test_container "atob" "$ATOB_DIR"
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ All container tests complete!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
