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

SCRIPT_NAME=$(basename "$0")
LOCK_FILE="/tmp/.${SCRIPT_NAME}.lock"

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

# ── 選項解析 ──────────────────────────────────────────────────────────────────
FILES_DIR=""
while [[ "${1:-}" == --* ]]; do
    case "$1" in
        --log-dir) FILES_DIR="$(dirname "$2")"; shift 2 ;;
        *) shift ;;
    esac
done

if [[ -z "$FILES_DIR" ]]; then
    FILES_DIR="${HOME}/www/tools/files"
fi
WORK_DIR="${FILES_DIR}/itemmall_web_loop"

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 "${WORK_DIR}" ] && mkdir -p ${WORK_DIR}

DIFF_TABLES=""
DIFF_TABLE_COUNTS=0
LOG_DIFF_TABLES_FILE="${WORK_DIR}/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 ${WORK_DIR}/test/; cd ${WORK_DIR}/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 ${WORK_DIR}/live/; cd ${WORK_DIR}/live; rsync -avz ACCOUNTDB:/tmp/${table}_livebackup_old_current.sql . >/dev/null 2>&1

    COUNT=$(diff ${WORK_DIR}/test/${table}_testbackup_new_current.sql ${WORK_DIR}/live/${table}_livebackup_old_current.sql | grep -E -v '\-\- Dumped ' | grep -E '^>|^<' | grep -v "GRANT ALL ON TABLE" | wc -l)

    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 -f ${LOCK_FILE}
