#!/bin/bash

set -e

. ./CLUSTER-SERVER/_mongodb_cluster_common.bash

gs_mongodb_cluster_require_local_role \
    "router" \
    "$GS_MONGODB_ROUTER_HOSTNAME"

echo "Registering shards through router:"
echo "  $GS_MONGODB_ROUTER_HOSTNAME:$GS_MONGODB_ROUTER_PORT"

for shard_index in "${!GS_MONGODB_SHARD_HOSTNAMES[@]}"; do
    SHARD_CONNECTION=$(gs_mongodb_cluster_shard_connection "$shard_index")
    SHARD_NAME=$(gs_mongodb_cluster_shard_replset "$shard_index")

    echo ""
    echo "Checking shard $((shard_index + 1)): $SHARD_CONNECTION"

    "$GS_MONGODB_SHELL" \
        --quiet \
        --host "$GS_MONGODB_ROUTER_HOSTNAME" \
        --port "$GS_MONGODB_ROUTER_PORT" \
        --eval "
var shardName = \"$SHARD_NAME\";
var shardConnection = \"$SHARD_CONNECTION\";
var configDB = db.getSiblingDB(\"config\");
var existing = configDB.shards.findOne({_id: shardName});

if (existing) {
    print(\"Shard '\" + shardName + \"' is already registered as \" + existing.host + \".\");
    if (existing.host !== shardConnection) {
        throw new Error(
            \"Configured connection string is '\" + shardConnection +
            \"', but the cluster records '\" + existing.host + \"'.\"
        );
    }
}
else {
    printjson(sh.addShard(shardConnection));
}
"
done

echo ""
echo "Current cluster status:"
"$GS_MONGODB_SHELL" \
    --quiet \
    --host "$GS_MONGODB_ROUTER_HOSTNAME" \
    --port "$GS_MONGODB_ROUTER_PORT" \
    --eval 'sh.status()'
