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

SCRIPT_NAME=$(basename "$0")
LOCK_FILE="${HOME}/www/tools/files/.${SCRIPT_NAME}.lock"

exec 200>"${LOCK_FILE}"
flock -n 200 || {
        echo "${SCRIPT_NAME} is running. Exiting."
    exit 1
}

LOOP_ALL_TABLES=$(psql -U postgres Tools -c "COPY (SELECT table_name_db FROM web_table_mapping WHERE table_name_db !~ 'x_test') TO STDOUT;")
echo ${LOOP_ALL_TABLES}

[ ! -d "${HOME}/www/tools/files/itemmall_web_loop" ] && mkdir -p ${HOME}/www/tools/files/itemmall_web_loop

DIFF_TABLES=""
DIFF_TABLE_COUNTS=0
LOG_DIFF_TABLES_FILE="${HOME}/www/tools/files/itemmall_web_loop/table_diff_web_loop_all.log"
[ -f "${LOG_DIFF_TABLES_FILE}" ] && rm -rf ${LOG_DIFF_TABLES_FILE}

for table in ${LOOP_ALL_TABLES}; do
    mkdir -p ${HOME}/www/tools/files/itemmall_web_loop/test/; cd ${HOME}/www/tools/files/itemmall_web_loop/test; echo "Dump ${table} on TEST ..."; pg_dump -U postgres ${GAME_TYPE}Account -t ${table} | sed '/^\\unrestrict /d' | sed '/^\\restrict /d' | sed '/^$/d' | sort > ${table}_testbackup_new_current.sql

    ssh ACCOUNTDB "echo 'Dump ${table} on LIVE ...'; pg_dump -U postgres ${GAME_TYPE}Account -t ${table} | sed '/^\\\\unrestrict /d' | sed '/^\\\\restrict /d' | sed '/^$/d' | sort > /tmp/${table}_livebackup_old_current.sql"
    mkdir -p ${HOME}/www/tools/files/itemmall_web_loop/live/; cd ${HOME}/www/tools/files/itemmall_web_loop/live; rsync -avz ACCOUNTDB:/tmp/${table}_livebackup_old_current.sql . >/dev/null 2>&1

    #CHECK=$(diff ${HOME}/www/tools/files/itemmall_web_loop/test/${table}_testbackup_new_current.sql ${HOME}/www/tools/files/itemmall_web_loop/live/${table}_livebackup_old_current.sql | grep -E -v 'Dumped|---' | awk -F'[c,]' '$1 == $3 && $2 == $4')
    COUNT=$(diff ${HOME}/www/tools/files/itemmall_web_loop/test/${table}_testbackup_new_current.sql ${HOME}/www/tools/files/itemmall_web_loop/live/${table}_livebackup_old_current.sql | grep -E -v '\-\- Dumped ' | grep -E '^>|^<' | wc -l)

    #if [[ -z "${CHECK}" ]]; then
    if [ "${COUNT}" -gt 0 ]; then
        DIFF_TABLES="${DIFF_TABLES} ${table}"
        DIFF_TABLE_COUNTS=$((DIFF_TABLE_COUNTS + 1))
    fi
done

if [ "${DIFF_TABLE_COUNTS}" -gt 0 ]; then
    echo ${DIFF_TABLES} | tee -a ${LOG_DIFF_TABLES_FILE}
    chmod 777 ${LOG_DIFF_TABLES_FILE}
fi

[ -f "${LOCK_FILE}" ] && rm -rf ${LOCK_FILE}
