#!/bin/sh

# EXPORT
export EXEM_HOME={{ EXEM_HOME }}
export EXEM_CONTAINER_HOME={{ EXEM_HOME }}/container


# STOP
PIDFILE=${EXEM_CONTAINER_HOME}/data/container_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-container-agent)
    if [ "${IS_RUNNING}" -ne 0 ]; then
      CNT=$((CNT+1))
      echo "exem-container-agent is stopping (${PID}) ..."
      sleep 1
    else
      break
    fi
  done

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

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

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