#!/bin/bash
set -e

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

echo -e "${GREEN}=== Enchun Docker Build & Push ===${NC}"
echo ""

# Configuration
IMAGE_PREFIX="${DOCKER_USERNAME:-pukpuklouis}"
BACKEND_IMAGE="${IMAGE_PREFIX}/website-enchun-cms"
FRONTEND_IMAGE="${IMAGE_PREFIX}/website-enchun-web"

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo -e "${RED}Error: Docker is not installed or not running${NC}"
    exit 1
fi

# Check if logged in to Docker Hub
if ! docker info | grep -q "Username"; then
    echo -e "${YELLOW}Warning: Not logged in to Docker Hub${NC}"
    echo -e "Please run: ${GREEN}docker login${NC}"
    exit 1
fi

# Function to build and push image
build_and_push() {
    local service=$1
    local image=$2
    local dockerfile=$3
    local context=$4

    echo -e "${YELLOW}Building ${service}...${NC}"
    echo -e "  Dockerfile: ${dockerfile}"
    echo -e "  Context: ${context}"
    docker build -t "${image}" -f "${dockerfile}" "${context}"

    if [ $? -ne 0 ]; then
        echo -e "${RED}Error: Failed to build ${service}${NC}"
        exit 1
    fi

    echo -e "${YELLOW}Pushing ${image}...${NC}"
    docker push "${image}"

    if [ $? -ne 0 ]; then
        echo -e "${RED}Error: Failed to push ${image}${NC}"
        exit 1
    fi

    echo -e "${GREEN}✓ ${service} built and pushed successfully${NC}"
}

# Main menu
echo "Select option:"
echo "1) Build and push frontend only"
echo "2) Build and push backend only"
echo "3) Build and push both"
echo "4) Exit"
echo ""
read -p "Enter choice: " choice

case $choice in
    1)
        build_and_push "frontend" "${FRONTEND_IMAGE}" "Dockerfile.frontend" "."
        ;;
    2)
        build_and_push "backend" "${BACKEND_IMAGE}" "Dockerfile.backend" "."
        ;;
    3)
        build_and_push "frontend" "${FRONTEND_IMAGE}" "Dockerfile.frontend" "."
        build_and_push "backend" "${BACKEND_IMAGE}" "Dockerfile.backend" "."
        ;;
    4)
        echo "Exiting..."
        exit 0
        ;;
    *)
        echo -e "${RED}Invalid option${NC}"
        exit 1
        ;;
esac

echo -e "${GREEN}=== Done ===${NC}"
