#!/bin/bash
set -e

echo "🚀 Qdrant Cluster Bootstrap Script"

# ECS metadata endpoint for Fargate
ECS_METADATA_URI="${ECS_CONTAINER_METADATA_URI_V4}"

if [ -n "$ECS_METADATA_URI" ]; then
    echo "📡 Fetching ECS task metadata..."

    # Get task metadata
    TASK_METADATA=$(curl -s "${ECS_METADATA_URI}/task")

    # Extract the task's private IP
    TASK_IP=$(echo "$TASK_METADATA" | jq -r '.Containers[] | select(.Name == "qdrant") | .Networks[0].IPv4Addresses[0]')

    if [ -z "$TASK_IP" ] || [ "$TASK_IP" = "null" ]; then
        echo "⚠️  Could not determine task IP from metadata, using hostname -i"
        TASK_IP=$(hostname -i | awk '{print $1}')
    fi

    echo "✅ Task IP: $TASK_IP"
else
    echo "⚠️  ECS metadata not available, using hostname -i"
    TASK_IP=$(hostname -i | awk '{print $1}')
    echo "✅ Task IP: $TASK_IP"
fi

# Only set cluster URL if clustering is enabled
if [ "${QDRANT__CLUSTER__ENABLED}" = "true" ]; then
    # Construct the cluster URL with the P2P port
    P2P_PORT="${QDRANT__CLUSTER__P2P__PORT:-6335}"
    CLUSTER_URL="http://${TASK_IP}:${P2P_PORT}"

    echo "🔗 Cluster URI: ${CLUSTER_URL}"
    echo "🔗 QDRANT__CLUSTER__ENABLED: ${QDRANT__CLUSTER__ENABLED}"
    echo "🔗 QDRANT__CLUSTER__P2P__PORT: ${P2P_PORT}"
    echo "🎯 Starting Qdrant with --uri flag..."

    # Execute Qdrant with --uri flag for cluster bootstrap
    exec /qdrant/qdrant --uri "${CLUSTER_URL}"
else
    echo "🎯 Starting Qdrant in standalone mode..."
    # Execute the original Qdrant binary
    exec /qdrant/qdrant
fi
