#!/bin/bash

if [ ! -f ~/run/pangu-rta-api.pid ]; then
  echo "Server [pangu-rta-api] doest not started!"
  exit
fi

pid=`cat ~/run/pangu-rta-api.pid`
if [ ! -n "${pid}" ]; then
  echo "illegal content in pangu-rta-api.pid!"
  exit
fi

process=`ps -aux|awk '{print $2}' | grep ${pid}`
if [ -n "${process}" ]; then
  echo "Server [pangu-rta-api] will be stop."
  kill ${pid}

  times=0
  while true
  do
    process=`ps -aux|awk '{print $2}' | grep ${pid}`
    if [ -n "${process}" ] && [ ${times} -lt 30 ]; then
      let times++
      sleep 1
    else
      break
    fi
  done

  process=`ps -aux|awk '{print $2}' | grep ${pid}`
  if [ -n "${process}" ]; then
    ## force kill process id
    ## kill -9 ${pid}
    echo "Server [pangu-rta-api] is running, Cannot stop in 30 sec!"
  fi
else
  echo "Server [pangu-rta-api] has been stoped."
fi

rm -f ~/run/pangu-rta-api.pid