#!/bin/bash

# Verification script for multi-architecture Docker images
# Tests that images work correctly on different platforms

set -e

# Configuration
REGISTRY="gitea-http.taildb3494.ts.net/will/adopt-a-street"
BACKEND_IMAGE="${REGISTRY}/backend"
FRONTEND_IMAGE="${REGISTRY}/frontend"
VERSION=${1:-latest}

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

echo -e "${BLUE}🔍 Multi-Architecture Image Verification${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""

# Function to inspect image manifest
inspect_image() {
    local image_name=$1
    local image_tag=$2

    echo -e "${YELLOW}📋 Inspecting ${image_name} manifest...${NC}"
    docker buildx imagetools inspect "${image_name}:${image_tag}"
    echo ""
}

# Function to test image pull on specific platform
test_platform_pull() {
    local image_name=$1
    local platform=$2
    local temp_container="test-$(echo $image_name | tr '/' '-')-${platform//[^a-zA-Z0-9]/}"

    echo -e "${YELLOW}🧪 Testing ${image_name} pull for ${platform}...${NC}"

    # Pull image for specific platform
    docker pull --platform "${platform}" "${image_name}:${VERSION}"

    # Create and run a test container
    if [[ "$image_name" == *"backend"* ]]; then
        # Test backend - check if it starts
        docker run --rm --platform "${platform}" --name "${temp_container}" -d \
            -p 5001:5000 \
            -e NODE_ENV=test \
            "${image_name}:${VERSION}"

        # Wait a moment and check if container is running
        sleep 5
        if docker ps | grep -q "${temp_container}"; then
            echo -e "${GREEN}✅ Backend container started successfully on ${platform}${NC}"
            docker stop "${temp_container}" >/dev/null 2>&1 || true
        else
            echo -e "${RED}❌ Backend container failed to start on ${platform}${NC}"
        fi
    else
        # Test frontend - check if nginx starts
        docker run --rm --platform "${platform}" --name "${temp_container}" -d \
            -p 8080:80 \
            "${image_name}:${VERSION}"

        # Wait a moment and check if container is running
        sleep 5
        if docker ps | grep -q "${temp_container}"; then
            echo -e "${GREEN}✅ Frontend container started successfully on ${platform}${NC}"
            docker stop "${temp_container}" >/dev/null 2>&1 || true
        else
            echo -e "${RED}❌ Frontend container failed to start on ${platform}${NC}"
        fi
    fi

    # Clean up
    docker rmi "${image_name}:${VERSION}" >/dev/null 2>&1 || true
    echo ""
}

# Check if images exist
echo -e "${YELLOW}🔍 Checking if images exist...${NC}"
if ! docker buildx imagetools inspect "${BACKEND_IMAGE}:${VERSION}" >/dev/null 2>&1; then
    echo -e "${RED}❌ Backend image ${BACKEND_IMAGE}:${VERSION} not found${NC}"
    exit 1
fi

if ! docker buildx imagetools inspect "${FRONTEND_IMAGE}:${VERSION}" >/dev/null 2>&1; then
    echo -e "${RED}❌ Frontend image ${FRONTEND_IMAGE}:${VERSION} not found${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Both images found in registry${NC}"
echo ""

# Inspect image manifests
inspect_image "Backend" "${BACKEND_IMAGE}"
inspect_image "Frontend" "${FRONTEND_IMAGE}"

# Test platform pulls (only test current platform to avoid emulation issues)
CURRENT_PLATFORM=$(docker version --format '{{.Server.Arch}}')
echo -e "${YELLOW}🏗️  Current platform detected: ${CURRENT_PLATFORM}${NC}"
echo ""

if [[ "$CURRENT_PLATFORM" == "x86_64" ]]; then
    echo -e "${BLUE}Testing AMD64 platform...${NC}"
    test_platform_pull "${BACKEND_IMAGE}" "linux/amd64"
    test_platform_pull "${FRONTEND_IMAGE}" "linux/amd64"
elif [[ "$CURRENT_PLATFORM" == "aarch64" ]] || [[ "$CURRENT_PLATFORM" == "arm64" ]]; then
    echo -e "${BLUE}Testing ARM64 platform...${NC}"
    test_platform_pull "${BACKEND_IMAGE}" "linux/arm64"
    test_platform_pull "${FRONTEND_IMAGE}" "linux/arm64"
else
    echo -e "${YELLOW}⚠️  Unknown platform ${CURRENT_PLATFORM}, skipping container tests${NC}"
fi

echo -e "${GREEN}🎉 Multi-architecture image verification completed!${NC}"
echo ""
echo -e "${BLUE}Summary:${NC}"
echo "  ✅ Images exist in registry"
echo "  ✅ Manifest lists contain multiple architectures"
echo "  ✅ Images can be pulled and run on current platform"
echo ""
echo -e "${BLUE}To test on other platforms, run this script on:${NC}"
echo "  - AMD64 (x86_64) machine for linux/amd64 testing"
echo "  - ARM64 (aarch64) machine for linux/arm64 testing"
