#!/bin/bash
# Build core_room Docker images
#
# Usage:
#   ./build.sh              # Build all
#   ./build.sh <service>    # Build specific service
#   ./build.sh --no-cache   # Force rebuild without cache

set -e

# Change to parent directory (services are in ../service_name)
cd "$(dirname "$0")/.."

# Export core_room/.env vars so child docker-compose files can use them
if [ -f ".env" ]; then
    export $(grep -v '^#' .env | grep -v '^$' | xargs)
fi

TARGET="all"
NO_CACHE=""
SERVICE_DIRS=()

# Find all service directories (have docker-compose.yml, exclude ctrl/nginx)
for dir in */; do
    dirname="${dir%/}"
    if [ -f "$dir/docker-compose.yml" ] && [ "$dirname" != "ctrl" ] && [ "$dirname" != "nginx" ]; then
        SERVICE_DIRS+=("$dirname")
    fi
done

for arg in "$@"; do
    case $arg in
        --no-cache) NO_CACHE="--no-cache" ;;
        all) TARGET="all" ;;
        *)
            # Check if it's a valid service directory
            if [[ " ${SERVICE_DIRS[@]} " =~ " ${arg} " ]]; then
                TARGET="$arg"
            fi
            ;;
    esac
done

build_service() {
    local service=$1
    echo "Building $service images..."
    cd "$service"
    DOCKER_BUILDKIT=0 COMPOSE_DOCKER_CLI_BUILD=0 docker compose build $NO_CACHE
    cd ..
    echo "  $service images built"
}

if [ "$TARGET" = "all" ]; then
    for service in "${SERVICE_DIRS[@]}"; do
        build_service "$service"
        echo ""
    done
elif [[ " ${SERVICE_DIRS[@]} " =~ " ${TARGET} " ]]; then
    build_service "$TARGET"
else
    echo "Usage: ./build.sh [${SERVICE_DIRS[*]}|all] [--no-cache]"
    exit 1
fi

echo "=== Build Complete ==="
