#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite, Network Edition.
# Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Synacor, Inc.  All Rights Reserved.
# ***** END LICENSE BLOCK *****
# 

if [ x`whoami` != xzimbra ]; then
  echo Error: must be run as zimbra user
  exit 1
fi

platform=`/opt/zimbra/libexec/get_plat_tag.sh`

source `dirname $0`/zmshutil || exit 1
zmsetvars \
  zimbra_home \
  zimbra_log_directory \
  vmware_heartbeat_interval


pidfile=${zimbra_log_directory}/vmware-heartbeat.pid
vmware_heartbeat_interval=${vmware_heartbeat_interval:=15}

getpid() {
  if [ -f $pidfile ]; then
    cpid=`cat $pidfile`
  fi
}

checkrunning() {
  getpid
  if [ "x$cpid" = "x" ]; then
    running=0
  else
    kill -0 $cpid 2> /dev/null
    if [ $? != 0 ]; then
      rm $pidfile >/dev/null 2>&1
      cpid=""
      running=0
    else
      running=1
    fi
  fi
}

pskillall() {
  ps_cmd="/bin/ps ax -o pid,ppid,command"
  killsig="$1"
  pname=`echo "$2" | sed -e 's%/%\\\/%g'`
  plist=`${ps_cmd} | awk '{ if ( $3 ~ /'${pname}'/ ) { print $1 " " $2 } }' | sort -nr -k2 -k1 | awk '{ print $1 }'`
  for p in ${plist}
  do
    kill ${killsig} ${p}
  done
}


#
# Main
#
case "$1" in
  'start')

    checkrunning
    echo -n "Starting vmware-ha..."
    if [ $running = 1 ]; then
      echo "vmware-ha is already running.";
    else
      ${zimbra_home}/libexec/vmware-heartbeat start
      for ((i = 0; i < 12; i++)); do
        checkrunning
        if [ $running = 1 ]; then
          echo "done."
        exit 0
        fi
        sleep 5
      done
      echo "failed."
      exit 1
    fi
    exit 0
   ;;
  
  'kill')
    if [ -f ${zimbra_log_directory}/vmware-ha.pid ]; then
      cpid=`cat ${zimbra_log_directory}/vmware-ha.pid`
      kill -9 "$cpid" 2> /dev/null
    fi
    pskillall -9 ${zimbra_home}/libexec/vmware-heartbeat
    exit 0
   ;;

  'stop')
    checkrunning
    echo -n "Stopping vmware-ha..."
    if [ $running = 0 ]; then
      echo  "vmware-ha is not running.";
    else
      ${zimbra_home}/libexec/vmware-heartbeat stop
      checkrunning
      if [ x"$cpid" != "x" ]; then
        kill -TERM "$cpid" 2> /dev/null
      fi
      for ((i = 0; i < 30; i++)); do
        sleep 2
        kill -0 $cpid 2> /dev/null
        if [ $? != 0 ]; then
          rm -f ${pidfile} >/dev/null 2>&1
          break
        fi
        kill $cpid
      done
      if [ -s ${pidfile} ]; then
        echo "failed."
        exit 1
      else
        echo "done."
      fi
    fi
    exit 0
  ;;
  
  'restart'|'reload')
    $0 stop
    $0 start $2
  ;;
  
  'status')
    checkrunning
    echo -n "vmware-ha is "
    if [ $running = 1 ]; then
      echo "running."
      exit 0
    else
      echo "not runnning."
      exit 1
    fi
  ;;
  
  *)
    echo "Usage: $0 start|stop|kill|restart|status"
    exit 1
  ;;
esac
