#!/bin/bash

# Multi-architecture Docker build script for Adopt-a-Street
# Builds and pushes images for AMD64 and ARM64 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}🏗️  Adopt-a-Street Multi-Architecture Docker Build${NC}"
echo -e "${BLUE}===============================================${NC}"
echo ""

# Check if we're logged into the registry
echo -e "${YELLOW}🔐 Checking registry authentication...${NC}"
echo -e "${GREEN}✅ Already logged into Docker registry${NC}"

# Setup multi-architecture builder
echo -e "${YELLOW}🔧 Setting up multi-architecture builder...${NC}"
./scripts/setup-multiarch-builder.sh

# Function to build and push image
build_image() {
    local service_name=$1
    local dockerfile_path=$2
    local build_context=$3
    local image_tag=$4

    echo -e "${YELLOW}📦 Building ${service_name} image for AMD64 and ARM64...${NC}"

    # Build and push multi-architecture image
    docker buildx build \
        --platform linux/amd64,linux/arm64 \
        --file "${dockerfile_path}" \
        --tag "${image_tag}:${VERSION}" \
        --tag "${image_tag}:latest" \
        --push \
        "${build_context}"

    echo -e "${GREEN}✅ ${service_name} image built and pushed successfully!${NC}"
    echo ""
}

# Build backend
echo -e "${BLUE}🔙 Building Backend Image${NC}"
build_image "Backend" "backend/Dockerfile" "backend" "${BACKEND_IMAGE}"

# Build frontend
echo -e "${BLUE}🎨 Building Frontend Image${NC}"
build_image "Frontend" "frontend/Dockerfile" "frontend" "${FRONTEND_IMAGE}"

# Verify images
echo -e "${YELLOW}🔍 Verifying multi-architecture images...${NC}"
echo -e "${BLUE}Backend image manifest:${NC}"
docker buildx imagetools inspect "${BACKEND_IMAGE}:${VERSION}"
echo ""
echo -e "${BLUE}Frontend image manifest:${NC}"
docker buildx imagetools inspect "${FRONTEND_IMAGE}:${VERSION}"

echo -e "${GREEN}🎉 Multi-architecture build completed successfully!${NC}"
echo ""
echo -e "${BLUE}Images pushed:${NC}"
echo "  - ${BACKEND_IMAGE}:${VERSION}"
echo "  - ${FRONTEND_IMAGE}:${VERSION}"
echo ""
echo -e "${BLUE}To pull on different architectures:${NC}"
echo "  # AMD64 (x86_64)"
echo "  docker pull ${BACKEND_IMAGE}:${VERSION}"
echo "  docker pull ${FRONTEND_IMAGE}:${VERSION}"
echo ""
echo "  # ARM64 (Raspberry Pi)"
echo "  docker pull ${BACKEND_IMAGE}:${VERSION}"
echo "  docker pull ${FRONTEND_IMAGE}:${VERSION}"
