#!/usr/bin/env bash
#
# Check if the given redis cluster is healthy.
#
# Usage: check_redis_cluster [-h host] [-p port] [-l]
#   -h <host>		Redis host (default 127.0.0.1)
#   -p <port>		Redis port (default 6379)
#   -l				Only check nodes with the same IP.
#

# Abort if we use an undeclared variable.
set -u

# Change to the folder containing this binary so we also have check_redis_node
cd "$(dirname "$0")"

OUTPUT=$(timeout 1 redis-cluster-nodes "$@" 2>&1)
STATUS=$?

if [[ $STATUS == 124 ]]; then
	echo "CRITICAL - PING timed out after 1 second"
	exit 2
elif [[ $STATUS != 0 ]]; then
	echo "CRITICAL - $OUTPUT"
	exit 2
fi

NODES=($OUTPUT)
COMBINED=0

# Loop over each cluster node entry.
for NODE in "${NODES[@]}"; do
	HOST=$(awk -F '[:@]' '{print $1}' <<< "$NODE")
	PORT=$(awk -F '[:@]' '{print $2}' <<< "$NODE")

	OUTPUT=$(./check_redis_node -h "$HOST" -p "$PORT" 2>&1)
	STATUS=$?

	if [[ "$STATUS" -gt "$COMBINED" ]]; then
		COMBINED="$STATUS"
	fi

	echo "$NODE - $OUTPUT"
done

exit "$COMBINED"
