#!/bin/bash
set -eu
set -o pipefail

SCRIPT_NAME="$(basename $0)"

function show_options () {
    echo "Usage: ${SCRIPT_NAME} [options]"
    echo "Prints the size of the RabbitMQ cluster the remote-host"
    echo "is a member of, if any. If the node is not clustered or"
    echo "is in a cluster by itself, prints 0."
    echo "Options:"
    echo "    --remote-node <NODENAME> - The Rabbit remote node name to use."
    echo "                               Defaults to rabbit."
    echo "    --remote-host <HOSTNAME> - The Rabbit remote host name to use."
    echo "                               If not set, the local machine is inspected."
    exit ${1}
}

# RabbitMQ database is tied to the system hostname.
REMOTE_HOST="$(hostname)"
REMOTE_NODE="rabbit"

TEMP=$(getopt -o h -l help,remote_node:,remote-host: -n "${SCRIPT_NAME}" -- "${@}")
[ ${?} -ne 0 ] && { echo "Terminating..." >&2; exit 1; };

# Note the quotes around "$TEMP": they are essential!
eval set -- "${TEMP}"

while true ; do
    case "${1}" in
        -h | --help) show_options 0;;
        --remote-node) REMOTE_NODE="${2}"; shift 2;;
        --remote-host) REMOTE_HOST="${2}"; shift 2;;
        --) shift ; break ;;
        *) echo "Error: unsupported option ${1}." >&2 ; exit 1 ;;
    esac
done


# Number of nodes in the cluster according to remote host $2.
# If $2 isn't in a cluster or it's in a cluster by itself, then this will
# print 0.
function cluster_size() {
    local remote_node="${1}"
    local remote_host="${2}"
    echo "$(rabbitmqctl -n "${remote_node}@${remote_host}" cluster_status 2>/dev/null |
            awk '/running_nodes,\[[^]]+,/,/]},/' |
            sed 's/,\([^[]\)/,\n\1/g' |
            wc -l)"
}

cluster_size "${REMOTE_NODE}" "${REMOTE_HOST}"
