#!/bin/bash

# 该脚本从数据库每5分钟读取一次开服信息，并根据开服时间自动安装节点以及开服
# crontab -e 里面配置
#*/5 * * * *  cd /data/server && sh ./auto_open_new.sh > /data/server/open_log.log 2>&1

# 数据库配置
DB_HOST="127.0.0.1"
DB_PORT="3306"
DB_USER="root"
DB_PASS="xxxx"
DB_NAME="sdk"
TB_NAME="game_server"

# 服务路径
SRV_SOURCE="/data/server"

# 当前时间戳
CUR_SEC=$(date '+%s')
CUR_SEC_L=$((CUR_SEC - 600))

# SQL 查询语句
SELECT_SQL="SELECT zone_id, open_time, srv_status, db_name FROM ${TB_NAME}"

# 获取查询结果
RESULT=($(mysql -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASS} -D${DB_NAME} -N -e "${SELECT_SQL}"))

# 检查是否有结果
if [ ${#RESULT[@]} -eq 0 ]; then
  echo "No data found in the database."
  exit 1
fi

# 处理查询结果
for (( i=0; i<${#RESULT[@]}; i+=4 )); do
  ZONE_ID=${RESULT[i]}
  OPEN_TIME=${RESULT[i+1]}
  SRV_STATUS=${RESULT[i+2]}
  DB_NAME=${RESULT[i+3]}

  # 将开服时间转化为时间戳
  OPEN_TIME_SEC=$(date -d "${OPEN_TIME}" '+%s')
  OPEN_TIME_BEFORE_10M=$((OPEN_TIME_SEC - 600))
  OPEN_TIME_AFTER_10M=$((OPEN_TIME_SEC + 600))

  # 判断是否在开服时间前后10分钟内
  if [ ${OPEN_TIME_BEFORE_10M} -lt ${CUR_SEC} ] && [ ${OPEN_TIME_AFTER_10M} -gt ${CUR_SEC} ]; then
    cd ${SRV_SOURCE}
    sh srv.sh srv_install ${ZONE_ID}
    echo "$(date) 开服成功 ZONE_ID=${ZONE_ID} OPEN_TIME=${OPEN_TIME} CUR_SEC=${CUR_SEC}" >> test.txt
  elif [ ${CUR_SEC} -gt ${OPEN_TIME_AFTER_10M} ] && [ ${SRV_STATUS} -ne 1 ]; then
    cd ${SRV_SOURCE}
    echo "$(date) 检测 ZONE_ID=${ZONE_ID}" >> test.txt
  else
    echo "$(date) 未到开服时间标准 ZONE_ID=${ZONE_ID}" >> test.txt
  fi
done

echo "自动脚本结束" >> test.txt







