#!/bin/sh

# EXPORT
export MGR_EXEM_HOME={{ EXEM_HOME }}
export MGR_EXEM_MANAGER_HOME={{ EXEM_HOME }}/manager


# STOP
PIDFILE=${MGR_EXEM_MANAGER_HOME}/data/manager_agent_pid

if [ -f "${PIDFILE}" ]; then
  PID=`echo -n | cat ${PIDFILE}`
  mv ${PIDFILE} ${PIDFILE}.stopped

  # WAITING
  LIMIT_CNT=10
  CNT=0
  while [ ${CNT} -lt ${LIMIT_CNT} ];
  do
    IS_RUNNING=`ps -fp "${PID}" | grep -c exem-manager-agent`
    if [ "${IS_RUNNING}" -ne 0 ]; then
      CNT=`expr $CNT + 1`
      echo "exem-manager-agent is stopping (${PID}) ..."
      sleep 1
    else
      break
    fi
  done

  if [ ${CNT} -ge ${LIMIT_CNT} ]; then
    echo "Something is wrong. Check exem-manager-agent (${PID})"
    exit 1
  fi

  echo "exem-manager-agent is stopped (${PID})"

else
  echo "exem-manager-agent is not running"
fi

echo "exem-manager-agent is stopped [binary_stop.sh]"