#!/bin/bash

# 載入 gamerc
source ~/.gamerc

output_filename="/tmp/elftablet_combo_2db_diff_monitor.log"

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

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

ssh ctrl "psql -U postgres WebTool -c \"CREATE TABLE IF NOT EXISTS elftablet_combo_2db (elftablet_combo_id integer primary key, elftablet_combo_name text)\""
ssh ctrl "psql -U postgres WebTool -c \"CREATE TABLE IF NOT EXISTS elftablet_combo_2db_old (elftablet_combo_id integer primary key, elftablet_combo_name text)\""
ssh ctrl "psql -U postgres WebTool -c \"TRUNCATE elftablet_combo_2db_old\""
ssh ctrl "psql -U postgres WebTool -c \"INSERT INTO elftablet_combo_2db_old SELECT * FROM elftablet_combo_2db ORDER BY elftablet_combo_id\""
ssh ctrl "psql -U postgres WebTool -c \"TRUNCATE elftablet_combo_2db\""
ssh ctrl "psql -U postgres WebTool -c \"COPY elftablet_combo_2db (elftablet_combo_id,elftablet_combo_name) FROM '/tmp/elftablet_combo_2db_tw.csv' csv\""
CHECK=$(ssh ctrl "psql -U postgres WebTool -c \"COPY (SELECT COUNT(*) FROM elftablet_combo_2db_old WHERE elftablet_combo_id NOT IN (SELECT elftablet_combo_id FROM elftablet_combo_2db)) TO STDOUT;\"")
if [ "${CHECK}" -gt 0 ]; then
	ssh ctrl "psql -U postgres WebTool -c \"COPY (SELECT * FROM elftablet_combo_2db_old WHERE elftablet_combo_id NOT IN (SELECT elftablet_combo_id FROM elftablet_combo_2db) ORDER BY elftablet_combo_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 elftablet_combo_2db_diff "S_ElftabletCombo.ini 石板潛能拔除確認"
	fi
fi
