#!/usr/bin/bash
# Author : yingjian
# Version : v1.1
# Date : 2023-03-06

if [ $# -ne 2 ];then
    echo "当前传入参数错误。"
    echo "Please bash check_game_process.sh \$1 {例如 P7} \$2{例如 mzuofang} "
    exit 2
fi

#获取本机 公网 ip地址
#local_ip=$(/bin/curl http://metadata.tencentyun.com/meta-data/public-ipv4)


#获取当前日期
date_dir=`date "+%F"`

#获取7天前日期
date_seven_ago=`date -d "7 days ago" +%F`

#获取脚本目录
cd `dirname $0`
script_dir=`pwd`

#项目目录
project_dir=$1

#平台目录
platform_dir=$2

#游戏项目发行目录
game_dir=${1}/${2}

check_log_dir=${script_dir}/logs

if [ ! -d $check_log_dir ];then
     mkdir -p $check_log_dir
fi

#获取游戏服id
get_game_server_id () {
  /bin/ls /${game_dir}|grep ^[0-9]*$ |tee -a > ${script_dir}/game_server_id.txt 
}

#检测游戏进程是否存活
check_process () {
while read line
do
#    echo $line
#游戏进程pid
  game_process_pid=`ps -ef |grep /${game_dir}/$line/runtime |grep -v grep |awk '{print $2}'`
#  echo $game_process_pid
#判断获取进程pid是否为空
  if [ -n "$game_process_pid" ]; then
    echo "该游戏进程存在 进程pid为：$game_process_pid" >> ${check_log_dir}/${date_dir}_game_process.log
  else
    echo "`date "+%Y-%m-%d %H:%M:%S"` 该游戏进程不存在 该游戏服id为：$line" >> ${check_log_dir}/${date_dir}_game_err_process.log
    /usr/bin/python3 ${script_dir}/feishu.py "告警时间 : `date "+%Y-%m-%d %H:%M:%S"`,项目 : ${project_dir},平台名称 : ${platform_dir},游戏服: ${line},告警原因 : 游戏进程不存在"
#启动已经挂掉游戏进程
    sudo /usr/bin/bash /${game_dir}/${line}/server_upload/server_ctrl_auto.sh start debug >> ${check_log_dir}/${date_dir}_game_err_process.log
    sleep 15
    re_game_process_pid=`ps -ef |grep /${game_dir}/$line/runtime |grep -v grep |awk '{print $2}'`
    if [ -n "$re_game_process_pid" ]; then
      /usr/bin/python3 ${script_dir}/feishu.py "告警时间 : `date "+%Y-%m-%d %H:%M:%S"`,项目 : ${project_dir},平台名称 : ${platform_dir},游戏服: ${line},告警原因 : 游戏进程已恢复,进程id ：${re_game_process_pid}"
    fi
  fi
done < ${script_dir}/game_server_id.txt
}

get_game_server_id

sleep 2

check_process

rm -f ${check_log_dir}/${date_seven_ago}*
