#!/bin/sh

# PROVIDE: rabbitmq
# REQUIRE: DAEMON
# BEFORE: LOGIN
# KEYWORD: shutdown
#
# Add the following line to /etc/rc.conf to enable RabbitMQ
#
#  rabbitmq_enable="YES"

. /etc/rc.subr

name=rabbitmq
rcvar=rabbitmq_enable

load_rc_config $name

# Set some defaults
: ${rabbitmq_enable="NO"}
: ${rabbitmq_user="rabbitmq"}

rabbitmq_server="%%PREFIX%%/sbin/rabbitmq-server"
rabbitmq_ctl="%%PREFIX%%/sbin/rabbitmqctl"
rabbitmq_env_conf="%%PREFIX%%/etc/rabbitmq/rabbitmq-env.conf"
pidfile="/var/run/rabbitmq/${name}.pid"

start_cmd="${name}_start"
stop_cmd="${name}_stop"
rotate_logs_cmd="su -m ${rabbitmq_user} -c 'sh -c \"${rabbitmq_ctl} rotate_logs\"'"
status_cmd="su -m ${rabbitmq_user} -c 'sh -c \"${rabbitmq_ctl} status\"'"
extra_commands="rotate_logs status"

# ensure scripts find erlang_cookie
export HOME=/var/db/${name}
# set defaults but allow admin to override them in rabbitmq_env_conf
: ${RABBITMQ_HOME:=/var/db/${name}}
: ${RABBITMQ_LOG_BASE:=/var/log/${name}}
: ${RABBITMQ_PID_FILE:=${pidfile}}
# require precise OTP version in case multiple erlangs are installed
export PATH=%%PREFIX%%/lib/%%_ERLANG_LIB%%/bin:$PATH

if [ -f ${rabbitmq_env_conf} ]; then
    . ${rabbitmq_env_conf}
fi

# Prevent conflicts with amqp_client and rabbit_common applications that
# may be installed in ERL_LIBS.
unset ERL_LIBS

rabbitmq_start()
{
	echo "Starting ${name}."

	if [ -d ${RABBITMQ_HOME} ]; then
		chown -R ${rabbitmq_user}:${rabbitmq_user} ${RABBITMQ_HOME}
	fi

	mkdir -p ${RABBITMQ_LOG_BASE}

	chown -R ${rabbitmq_user}:${rabbitmq_user} ${RABBITMQ_LOG_BASE}

	if [ -f ${RABBITMQ_HOME}/.erlang.cookie ]; then
		chmod 600 ${RABBITMQ_HOME}/.erlang.cookie
	fi

	install -d -o ${rabbitmq_user} -g ${rabbitmq_user} /var/run/${name}

	export RABBITMQ_HOME RABBITMQ_LOG_BASE RABBITMQ_PID_FILE

	rm -f ${pidfile}

	debug "Running: rabbitmq-server -detached"
	su -m ${rabbitmq_user} -c "${rabbitmq_server} -detached" >/dev/null 2>&1
	debug "Running: rabbitmqctl wait ${pidfile}"
	su -m ${rabbitmq_user} -c "${rabbitmq_ctl} wait ${pidfile}" >/dev/null 2>&1
}

rabbitmq_stop()
{
	echo "Stopping ${name}."

	if [ -f ${pidfile} ]; then
		debug "Running: ${rabbitmq_ctl} stop ${pidfile}"
		su -m ${rabbitmq_user} -c "${rabbitmq_ctl} stop ${pidfile}" >/dev/null 2>&1
	else
		debug "Running: ${rabbitmq_ctl} shutdown"
		su -m ${rabbitmq_user} -c "${rabbitmq_ctl} shutdown" >/dev/null 2>&1
	fi
}

run_rc_command "$1"

