#!/bin/bash
#
# queuemetrics-cli - Command line interface for QueueMetrics service management
#

if [ -z "${JAR}" ]
then
	JAR="/opt/loway/queuemetrics/"$( cat /lib/systemd/system/queuemetrics.service | grep "^ExecStart=" | sed "s:.*-jar ::" | awk '{print $1}' )""
fi

if [ "$( which -a sudo > /dev/null 2>&1 )" ]
then
	SUDO="sudo"
else
	SUDO=""
fi

usage() {
    cat <<EOF
Usage: queuemetrics-cli <command>

Commands:
  restart      Restart the QueueMetrics service
  stop         Stop the QueueMetrics service
  status       Show the status of the QueueMetrics service
  threaddump   Produce a thread dump
  version      Show QueueMetrics version
  dbupdater    Run the database updater
  journal      Show the latest 1000 lines of the journal file

EOF
    exit 1
}

threaddump() {
	if systemctl is-active --quiet queuemetrics
	then
		FILE="/opt/loway/queuemetrics/threaddumps/qm."$( date +%Y-%m-%d_%H%M%S )""
		PID="$( systemctl show --property=MainPID --value queuemetrics )"
		test -z "${PID}" && PID="$( systemctl show queuemetrics 2>/dev/null | sed -n 's/^MainPID=//p' )"

		if [ -z "${PID}" ]
		then
			echo "Unable to get the PID of the queuemetrics process"
		elif [ "$PID" -gt 0 ]
		then
			${SUDO} jcmd ${PID} GC.class_histogram >> "${FILE}"-histo.txt && echo "GC.class_histogram saved as "${FILE}"-histo.txt"
			${SUDO} jcmd ${PID} Thread.print >> "${FILE}".txt && echo "Thread.print saved as "${FILE}".txt"
		fi
	else
		echo "Service queuemetrics is not running"
	fi
}

case "${1}" in
    restart)
        ${SUDO} systemctl restart queuemetrics
        ;;
    stop)
        ${SUDO} systemctl stop queuemetrics
        ;;
    status)
        ${SUDO} systemctl status queuemetrics
        ;;
    threaddump)
        threaddump
        ;;
    version)
        java -jar ${JAR} version
        ;;
    dbupdater)
        shift
        java -jar ${JAR} dbupdater "$@"
        ;;
    journal)
	PAGER="cat" journalctl -u queuemetrics | tail -1000
	;;
    *)
        usage
        ;;
esac
