#!/bin/bash
die(){
  [ -n "$@" ] && echo "$@"
  exit 1
}

usage(){
  cat<<EOF
  Usage: $0 RABBITMQ-HOST HTTP-CREDENTIALS VHOST

  Deletes unused, randomly-generated queues from amqp
EOF
  die
}

host="$1"
creds="$2"
vhost="$3" # "/" vhost
port=15672

pattern="/^amq\\.gen/"

ruby -rjson -e "puts JSON" &>/dev/null || die "Need ruby with json library"

[ -z "$host" ] || [ -z "$creds" ] || [ -z "$vhost" ] && echo "Wrong arguments" && usage

curl -s -XGET http://$host:$port/ &>/dev/null || die "http://$host:$port/ not responding"

case $vhost in
  /) vhost="%2F" ;;
  %*) ;;
  *) vhost=$(echo "$vhost" | ruby -rcgi -e 'puts CGI.escape($stdin.read)') ;;
esac


[ -z "$vhost" ] && die "Can't escape vhost"

uri="http://$host:$port/api"

queues=$(curl -s -XGET -u$creds $uri/queues | ruby -rcgi -rjson -e"
  JSON.parse(\$stdin.read)
    .select { |q| q['consumers'] == 0 && q['name'] =~ $pattern }
    .each { |q| puts CGI.escape(q['name']) }
")

count=$(echo -e "$queues" | wc -l)

echo "$count queues in vhost $vhost that looks like $pattern"
echo "Deleting...(ctrl-c to break, enter to continue)"
read

for q in $(echo -e $queues); do
 if curl -s -XDELETE -u$creds "$uri/queues/$vhost/$q"; then
    echo "Deleted $q"
  else
    echo "Failed to delete $q"
    echo "Continue?"
    read
  fi
done
