#!/bin/bash

set -e

. ./CLUSTER-SERVER/_mongodb_cluster_common.bash

check_hostname()
{
    role=$1
    host=$2

    printf "%-28s %-36s " "$role" "$host"
    if getent hosts "$host" >/dev/null 2>&1; then
        echo "resolves"
    else
        echo "DOES NOT RESOLVE"
        return 1
    fi
}

failures=0
check_hostname "Router" "$GS_MONGODB_ROUTER_HOSTNAME" || failures=$((failures + 1))
check_hostname "Config server" "$GS_MONGODB_CONFIG_SERVER_HOSTNAME" || failures=$((failures + 1))

for shard_index in "${!GS_MONGODB_SHARD_HOSTNAMES[@]}"; do
    check_hostname \
        "Shard $((shard_index + 1))" \
        "${GS_MONGODB_SHARD_HOSTNAMES[$shard_index]}" || failures=$((failures + 1))
done

echo ""
echo "Replica sets:"
echo "  config: $GS_MONGODB_CONFIG_REPLSET"
for shard_index in "${!GS_MONGODB_SHARD_HOSTNAMES[@]}"; do
    echo "  shard $((shard_index + 1)): $(gs_mongodb_cluster_shard_connection "$shard_index")"
done

echo ""
echo "Current computer: $(hostname -s)"
roles=0
if gs_mongodb_cluster_host_is_local "$GS_MONGODB_ROUTER_HOSTNAME"; then
    echo "  role: router"
    roles=$((roles + 1))
fi
if gs_mongodb_cluster_host_is_local "$GS_MONGODB_CONFIG_SERVER_HOSTNAME"; then
    echo "  role: config server"
    roles=$((roles + 1))
fi
if local_shard_index=$(gs_mongodb_cluster_find_local_shard); then
    echo "  role: shard $((local_shard_index + 1))"
    roles=$((roles + 1))
fi
if [ "$roles" -eq 0 ]; then
    echo "  role: client/orchestration host only"
fi

if [ "$failures" -ne 0 ]; then
    echo "" >&2
    echo "$failures configured hostname(s) did not resolve." >&2
    exit 1
fi

echo ""
echo "Cluster setup is internally consistent and all hostnames resolve."
