#!/bin/bash

source ~/.gamerc

COREDUMP_ROOT_DIRECTORY="${WORKING_DIRECTORY}/www/core"
COREDUMP_OLD_DIRECTORY="${WORKING_DIRECTORY}/www/core/live_core_dump"
#TIME_INTERVAL="5"
#CHECK_TIME_INTERVAL=$(date --date="${TIME_INTERVAL} minutes ago" +'%Y-%m-%d %H:%M') 
TEST_SERVER_IP=${TEST_SERVER_GLOBAL_IP}
PATCH_SERVER_IP=${REMOTE_PATCH_SERVER}
REMOTE_DIRECTORY_ON_PATCH="upload/${COUNTRY_CODE}"
TODAY=$(date +'%Y%m%d')
COREDUMP_UPLOAD_RECORD="${COREDUMP_ROOT_DIRECTORY}/.live_core_dump_upload_record"
CTRL_DB_WEBTOOL_PASSWORD="eU-n#48Ku(_X!SMk~Z9H3)";


cd ${COREDUMP_ROOT_DIRECTORY}

COUNT=$(ls ${GAME_TYPE}-${COUNTRY_CODE}-*.core_dump.*.tar.gz | wc -l)

if [ ${COUNT} -gt 0 ]; then

	if [ ! -d ${COREDUMP_OLD_DIRECTORY}/${TODAY} ] ; then
		mkdir -p ${COREDUMP_OLD_DIRECTORY}/${TODAY}
	fi

	for coredump in $(ls ${GAME_TYPE}-${COUNTRY_CODE}-*.core_dump.*.tar.gz); do
		SERVER_NAME=$(echo ${coredump} | awk -F"." '{print $1}' | cut -d "-" -f3)
		SET_ID=$(server_name_to_set_id ${SERVER_NAME})
		[ "${SET_ID}" == "Common" ] && QUERY_SET_ID="1" || QUERY_SET_ID="${SET_ID}"
		TIMEZONE=$(ssh CTRL "psql -U postgres WebTool -c \"COPY (SELECT timezone FROM db_setup WHERE set_id = ${SET_ID}) TO STDOUT;\"")
		YEAR=$(echo ${coredump} | awk -F"." '{print $3}' | cut -c1-4)
		MONTH=$(echo ${coredump} | awk -F"." '{print $3}' | cut -c5-6)
		DAY=$(echo ${coredump} | awk -F"." '{print $3}' | cut -c7-8)
		HOUR=$(echo ${coredump} | awk -F"." '{print $3}' | cut -c10-11)
		MINUTE=$(echo ${coredump} | awk -F"." '{print $3}' | cut -c12-13)
		SECOND=$(echo ${coredump} | awk -F"." '{print $3}' | cut -c14-15)		
		DATETIME="${YEAR}-${MONTH}-${DAY} ${HOUR}:${MINUTE}:${SECOND}${TIMEZONE}"

		lftp -e "put ${coredump} ; quit" http://${PATCH_SERVER_IP}/${REMOTE_DIRECTORY_ON_PATCH}

		NOW=$(date +'%Y-%m-%d %H:%M:%S')
		echo "${NOW},http://${TEST_SERVER_IP}/core/live_core_dump/${TODAY}/${coredump},/var/www/html/upload/${COUNTRY_CODE}/${coredump}" >> ${COREDUMP_UPLOAD_RECORD}

		CTRL_EXISTSORNOT=$(cat /etc/hosts | grep -i CTRL)
		if [[ -z ${CTRL_EXISTSORNOT} ]]; then
			psql -U postgres WebTool -c "INSERT INTO crashlog_precisely_v3 (set_id, server_name, realdate, regdate, log_date, core_dump_url, upload_site) values (${SET_ID}, '${SERVER_NAME}', '${DATETIME}', '${DATETIME}', NOW(), '<A HREF=\"http://${TEST_SERVER_IP}/core/live_core_dump/${TODAY}/${coredump}\">/upload/${COUNTRY_CODE}/${coredump}</a>', 'upload/${COUNTRY_CODE}/${coredump}');"
		else
			PGPASSWORD=${CTRL_DB_WEBTOOL_PASSWORD} /usr/bin/psql -U webtool -h CTRL WebTool -c "INSERT INTO crashlog_precisely_v3 (set_id, server_name, realdate, regdate, log_date, core_dump_url, upload_site) values (${SET_ID}, '${SERVER_NAME}', '${DATETIME}', '${DATETIME}', NOW(), '<A HREF=\"http://${TEST_SERVER_IP}/core/live_core_dump/${TODAY}/${coredump}\">/upload/${COUNTRY_CODE}/${coredump}</a>', 'upload/${COUNTRY_CODE}/${coredump}');"
		fi

		mv ${coredump} ${COREDUMP_OLD_DIRECTORY}/${TODAY}
	done
fi
