#!/bin/sh -e

DARUMA_INSTALL_DIR=/usr/local/daruma
DARUMA_LOG_DIR=/var/tmp
DARUMA_LOG_FILE=daruma
DARUMA_LOG_GZIP=false
DARUMA_CLIENT_COMMAND=darumaClient
DARUMA_ADMIN_PORT=5051

PRINT_MESSAGE_ON_STARTING_ENDING=false

JAVA_HOME=/usr/java/default
PATH=$JAVA_HOME/bin:$PATH
export JAVA_HOME PATH


usage()
{
	echo "Usage: ${0} COMMAND"
	echo "Possible COMMAND are:"
	echo "     start"
	echo "     stop"
	echo "     restart"
	echo "     status"
}

if [ $# -ne 1 ]; then
	usage 1>&2
	exit 1
fi

command="${1}"

daruma_start()
{
	if [ X"${PRINT_MESSAGE_ON_STARTING_ENDING}" = X'true' ]; then
		echo 'daruma'
	fi

	if [ X"${DARUMA_LOG_GZIP}" = X'true' ]; then
		if [ -e "${DARUMA_LOG_DIR}/${DARUMA_LOG_FILE}".gz ]; then
			mv "${DARUMA_LOG_DIR}/${DARUMA_LOG_FILE}".gz \
			   "${DARUMA_LOG_DIR}/${DARUMA_LOG_FILE}".old.gz
		fi

		("${DARUMA_INSTALL_DIR}"/run 2>&1) \
			| gzip >> "${DARUMA_LOG_DIR}/${DARUMA_LOG_FILE}".gz &
	else
		"${DARUMA_INSTALL_DIR}"/run \
			>> "${DARUMA_LOG_DIR}/${DARUMA_LOG_FILE}" 2>&1 &
	fi
}

daruma_stop()
{
	if [ X"${PRINT_MESSAGE_ON_STARTING_ENDING}" = X'true' ]; then
		echo 'daruma'
	fi

	echo 'shutdown' | $DARUMA_CLIENT_COMMAND -p "${DARUMA_ADMIN_PORT}"
}

daruma_status()
{
	echo 'list' | $DARUMA_CLIENT_COMMAND -p "${DARUMA_ADMIN_PORT}"
}


case "${command}" in

	start)
		daruma_start
		;;

	stop)
		daruma_stop
		;;

	restart)
		daruma_stop
		daruma_start
		;;

	status)
		daruma_status
		;;

	*)
		usage 1>&2
		exit 1
		;;
esac
