#!/bin/bash

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

# 如果是非 Ctrl 架構請自行設定遊戲名稱跟國家名稱
[ -z "${GAME_TYPE}" ] && GAME_TYPE="非Ctrl架構, 自行設定"
[ -z "${COUNTRY_CODE}" ] && COUNTRY_CODE="非Ctrl架構, 自行設定"

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

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

# OUTPUT LOGFILE
LOG_OUTPUT="/tmp/deadline_monitor.log"
LOG_OUTPUT_TEST="/tmp/deadline_monitor_test.log"
LOG_OUTPUT_LIVE="/tmp/deadline_monitor_live.log"
MESSAGES_OUTPUT="/tmp/deadline_monitor_messages.log"

[ -f "${LOG_OUTPUT}" ] && rm -rf ${LOG_OUTPUT}
[ -f "${MESSAGES_OUTPUT}" ] && rm -rf ${MESSAGES_OUTPUT}

# TEST
~/bin/deadline_monitor_notice
[ -f ${LOG_OUTPUT_TEST} ] && cat ${LOG_OUTPUT_TEST} >> ${LOG_OUTPUT}

# LIVE
sendscript allms <<< "~/bin/deadline_monitor_notice"
sendscript allms -p nosave nohostname <<< "[ -f ${LOG_OUTPUT_LIVE} ] && cat ${LOG_OUTPUT_LIVE}" >> ${LOG_OUTPUT}

# If disk sizes upper to the limitation
LOG_SIZE=$(stat --printf="%s" ${LOG_OUTPUT})
DATETIME=$(date +"%Y-%m-%d %T %Z")
if [ "${LOG_SIZE}" -gt 0 ]; then
	cat ${LOG_OUTPUT} | awk -F"," '{
		if ($3 == "X")
			print $1"-"$2" TEST DEADLINE: "$4" => REMAINING: "$5" Days Only.";
		else
			print $1"-"$2" SET-"$3" DEADLINE: "$4" => REMAINING: "$5" Days Only.";
		}' > ${MESSAGES_OUTPUT}
	sed -i "1s/^/\n[WARNING: 自爆日期警示]\n${DATETIME}\n/" ${MESSAGES_OUTPUT}
	MESSAGE=$(cat ${MESSAGES_OUTPUT})
	curl -sS -X POST --data-urlencod "message=${MESSAGE}" "https://web-dev.x-legend.com/api/${ROUTE}/"
else
	if [ "$1" == "maintenance" ]; then
		# DEADLINE LOG PARSER
		if [ "${GAME_TYPE}" == "FF" ] || [ "${GAME_TYPE}" == "AK" ] || [ "${GAME_TYPE}" == "M11" ] || [ "${GAME_TYPE}" == "M12" ] || [ "$GAME_TYPE" == "G1" ] ; then
		        DEADLINE_COMMAND="$(xcat $HOME/servers*/MissionServer*/Rank*.log.* | grep ",RankUpdate:" | sort -t , -k 2 | tail -1 \
		                        | sed 's/^.*: Type=\([0-9]\+\) Group=\([0-9]\+\) Class=\([0-9]\+\),/20\1-\2-\3/g')"
		elif [ "$GAME_TYPE" == "AR" ] ; then
		        DEADLINE_COMMAND="$(xcat $HOME/servers*/MissionServer*/Family.log.* | grep "FamilyUpdate," | sort -t , -k 2 | tail -1 \
		                        | sed 's/^.*, Type=\([0-9]\+\) Group=\([0-9]\+\) Class=\([0-9]\+\)/20\1-\2-\3/g')"
		elif [ "${GAME_TYPE}" == "DJ" ] ; then
		        DEADLINE_COMMAND="$(xcat $HOME/servers*/MissionServer*/Isle.log.* | grep ",RankUpdate:" | sort -t , -k 2 | tail -1 \
		                        | sed 's/^.*:Type=\([0-9]\+\) Group=\([0-9]\+\) Class=\([0-9]\+\),/20\1-\2-\3/g')"
		else
			DEADLINE_COMMAND="$(xcat $HOME/servers*/MissionServer*/Test.log.* | grep "Dead Line" | sort -t , -k 2 | tail -1 \
					| sed 'y/\]\[/::/' | awk -F: '{print $(NF-3)}')"
		fi

		# FETCH ONE GAMEDB MACHINE IN HOSTS
		MACHINE=$(cat /etc/hosts | sed -n '/BELOW/,/ABOVE/p' | grep GAMEDB | head -n 1 | awk -F" " '{ for (i=1;i<=NF;i++) { if ($i ~/GAMEDB/) { printf "%s",$i; } } }')
		
		# GET THE DEADLINE FROM LIVE
		DEADLINE=$(ssh ${MACHINE} "echo ${DEADLINE_COMMAND}")

                # DEADLINE ERROR DATE FIX
                DEADLINE_YEAR=$(echo ${DEADLINE} | cut -d - -f1)
                DEADLINE_MONTH=$(echo ${DEADLINE} | cut -d - -f2)
                DEADLINE_DAY=$(echo ${DEADLINE} | cut -d - -f3)

                if [ "${DEADLINE_MONTH}" == "2" ] && ([ "${DEADLINE_DAY}" == "29" ] || [ "${DEADLINE_DAY}" == "30" ]); then
                        DEADLINE="${DEADLINE_YEAR}-2-28"
		elif ([ "${DEADLINE_MONTH}" == "2" ] || [ "${DEADLINE_MONTH}" == "4" ] || [ "${DEADLINE_MONTH}" == "6" ] || [ "${DEADLINE_MONTH}" == "9" ] || [ "${DEADLINE_MONTH}" == "11" ]) && ([ "${DEADLINE_DAY}" == "31" ]); then
			DEADLINE="${DEADLINE_YEAR}-${DEADLINE_MONTH}-30"
                fi
                   
		# CALCULATE THE DEADLINE REMAINING DAYS
		DEADLINE_DATE="$(date -d ${DEADLINE} +%Y-%m-%d)"
		DEADLINE_DAY_REMAINING="$(( ($(date -d ${DEADLINE} +%s)-$(date +%s)) / 86400 ))"

        	# 發送訊息
		MESSAGE=$(printf "[維護確認]\n${DATETIME}\n${GAME_TYPE_DISPLAY}-${COUNTRY_CODE_DISPLAY} => MissionServer 自爆檢查 OK!\n自爆日期: ${DEADLINE} 剩餘天數: ${DEADLINE_DAY_REMAINING}")

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