#!/bin/bash

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

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

process=`ps -aux|awk '{print $2}' | grep ${pid}`
if [ -n "${process}" ]; then
  echo "Server [adscounter-youku] 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 [adscounter-youku] is running, Cannot stop in 30 sec!"
  fi
else
  echo "Server [adscounter-youku] has been stoped."
fi

rm -f ~/run/adscounter-youku.pid