#!/bin/bash

<<Comment
    ************************************************************************************************************************
    * It Automatically Start Control process if binary exist.It Kill all control processes if more than one is present     *
    * and  start fresh one. If equal to one than process continue. If more than one control file is present then it will   *
    * pop a message informing more than one control binary present.                                                        *
    ************************************************************************************************************************
Comment

path=$NDHOME
if [ "X$path" == "X" ];
then
  path="/home/cavisson/netdiagnostics"
fi;


# bin/goAgent.
# Invoking control Process
Invoke()
{
  echo 'launching the agent'
  #export LD_PRELOAD=${path}/go/lib/libunwind.so:${path}/go/lib/libdyninstAPI_RT.so;
  nohup ${path}/go/bin/goAgent &>/dev/null &
  y=`ps -ef| grep "bin/goAgent" |grep -v "grep"|  grep -v "bin/cm_ps_data_ex" | tr -s ' ' | cut -d" " -f2`
  echo $y > $path/cavgoService.pid
}



checkAndRestartgoControlBin()
{
while :
do
# Counting no of control processes running.
  x=$(ps -ef | grep -v "grep"| grep "bin/goAgent" |  grep -v "bin/cm_ps_data_ex" -c)
  echo ${path}/go/bin/goAgent
# Checking if Control Binary exists in given path.
  if [ -f ${path}/go/bin/goAgent ]; then
  
    if [ $x -lt 1 ];then
      echo 'launching agent'
      echo $x
      Invoke
    fi

# Killing all the processes if >1.
  x=$(ps -ef | grep -v "grep"| grep "${path}/go/bin/goAgent" | grep -v "bin/cm_ps_data_ex" -c)
  if [ $x -gt 2 ];then
    y=( $(ps -ef | grep "bin/goAgent" | grep -v "bin/cm_ps_data_ex"| tr -s ' ' | cut -d" " -f2) )
    for i in ${y[*]}
    do
      echo 'killing service'
      echo $i
       kill -10 $i
    done
    > $path/cavgoService.pid
    Invoke
  fi

# Continue is =1 and recheck after 10 sec.
  elif [ $x -eq 1 ]; then
    sleep 10
    continue 
  else
    echo "goAgent Binary is not present"
    break
  fi
  
  sleep 10  
done

}
 
  
    checkAndRestartgoControlBin

