#!/bin/sh

# Fujitsu LIMITED 2017

# /usr/bin wrapper for running thresh topology start/stop/status.
# start&stop are used from systemd service files as, respectively, ExecStart and ExecStop
# status is add-on

case "$1" in
    start)
      $0 status
      if [ $? -ne 0 ]; then
        sudo -EHu monasca-thresh storm jar /usr/share/monasca-thresh/thresh.jar monasca.thresh.ThresholdingEngine /etc/monasca-thresh/thresh.yaml 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 -EHu monasca-thresh storm kill thresh-cluster
      # The above command returns but actually takes awhile loop watching status
      while true; do
        sudo -EHu monasca-thresh storm list | grep thresh-cluster
        if [ $? -ne 0 ]; then break; fi
        sleep 1
      done
    ;;
    status)
      sudo -EHu monasca-thresh storm list | grep thresh-cluster
    ;;
esac
