#!/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}

# 撈取時間分鐘變數
MINUTES="5"
TIMEDIFF_MINUTES="15"

# 撈取近 ${MINUTES} 分鐘內的 crashlog
CRASH_DATA_CHECK=$(psql -U postgres WebTool -c "COPY (SELECT set_id AS \"SetID\", server_name AS \"SName\", realdate AS \"CS_DateTime\", regdate AS \"CS_DateTime_+8\", upload_site AS \"Upload_Site\" FROM crashlog_precisely_v3 WHERE (log_date BETWEEN NOW() - INTERVAL '${MINUTES} min' AND NOW()) AND (EXTRACT(EPOCH FROM (log_date - regdate)) / 60 <= ${TIMEDIFF_MINUTES})) TO STDOUT WITH CSV HEADER" | egrep -v "SetID") 
CRASH_DATA=$(psql -U postgres WebTool -c "COPY (SELECT set_id AS \"SetID\", server_name AS \"SName\", realdate AS \"CS_DateTime\", regdate AS \"CS_DateTime_+8\", upload_site AS \"Upload_Site\" FROM crashlog_precisely_v3 WHERE (log_date BETWEEN NOW() - INTERVAL '${MINUTES} min' AND NOW()) AND (EXTRACT(EPOCH FROM (log_date - regdate)) / 60 <= ${TIMEDIFF_MINUTES})) TO STDOUT WITH CSV HEADER")

# 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})
#GOOGLE_CHAT_WEBHOOK_URL="https://chat.googleapis.com/v1/spaces/AAAA7hXAOCM/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=YupvEeDhNq2aF9ldCAf8TeJw8kmafVAXpj3xJWIzRGw%3D"

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

	# 發送訊息
        MESSAGE_SKYPE=$(printf "[CRASH NOTIFY]\n ${GAME_TYPE_DISPLAY}-${COUNTRY_CODE_DISPLAY} (${DATETIME})\n ${CRASH_DATA}")
MESSAGE_GOOGLE_CHAT=$(printf "
{
  \"cards\": [
    {
      \"sections\": [
        {
          \"widgets\": [
            {
              \"image\": {
                \"imageUrl\": \"https://dlg.x-legend.tw/apk/crash_full.png\",
              },
            },
            {
              \"textParagraph\": {
                \"text\": \"<b>[CRASH NOTIFY]</b><br><b>${GAME_TYPE_DISPLAY}-${COUNTRY_CODE_DISPLAY}</b> <b><font color='#008000'>(${DATETIME})</font></b><br><b><font color='#ff0000'>${CRASH_DATA}</font></b>\"
              }
            },
          ]
        }
      ]
    }
  ]
}
")

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

        # 送出資訊給 Google Chat Webhook
        curl -sS -X POST -H 'Content-Type: application/json' $GOOGLE_CHAT_WEBHOOK_URL -d "${MESSAGE_GOOGLE_CHAT}"
fi
