#!/usr/bin/env bash
#
# Delete the "guest" default user and replace it with a Zulip user
# with a real password
set -e
set -x

RABBITMQ_FLAGS=()
if [ -n "$RABBITMQ_NODE" ]; then
    RABBITMQ_FLAGS=(-n "$RABBITMQ_NODE")
fi
RABBITMQ_USERNAME=$("$(dirname "$0")/../get-django-setting" RABBITMQ_USERNAME)
RABBITMQ_PASSWORD=$("$(dirname "$0")/../get-django-setting" RABBITMQ_PASSWORD)

if [ "$EUID" -eq 0 ]; then
    RABBITMQCTL_COMMAND="rabbitmqctl"
else
    RABBITMQCTL_COMMAND="sudo rabbitmqctl"
fi

$RABBITMQCTL_COMMAND "${RABBITMQ_FLAGS[@]}" delete_user "$RABBITMQ_USERNAME" || true
$RABBITMQCTL_COMMAND "${RABBITMQ_FLAGS[@]}" delete_user zulip || true
$RABBITMQCTL_COMMAND "${RABBITMQ_FLAGS[@]}" delete_user guest || true
$RABBITMQCTL_COMMAND "${RABBITMQ_FLAGS[@]}" add_user "$RABBITMQ_USERNAME" "$RABBITMQ_PASSWORD"
$RABBITMQCTL_COMMAND "${RABBITMQ_FLAGS[@]}" set_user_tags "$RABBITMQ_USERNAME" administrator
$RABBITMQCTL_COMMAND "${RABBITMQ_FLAGS[@]}" set_permissions -p / "$RABBITMQ_USERNAME" '.*' '.*' '.*'
