#!/bin/bash

###### 檔案資訊 ######
#
# 檔名: send_crash_notify
#
# 功能: 將 Game Servers 當機的資訊,
#       發送至各版本的 Skpe 群組
#
# 版更:
# v1: 基本款
#
###### 檔案資訊 ######

# 如果 gamerc 存在, 則載入它
[ -f ~/.gamerc ] && source ~/.gamerc

# 如果有需要自訂或是修改顯示的遊戲與國家名稱, 請自行修正
[ "${GAME_TYPE}" == "AK" ] && GAME_TYPE_DISPLAY="M7" || GAME_TYPE_DISPLAY=${GAME_TYPE}

# 撈取近 5 分鐘內的 crashlog
CRASH_DATA=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "copy (select process as \"ServerName\",regdate as \"Crash_DateTime\" from crashlog where regdate between now() - interval '5 min' and now()) to stdout with csv header" | grep -v 'ServerName,Crash_DateTime')

# API ROUTE 設定, 如果需要可自行修改
[ ! -z "${COUNTRY_CODE_DISPLAY}" ] && ROUTE=$(echo ${GAME_TYPE}-${COUNTRY_CODE_DISPLAY}) || ROUTE=$(echo ${GAME_TYPE}-${COUNTRY_CODE})
[ ! -z "${COUNTRY_CODE_DISPLAY}" ] && COUNTRY_CODE_DISPLAY=$(echo ${COUNTRY_CODE_DISPLAY}) || COUNTRY_CODE_DISPLAY=$(echo ${COUNTRY_CODE})

# 如果有撈取到當機紀錄, 則發出通知
if [ "${CRASH_DATA}" != "" ]; then
	# 發送當下時間
	DATETIME=$(date +"%Y-%m-%d %T %Z")

	# 發送訊息
        MESSAGE=$(printf "[CRASH NOTIFY]\n ${GAME_TYPE_DISPLAY}-${COUNTRY_CODE_DISPLAY} (${DATETIME})\n ${CRASH_DATA}")

	# 送出資訊給 API
        curl -sS -X POST --data-urlencod "message=${MESSAGE}" "https://web-dev.x-legend.com/api/${ROUTE}/"
fi
