#!/bin/bash

# List of services to build

MINIMUM_REPOS=(
    "oc-auth"
    "oc-catalog"
    "oc-datacenter"
    "oc-peer"
    "oc-scheduler"
    "oc-schedulerd"
    "oc-workflow"
    "oc-workspace"
)

EXTRA_REPOS=(
    "oc-front"
    "oc-shared"
    "oc-monitord"
)

REPOS=("${MINIMUM_REPOS[@]}")  # Start with minimum repos

OC_ROOT="$(realpath ../..)"
DOCKER_BUILD="$(pwd)"
LOG_DIR="$DOCKER_BUILD/build_logs"
mkdir -p "$LOG_DIR"

cd "$OC_ROOT" || exit 1

# Function to build a service
build_service() {
    local service=$1
    local logfile="$LOG_DIR/$service.log"

    echo "[START] Building $service..."

    docker build -t "$service" "$OC_ROOT/$service" > "$logfile" 2>&1 &
    echo $!  # Return PID
}

# Track running builds
declare -A pids
declare -a active_services=()


# Select services to build
echo "🔧 Optional extra services:"
for i in "${!EXTRA_REPOS[@]}"; do
    echo "  [$((i+1))] ${EXTRA_REPOS[$i]}"
done

read -p "🟡 Do you want to add any extra services? Enter numbers separated by space (e.g., 1 3), or press Enter to skip: " -a selected

for index in "${selected[@]}"; do
    if [[ "$index" =~ ^[0-9]+$ ]] && (( index >= 1 && index <= ${#EXTRA_REPOS[@]} )); then
        REPOS+=("${EXTRA_REPOS[$((index-1))]}")
    else
        echo "⚠️  Invalid selection: $index"
    fi
done

echo "✅ Selected services:"
for repo in "${REPOS[@]}"; do
    echo "  - $repo"
done

# Launch builds
for service in "${REPOS[@]}"; do
    IMAGE_NAME="$service"

    # Check if the image exists locally
    if docker image inspect "$IMAGE_NAME" >/dev/null 2>&1; then
        read -p "🟡 Image '$IMAGE_NAME' already exists. Rebuild? (y/N): " rebuild
        if [[ "$rebuild" =~ ^[Yy]$ ]]; then
            echo "🔄 Rebuilding image for '$IMAGE_NAME'..."
        else
            echo "⏭️  Skipping build for '$IMAGE_NAME'."
            continue
        fi
    fi

    # Check if a container is already running from this image
    if docker ps --filter "ancestor=$IMAGE_NAME" --format '{{.ID}}' | grep -q .; then
        echo "✅ A container from image '$IMAGE_NAME' is already running. Skipping build."
    else
        SERVICE_PATH="$OC_ROOT/$service"
        if [ -d "$SERVICE_PATH" ]; then
            build_service "$service" &
            pids["$service"]=$!
            active_services+=("$service")
        else
            echo "⚠️  Directory not found for $service. Skipping."
        fi
    fi
done


echo "========================"
echo "Building: ${active_services[*]}"
echo "========================"

# Monitor logs for each build in parallel
for service in "${active_services[@]}"; do
    logfile="$LOG_DIR/$service.log"

    (
        tail -n 0 -f "$logfile" | while IFS= read -r line; do
            # Highlight docker build steps
            if [[ "$line" =~ Step\ ([0-9]+/[0-9]+) ]]; then
                echo -e "[$service] 🚧 ${BASH_REMATCH[0]}: $line"
            else
                echo "[$service] $line"
            fi
        done
    ) &
done

# Wait for all builds to complete
for pid in "${pids[@]}"; do
    wait "$pid"
done

for service in "${active_services[@]}"; do
    cd $OC_ROOT/service
    docker compose up -d
done

echo "✅ All builds completed."