#!/bin/bash

set -e

. ./CLUSTER-SERVER/_mongodb_cluster_common.bash

gs_mongodb_cluster_require_local_role "router" "$GS_MONGODB_ROUTER_HOSTNAME"

REMOTE_DIR=${1:-$GS_MONGODB_REMOTE_SOURCE_DIR}
SOURCE_FILE="$GS_MONGODB_SOURCE_HOME/_mongodb_cluster_setup.bash"

[ -f "$SOURCE_FILE" ] || gs_mongodb_die "Missing $SOURCE_FILE"

copy_to_host()
{
    host=$1

    if gs_mongodb_cluster_host_is_local "$host"; then
        return 0
    fi

    for copied_host in "${COPIED_HOSTS[@]}"; do
        [ "$copied_host" != "$host" ] || return 0
    done
    COPIED_HOSTS+=("$host")

    printf -v remote_dir_q '%q' "$REMOTE_DIR"
    "$GS_MONGODB_SSH_COMMAND" \
        "${GS_MONGODB_SSH_OPTIONS[@]}" \
        "$host" \
        "test -d $remote_dir_q"

    echo "Copying cluster setup to $host:$REMOTE_DIR/"
    "$GS_MONGODB_SCP_COMMAND" \
        "${GS_MONGODB_SCP_OPTIONS[@]}" \
        "$SOURCE_FILE" \
        "$host:$REMOTE_DIR/_mongodb_cluster_setup.bash"
}

COPIED_HOSTS=()
copy_to_host "$GS_MONGODB_CONFIG_SERVER_HOSTNAME"
for shard_host in "${GS_MONGODB_SHARD_HOSTNAMES[@]}"; do
    copy_to_host "$shard_host"
done

echo "Cluster setup copied to all other configured hosts."
