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

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

	# 發送訊息
        #MESSAGE=$(printf "<p style='font-family:Courier; color:Red; font-size: 20px;'>[CRASH NOTIFY]\n ${GAME_TYPE_DISPLAY}-${COUNTRY_CODE_DISPLAY} (${DATETIME})\n INTERNAL TEST</p>")
        #MESSAGE=$(printf "<users/all>\n<font color='red'>*[CRASH NOTIFY]*\n *${GAME_TYPE_DISPLAY}-${COUNTRY_CODE_DISPLAY}* *(${DATETIME})*\n *INTERNAL TEST*</font>")

	CRASH_DATA="ZoneServer303,2022-06-09 23:51:45.052228+08"
MESSAGE=$(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}" "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 "{\"text\": \"${MESSAGE}\"}"
        curl -sS -X POST -H 'Content-Type: application/json' $GOOGLE_CHAT_WEBHOOK_URL -d "${MESSAGE}"
#fi
