#!/bin/bash
#
# Daemon Name: CloudStats Monitoring
#
# chkconfig: - 58 74
# description: universal init.d script for the agent
#
#

### BEGIN INIT INFO
# Provides:          CloudStats Monitoring
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: agent startup script
# Description:       universal init.d script for agent.
### END INIT INFO

# absolute path to the executable library
homepath='/home/cloudstats_agent'
progpath='/home/cloudstats_agent/cloudstats-agent'

# binary name
prog=cloudstats-agent
keepalive_prog="$homepath/keepalive"

# pid file
pidfile="/var/run/${prog}.pid"

# check the binary if not there exit
! [ -x $progpath ] && echo "$progpath: Agent not found" && exit 1

eval_cmd() {
  local rc=$1
  if [ $rc -eq 0 ]; then
    echo '[  OK  ]'
  else
    echo '[FAILED]'
  fi
  return $rc
}

start() {
  # check if it's already running
  local pids=$(pidof -c $prog)

  if [ -n "$pids" ]; then
    echo "$prog (pid $pids) is already running"
    return 0
  fi
  printf "%-50s%s" "Starting $prog: " ''
  ENV=production $progpath > /dev/null 2>&1 &

  # save pid to file
  local pid=$!
  echo $pid > $pidfile

  # check again if it's running
  ps -p $pid >/dev/null 2>&1
  eval_cmd $?
}

stop() {
  # check if it's running
  local pids="$(pidof -cx $keepalive_prog) $(pidof -c $prog)"

  if [ ${#pids} -lt 2 ]; then
    echo "$prog not running"
    return 0
  fi
  printf "%-50s%s" "Stopping $prog: " ''
  rm -f $pidfile
  kill -9 $pids
  eval_cmd $?
}

status() {
  # check if it's running
  local  pids=$(pidof -c $prog)

  if [ -n "$pids" ]; then
    echo "$prog (pid $pids) is running"
  else
    echo "$prog is stopped"
  fi
}

uninstall() {
  # check if it's running
  stop

  rm -rf /home/cloudstats_agent
  rm -rf /etc/init.d/cloudstats-agent
  eval_cmd $?
  echo "CloudStats Agent has been uninstalled."
}

case $1 in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    status
    ;;
  uninstall)
    uninstall
    ;;
  restart)
    stop
    sleep 1
    start
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart|uninstall}"
    exit 1
esac

exit $?
