#!/bin/bash
### BEGIN INIT INFO
# Provides:          monasca-thresh
# Required-Start:    $nimbus
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Monitoring threshold engine running under storm
# Description:
### END INIT INFO

case "$1" in
    start)
      $0 status
      if [ $? -ne 0 ]; then
        sudo -Hu thresh /opt/storm/current/bin/storm jar /opt/monasca/monasca-thresh.jar monasca.thresh.ThresholdingEngine /etc/monasca/thresh-config.yml thresh-cluster
        exit $?
      else
        echo "monasca-thresh is already running"
        exit 0
      fi
    ;;
    stop)
      # On system shutdown storm is being shutdown also and this will hang so skip shutting down thresh in that case
      if [ -e '/sbin/runlevel' ]; then  # upstart/sysV case
        if [ $(runlevel | cut -d\  -f 2) == 0 ]; then
          exit 0
        fi
      else  # systemd case
        systemctl list-units --type=target |grep shutdown.target
        if [ $? -eq 0 ]; then
          exit 0
        fi
      fi
      sudo -Hu thresh /opt/storm/current/bin/storm kill thresh-cluster
      # The above command returns but actually takes awhile loop watching status
      while true; do
        sudo -Hu thresh /opt/storm/current/bin/storm list |grep thresh-cluster
        if [ $? -ne 0 ]; then break; fi
        sleep 1
      done
    ;;
    status)
        sudo -Hu thresh /opt/storm/current/bin/storm list |grep thresh-cluster
    ;;
    restart)
      $0 stop
      $0 start
    ;;
esac
