#!/usr/bin/env sh

export DOCKER_HOST=unix:///var/run/docker.sock
docker_hosts=$(docker node ls --format '{{.Hostname}}')

# Retrieve the list of hosts from the Docker node (needs to run 
# within the Swarm).
# We use this list to configure RabbitMQ statically: On every node
# in the cluster, a RabbitMQ instance is running. They are 
# configured to use the Swarm node hostname as their hostname; so
# we can assume every cluster host to be a RabbitMQ node, too!
# This is a bit of a hack, but unfortunately using the DNS 
# discovery mechanism just isn't possible in Docker Swarm.
count=0
for host in ${docker_hosts}; do
  count=$((count + 1))
  echo "cluster_formation.classic_config.nodes.${count} = rabbit@rabbitmq-${host}" >> nodes.tmp.txt
done

lead='^# BEGIN DOCKER NODES$'
tail='^# END DOCKER NODES$'
sed -e "/${lead}/,/${tail}/{ /${lead}/{p; r nodes.tmp.txt}; /${tail}/p; d }"  rabbitmq.conf >> rabbitmq.tmp.conf
mv rabbitmq.tmp.conf rabbitmq.conf
rm nodes.tmp.txt

# Add the magic OAuth values to the configuration file. Sadly,
# RabbitMQ doesn't have much in terms of secret loading, so this 
# is the only way to get our secrets into the app.
echo "management.oauth_client_id = ${RABBITMQ_OAUTH_CLIENT_ID}" >> rabbitmq.conf
echo "management.oauth_provider_url = ${RABBITMQ_OAUTH_PROVIDER_URL}" >> rabbitmq.conf
echo "auth_oauth2.resource_server_id = ${RABBITMQ_OAUTH_RESOURCE_SERVER_ID}" >> rabbitmq.conf
echo "auth_oauth2.jwks_url = ${RABBITMQ_OAUTH_JWKS_URL}" >> rabbitmq.conf

# here, we build the rabbitmq metadata information as a json 
# schema we can import during the cluster boot. this will ensure
# our desired user accounts, vhosts, and exchanges exist when the
# cluster is formed.
# see here for more information on the schema definitions:
# https://www.rabbitmq.com/definitions.html#import-on-boot
RABBITMQ_VERSION="${RABBITMQ_VERSION:-3.11.9}"
RABBITMQ_PASSWORD_HASH=$(python bin/hash_rabbitmq_password.py "${RABBITMQ_PASSWORD}")
template='{"bindings":[],"exchanges":[],"global_parameters":[],"parameters":[],"permissions":[{"configure":".*","read":".*","user":"%s","vhost":"%s","write":".*"}],"policies":[],"queues":[],"rabbit_version":"%s","rabbitmq_version":"%s","topic_permissions":[],"users":[{"hashing_algorithm":"rabbit_password_hashing_sha256","limits":{},"name":"%s","password_hash":"%s","tags":["administrator"]}],"vhosts":[{"limits":[],"metadata":{"description":"default virtual host","tags":[]},"name":"%s"}]}'

printf -v rabbitmq_definitions "${template}" \
    "${RABBITMQ_USER}" \
    "${RABBITMQ_VHOST}" \
    "${RABBITMQ_VERSION}" \
    "${RABBITMQ_VERSION}" \
    "${RABBITMQ_USER}" \
    "${RABBITMQ_PASSWORD_HASH}" \
    "${RABBITMQ_VHOST}"
echo -e "${rabbitmq_definitions}" > rabbitmq_definitions.json