#!/bin/bash
set -eu
set -o pipefail

SCRIPT_NAME="$(basename $0)"

function show_options () {
    echo "Usage: ${SCRIPT_NAME} [options]"
    echo "Let the local RabbitMQ node gracefully exit any cluster"
    echo "and clear down the local mnesia database. At the end of"
    echo "the process an attempt is made to restart the RabbitMQ"
    echo "Erlang pocesses even if a failure was encounted."
    echo "Options:"
    echo "    --force-reset         - Forcefully return the node to"
    echo "                            its virgin state."
    exit ${1}
}

RESET_OPTION="reset"

TEMP=$(getopt -o h -l help,force-reset -n "${SCRIPT_NAME}" -- "${@}")
[ $? -ne 0 ] && { echo "Terminating..." >&2; exit 1; };

# Note the quotes around "$TEMP": they are essential!
eval set -- "${TEMP}"

while true ; do
    case "${1}" in
        --force-reset) RESET_OPTION="force_reset"; shift ;;
        -h | --help) show_options 0 ;;
        --) shift ; break ;;
        *) echo "Error: unsupported option ${1}." >&2 ; exit 1 ;;
    esac
done


function reset_node() {
    local reset_option="${1}"
    rabbitmqctl stop_app
    # This syncs all data into the cluster, then removes this node, cleaning local mnesia.
    rabbitmqctl "${reset_option}"
}

if ! reset_node "${RESET_OPTION}"; then
   RET_VAL=${?}
   echo "Failed: Node has failed to correctly exit cluster" >&2
   rabbitmqctl start_app ||
       echo "Failed: Node has failed to start RabbitMQ app" >&2
   exit ${RET_VAL}
fi
