#!/bin/bash
source $HOME/.gamerc

### DB Info ###
#dbname=${WEBTOOL_DB_NAME}
#dbip=$(cat /etc/hosts | grep CTRL | awk -F" " '{print $1}')
#dbuser=${WEBTOOL_DB_USER}
#dbpass=${WEBTOOL_DB_PASSWORD}
### DB Info ###

output_filename="/tmp/filelist_diff_monitor.log"

cat ~/bin/*${GAME_TYPE}${COUNTRY_CODE_DISPLAY}*.txt > /tmp/FullFileList_${GAME_TYPE}${COUNTRY_CODE_DISPLAY}_all.txt
rsync -avz /tmp/FullFileList_${GAME_TYPE}${COUNTRY_CODE_DISPLAY}_all.txt CTRL:/tmp/.

ssh CTRL "psql -U postgres WebTool -c \"CREATE TABLE IF NOT EXISTS filelist_mapping_tmp ( filename TEXT, path TEXT, nfs_filename TEXT )\""
ssh CTRL "psql -U postgres WebTool -c \"CREATE TABLE IF NOT EXISTS filelist_mapping ( filename TEXT, path TEXT, nfs_filename TEXT )\""
ssh CTRL "psql -U postgres WebTool -c \"CREATE TABLE IF NOT EXISTS filelist_mapping_old ( filename TEXT, path TEXT, nfs_filename TEXT )\""
ssh CTRL "psql -U postgres WebTool -c \"TRUNCATE filelist_mapping_tmp\""
ssh CTRL "psql -U postgres WebTool -c \"COPY filelist_mapping_tmp FROM '/tmp/FullFileList_${GAME_TYPE}${COUNTRY_CODE_DISPLAY}_all.txt' CSV\""
#DIFF=$(ssh CTRL "psql -U postgres WebTool -c \"COPY (SELECT * FROM filelist_mapping_tmp FULL OUTER JOIN filelist_mapping ON filelist_mapping_tmp.filename = filelist_mapping.filename WHERE filelist_mapping_tmp.filename IS NULL OR filelist_mapping.filename IS NULL) TO STDOUT CSV\"")
DIFF=$(ssh CTRL "psql -U postgres WebTool -c \"COPY (SELECT * FROM filelist_mapping_tmp FULL OUTER JOIN filelist_mapping ON (filelist_mapping_tmp.filename,filelist_mapping.path) = (filelist_mapping.filename,filelist_mapping_tmp.path) WHERE filelist_mapping_tmp.filename IS NULL OR filelist_mapping.filename IS NULL OR (filelist_mapping.filename,filelist_mapping.path,filelist_mapping.nfs_filename) <> (filelist_mapping_tmp.filename,filelist_mapping_tmp.path,filelist_mapping_tmp.nfs_filename)) TO STDOUT CSV\"")

if [ ! -z "${DIFF}" ]; then
	ssh CTRL "psql -U postgres WebTool -c \"TRUNCATE filelist_mapping_old\""
	ssh CTRL "psql -U postgres WebTool -c \"INSERT INTO filelist_mapping_old SELECT * FROM filelist_mapping\""
	ssh CTRL "psql -U postgres WebTool -c \"TRUNCATE filelist_mapping\""
	ssh CTRL "psql -U postgres WebTool -c \"INSERT INTO filelist_mapping SELECT * FROM filelist_mapping_tmp\""

	CHECK=$(ssh CTRL "psql -U postgres WebTool -c \"COPY (SELECT COUNT(*) FROM filelist_mapping_old WHERE filename NOT IN (SELECT filename FROM filelist_mapping)) TO STDOUT;\"")
	if [ "${CHECK}" -gt 0 ]; then
		ssh CTRL "psql -U postgres WebTool -c \"COPY (SELECT * FROM filelist_mapping_old WHERE filename NOT IN (SELECT filename FROM filelist_mapping) ORDER BY filename) TO '${output_filename}' HEADER CSV\""
		rsync -avz CTRL:${output_filename} /tmp/

		LOG_SIZE=$(stat --printf="%s" ${output_filename})
		if [ "${LOG_SIZE}" -gt 0 ]; then
			send_messages WARNING filelist_diff "Client Patch (遊戲內檔案+翻譯檔) 檔案拔除確認"
		fi
	fi
fi
