#!/usr/bin/env bash

set -e

if [ $# -ne 1 ]; then
    echo "Usage: ./helpers/deploy_rabbitmq.sh <values_base_dir>"
    exit 1
fi

# ci_geosphere-test
values_base="$1"

ns=$(./helpers/get_namespace.sh)
# copy secret kubeconfig to the mounted (pwd) directory
cp $kubekorner_k3s_config .
kubeconfig=$(basename $kubekorner_k3s_config)
# get password from any previous installation
# if we don't do this the password will get out of sync
# WARNING: If you can't figure out why the password isn't working and you
#          can't authenticate the user, double check that the PVC for rabbitmq
#          is deleted. This is storing the old password and may be messing
#          things up.
# Test user authentication by logging in to the rabbitmq pod and running:
#   rabbitmqctl authenticate_user user <password>
# where password is accessed from the kubectl secret:
#   kubectl get secret --namespace geosphere geosphere-rabbit-rabbitmq -o jsonpath="{.data.rabbitmq-password}" | base64 --decode
sec_info=$(kubectl --kubeconfig $kubeconfig get secret --namespace $ns geosphere-rabbit-rabbitmq || echo "")
echo $sec_info
auth_sec="geosphere-rabbit-rabbitmq"
if [[ "$sec_info" != "" ]]; then
    pw=$(kubectl --kubeconfig $kubeconfig get secret --namespace $ns $auth_sec -o jsonpath="{.data.rabbitmq-password}" | base64 -d);
    ec=$(kubectl --kubeconfig $kubeconfig get secret --namespace $ns $auth_sec -o jsonpath="{.data.rabbitmq-erlang-cookie}" | base64 -d);
    EXTRA_ARGS="--set auth.password=$pw --set auth.erlangCookie=$ec";
fi
echo "Adding extra arguments: $EXTRA_ARGS"
# install third-party rabbitmq server
helm repo add bitnami "https://charts.bitnami.com/bitnami"
helm upgrade -v 2 --install --kubeconfig $kubeconfig -f ${values_base}/values-geosphere-rabbit.yaml $EXTRA_ARGS --namespace $ns geosphere-rabbit bitnami/rabbitmq
# do a little waiting for the rabbitmq pod to be ready so future stages
# don't fail to communicate with it
echo "Start waiting for rabbitmq: $(date +%Y%m%dT%H%M%S)"
kubectl wait --kubeconfig $kubeconfig -n $ns pod/geosphere-rabbit-rabbitmq-0 --timeout 120s --for=condition=Ready
status=$?
echo "Done waiting for rabbitmq: $(date +%Y%m%dT%H%M%S) : $status"
exit $status
