#!/bin/bash
# Move to the script's directory
cd "$(dirname "$0")"

# 1. ROBUST ENV SOURCING (Same logic as MinIO/Keepalived)
ENV_PATH="/docker/mongo/.env"
if [ -f "$ENV_PATH" ]; then
    while read -r line || [ -n "$line" ]; do
        [[ "$line" =~ ^#.*$ ]] && continue
        [[ -z "$line" ]] && continue
        export "${line//\"/}"
    done < "$ENV_PATH"
else
    echo "ERROR: .env file not found!"
    exit 1
fi

STATUS_JSON=$(docker exec -t "mongo-db${KOMODO_NODE_ID}" mongosh --quiet --eval "rs.status()" 2>/dev/null)
IS_INIT=$(echo "$STATUS_JSON" | grep -c "ok: 1")

if [ "$IS_INIT" -gt 0 ]; then
    echo "✅ MongoDB is already part of a replica set. Nothing to do."
    exit 0
fi

if [ "$KOMODO_NODE_ID" == "1" ]; then
    echo "👑 Node 1 detected. Initiating as Primary for 'rs${LXC_NUM}'..."
    
    # Initiate with just self to guarantee Primary status
    docker exec -t "mongo-db1" mongosh --eval "
    rs.initiate({
      _id: 'rs${LXC_NUM}',
      members: [{ _id: 0, host: 'mongo-db1:27017' }]
    })"
    
    echo "⏳ Waiting for election..."
    sleep 5
    
    # Pre-authorize the partner
    docker exec -t "mongo-db1" mongosh --eval "rs.add('mongo-db2:27017')"
    echo "🚀 Node 1 is now Primary and waiting for Node 2."

else
    echo "🏃 Node 2 detected. Attempting to handshake with Node 1..."
    
    # Node 2 doesn't initiate. It just waits for Node 1 to be ready.
    # Node 1 already ran rs.add('mongo-db2'), so Node 2 just needs to be up.
    echo "🤝 Node 2 is online. Synchronization should start automatically via Node 1's config."
fi