#!/bin/bash
#
# (C) Copyright 2015 Hewlett Packard Enterprise Development Company LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

### 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 mon-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 mon-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 mon-thresh /opt/storm/current/bin/storm list |grep thresh-cluster
        if [ $? -ne 0 ]; then break; fi
        sleep 1
      done
    ;;
    status)
        sudo -Hu mon-thresh /opt/storm/current/bin/storm list |grep thresh-cluster
    ;;
    restart)
      $0 stop
      $0 start
    ;;
esac
