#!/bin/bash

# 載入 gamerc
source ~/.gamerc

output_filename="/tmp/node2db_diff_monitor.log"

## 台版場景ID與名稱對應
cat ${WORKING_DIRECTORY}/common-${SOURCE_OF_SYNC_TO_LIVE}/Data/db/S_Node.ini | egrep '^[0-9].*' | awk -F"|" '{print $1","$2}' > /tmp/node2db_tw.csv

# 台版場景對應 CSV 同步到 Ctrl 機, 並更新到 node2db
scp /tmp/node2db_tw.csv ctrl:/tmp

ssh ctrl "psql -U postgres WebTool -c \"CREATE TABLE IF NOT EXISTS node2db (node_id integer primary key, nodename text)\""
ssh ctrl "psql -U postgres WebTool -c \"CREATE TABLE IF NOT EXISTS node2db_old (node_id integer primary key, nodename text)\""
ssh ctrl "psql -U postgres WebTool -c \"TRUNCATE node2db_old\""
ssh ctrl "psql -U postgres WebTool -c \"INSERT INTO node2db_old SELECT * FROM node2db ORDER BY node_id\""
ssh ctrl "psql -U postgres WebTool -c \"TRUNCATE node2db\""
ssh ctrl "psql -U postgres WebTool -c \"COPY node2db (node_id,nodename) FROM '/tmp/node2db_tw.csv' csv\""
CHECK=$(ssh ctrl "psql -U postgres WebTool -c \"COPY (SELECT COUNT(*) FROM node2db_old WHERE node_id NOT IN (SELECT node_id FROM node2db)) TO STDOUT;\"")
if [ "${CHECK}" -gt 0 ]; then
	ssh ctrl "psql -U postgres WebTool -c \"COPY (SELECT * FROM node2db_old WHERE node_id NOT IN (SELECT node_id FROM node2db) ORDER BY node_id) 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 node2db_diff "S_Node.ini 地圖拔除確認"
	fi
fi
