#!/bin/bash

# Copyright 2014 Stephen Gran <sgran@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

usage(){
	ret=$1
	if [ $ret -gt 0 ]; then
		echo "Usage: $0 <hostname> <prefix> [<vhost>]" >&2
	else
		echo "Usage: $0 <hostname> <prefix> [<vhost>]"
	fi
	exit $ret
}

host=$1
prefix=$2
vhost=$3

if [ -z "$host" ] || [ "$host" = "-h" ] ||  [ "$host" = "--help" ]; then
	usage 3
fi

if [ -z "$prefix" ] || [ "$prefix" = "-h" ] ||  [ "$prefix" = "--help" ]; then
	usage 3
fi

if [ -z "$vhost" ]; then
	vhost=dsa
fi

if [ "$vhost" = "-h" ] ||  [ "$vhost" = "--help" ]; then
	usage 3
fi

if [ "${host/[^a-z0-9-]/}" != "$host" ]; then
	echo >&2 "$0: Invalid hostname $1"
	exit 3
fi

if [ "${prefix/[^a-z0-9-]/}" != "$prefix" ]; then
	echo >&2 "$0: Invalid prefix $2"
	exit 3
fi

check_output() {
	found=0
	while read name messages consumers; do
		found=1
		if [ "${name}" != "${prefix}-${host}.debian.org" ]; then
			echo "Unexpected output: ${name} ${messages} ${consumers}"
			return 3
		fi
		if [ "${messages}" -gt 0 ] ; then
			if [ "${consumers}" -eq 0 ]; then
				echo "${host} not connected to MQ"
				return 2
			fi
		fi
		return 0
	done
	if [ $found = 0 ]; then
		return 2
	fi
}

check_conn () {
	sudo -u rabbitmq rabbitmqctl list_queues -p ${vhost} name messages consumers \
		| grep "${prefix}-${host}.debian.org" \
		| check_output
	ret=$?
	if [ $ret != 0 ]; then
		echo "${host} not connected to MQ"
		return 2
	fi
	return 0
}
check_conn
ret=$?
if [ $ret -eq 0 ]; then
	echo "${host} connected to ${prefix}-${host}.debian.org in ${vhost}"
fi
exit $ret
