#!/bin/bash

source ~/.gamerc

PREV_TEN_MINUTES_DATE="$(date -d "-10 minutes" +"%Y/%m/%d %H:%M"|head -c 15)"

get_os() {
	local os=$(cat /etc/os-release | egrep "^ID=" | sed 's/ID=//;s/"//g')
	echo ${os}
}

get_internal_ip() {
	local os=$(get_os)
	if [ "${os}" == "centos" ]; then
		local internal_ip=$(/sbin/ifconfig eth0 | grep 'inet' | grep -v 'inet6' | awk -F' ' '{print $2}' | awk '{print $1}')
	elif [ "${os}" == "debian" ]; then
		local internal_ip=$(/sbin/ifconfig ens4 | grep 'inet' | grep -v 'inet6' | awk -F' ' '{print $2}' | awk '{print $1}')
	fi
	echo ${internal_ip}
}

get_environment() {
	local internal_ip=$(get_internal_ip)
	local checked=$(sed -n '/PLEASE DO NOT CHANGE THE FILE/,/DO NOT CHANGE THE SERVER NAMES ABOVE/p' /etc/hosts | egrep "${internal_ip} ")
	if [ -z "${checked}" ]; then
		local environment="TEST"
	else
		local environment="LIVE"
	fi
	echo ${environment}
}

get_machine() {
	local internal_ip=$(get_internal_ip)
	local checked=$(grep "${internal_ip} " /etc/hosts | awk -F" " '{print $2}')
	if [ -z "${checked}" ]; then
		local machine="Unknown"
	else
		local machine=${checked}
	fi
	echo ${machine}
}

get_set_by_server() {
	local server="$1"
	local internal_ip=$(get_internal_ip)
	local environment=$(get_environment)
	local machine=$(get_machine)
	case ${server} in
		GameDBS*|MissionS*|RankS*|ChatS*)
			set_id=$(echo ${server} | sed 's/GameDBServer//;s/MissionServer//;s/RankServer//;s/ChatServer//')
			;;
		WorldS*|ZoneS*)
			set_id_pre=$(echo ${server} | sed 's/WorldServer//;s/ZoneServer//')
			set_id=${set_id_pre::-2}
			;;
        AccountDBS*)
            sed_id=1
			;;
		*)
			set_id="Unknown"
			;;
	esac
	echo ${set_id}
}

get_short_name_by_server() {
	local server="$1"
	case ${server} in
		GameDBS*)
			short_name=$(echo ${server} | sed 's/GameDBServer/GDS/')
			;;
		MissionS*)
			short_name=$(echo ${server} | sed 's/MissionServer/MS/')
			;;
		WorldS*|ZoneS*)
			short_name=$(echo ${server} | sed 's/WorldServer/WS/;s/ZoneServer/ZS/')
			;;
		RankS*)
			short_name=$(echo ${server} | sed 's/RankServer/RANKS/')
			;;
		ChatS*)
			short_name=$(echo ${server} | sed 's/ChatServer/CHATS/')
			;;
        AccountDBS*)
            short_name="ACCTDBS"
			;;
		*)
			short_name="Unknown"
	esac
	echo ${short_name}
}

for ServerDir in ~/servers*/{AccountDBS,GameDBS,MissionS,WorldS,RankS,ChatS}*; do
#for ServerDir in ~/servers*/{GameDBS,MissionS,WorldS,RankS}*; do
	if [ -d ${ServerDir} ]; then
		Server=$(basename ${ServerDir})
		internal_ip=$(get_internal_ip)
		environment=$(get_environment)
		machine=$(get_machine)
		sid=$(get_set_by_server ${Server})
		ssn=$(get_short_name_by_server ${Server})

		cd ${ServerDir}
		current_dir=$(pwd)
		echo "${current_dir}"
		rm -rf /tmp/${ssn}_SQLAssert.log

		pattern="SQLAss*"
		if find . -maxdepth 1 -mindepth 1 -type f -name "$pattern" | grep -q .; then
			echo "${ServerDir} => ${Server} 1"
			search_info=$(grep -h "^[ 0-9]\+,$PREV_TEN_MINUTES_DATE" $(ls -tr SQLAss*log* 2> /dev/null|tail -2)|sed "s/'/''/g")
			echo "grep -h \"^[ 0-9]\+,$PREV_TEN_MINUTES_DATE\" $(ls -tr SQLAss*log* 2> /dev/null|tail -2)|sed \"s/'/''/g"\"
			if [ -z "${search_info}" ]; then
				echo "${ServerDir} => ${Server} 1 0"
				touch /tmp/${ssn}_SQLAssert.log		
			else
				echo "${ServerDir} => ${Server} 1 1"
				grep -h "^[ 0-9]\+,$PREV_TEN_MINUTES_DATE" $(ls -tr SQLAss*log* 2> /dev/null|tail -2) | sed "s/'/''/g" | head -n 1 | perl -ne 'print "$2,$3,...\n" if /((\d+),(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}),\[\*\*\*ASSERT\*\*\*\]\[(.+))/' > /tmp/${ssn}_SQLAssert.log
				FILE_DATE=$(echo $PREV_TEN_MINUTES_DATE | awk -F" " '{print $1}' | sed 's|/||g')
				LOCAL_DIR="/tmp/AssertLog/${environment}/${FILE_DATE}/${ssn}"
				REMOTE_DIR="$HOME/www/download/AssertLog/${environment}/${FILE_DATE}/${ssn}"
				if [ ! -d "${LOCAL_DIR}" ]; then
					mkdir -p ${LOCAL_DIR}
				fi
				grep -h "^[ 0-9]\+,$PREV_TEN_MINUTES_DATE" $(ls -tr SQLAss*log* 2> /dev/null|tail -2) | sed "s/'/''/g" | perl -ne 'print "$1\n\n" if /((\d+),(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}),\[\*\*\*ASSERT\*\*\*\]\[(.+))/' >> ${LOCAL_DIR}/${ssn}_SQLAssert.log.${FILE_DATE}
				#rsync /dev/null TEST:${REMOTE_DIR}/
				ssh TEST "if [ ! -d "${REMOTE_DIR}" ]; then mkdir -p ${REMOTE_DIR}; fi"
				rsync -avz ${LOCAL_DIR}/${ssn}_SQLAssert.log.${FILE_DATE} TEST:${REMOTE_DIR}/.
			fi
		else
			echo "${ServerDir} => ${Server} 0"
			touch /tmp/${ssn}_SQLAssert.log		
		fi

		# 如果輸出的 LOG 檔案有內容, 則發送訊息到 API, 請機器人送群組
		LOG_SIZE=$(stat --printf="%s" /tmp/${ssn}_SQLAssert.log)

		# 發送當下時間
		DATETIME=$(date +"%Y-%m-%d %T %Z")

		if [ "${LOG_SIZE}" -gt 0 ]; then
			FILE_DATE=$(echo $PREV_TEN_MINUTES_DATE | awk -F" " '{print $1}' | sed 's|/||g')
			OUTPUT_ASSERT_LINK="http[:]\/\/${TEST_SERVER_GLOBAL_IP}\/download/AssertLog\/${environment}\/${FILE_DATE}\/${ssn}\/${ssn}_SQLAssert.log.${FILE_DATE}";
			DATA_COUNT=$(cat /tmp/AssertLog/${environment}/${FILE_DATE}/${ssn}/${ssn}_SQLAssert.log.${FILE_DATE} | egrep "$PREV_TEN_MINUTES_DATE" | wc -l)
			sed -i "1s/^/[ERROR] SQL Assert Log happened. ( ${DATA_COUNT} )\n${DATETIME}\n[${environment}] ${machine} ( ${internal_ip} )\nSET${sid} ${ssn}\n/" /tmp/${ssn}_SQLAssert.log
			sed -i "\$a\ ${OUTPUT_ASSERT_LINK}" /tmp/${ssn}_SQLAssert.log
			MESSAGE=$(cat /tmp/${ssn}_SQLAssert.log)

			# 送出資訊給 Google Chat Webhook
			#GOOGLE_CHAT_WEBHOOK_URL="https://chat.googleapis.com/v1/spaces/AAAA7hXAOCM/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=YupvEeDhNq2aF9ldCAf8TeJw8kmafVAXpj3xJWIzRGw%3D"
			if [[ ! ${Server} =~ ^ChatS* ]]; then
				curl -sS -X POST -H 'Content-Type: application/json' $GOOGLE_CHAT_WEBHOOK_URL -d "{\"text\": \"${MESSAGE}\"}"
			fi
		fi
	fi
done

