#!/bin/bash
[ "$2" == "" ] && exec echo "Usage: $0 [--log-dir <path>] <table name> <execute by who>"

source ~/.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
}

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

TABLE_NAME=$1
EXEC_USER=$2

DATE=$(date +"%Y%m%d")
if [[ -n "$LOG_DIR_BASE" ]]; then
    LOG_DIR="${LOG_DIR_BASE}/${DATE}"
else
    LOG_DIR="/tmp/rollback_table_from_live_to_test_log/${DATE}"
fi
[ -d "${LOG_DIR}" ] || { mkdir -p "${LOG_DIR}"; chmod 777 -R "${LOG_DIR}" 2>/dev/null; }

NOW=$(date +"%Y%m%dT%H%M%S")
LOG_FILE="${LOG_DIR}/rollback_${TABLE_NAME}_${NOW}_${EXEC_USER}.log"

NICK_NAME=$(ssh TEST "psql -U postgres Tools -c \"COPY (SELECT note FROM userinfo WHERE email = '${EXEC_USER}'||'@x-legend.com.tw') TO STDOUT;\"")
EXEC_USER_NICK_NAME="${EXEC_USER} ( ${NICK_NAME} )"

# ═════════════════════════════════════════════════════════════════════════════
main() {

$HOME/bin/send_chatbot_text_only_by_thread_tag "itemmall" "網頁工具操作" "資料表名稱 ${TABLE_NAME}, 測試機回朔正式機的資料開始, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10

# Dump test
NOW=$(date +"%Y%m%dT%H%M%S")
pg_dump -U postgres ${ACCOUNT_DB_NAME} -t ${TABLE_NAME} > ${LOG_DIR}/${TABLE_NAME}_${NOW}_${EXEC_USER}_test.sql

# Restore live
CMD="source $HOME/.gamerc; echo \"Rollback table ${TABLE_NAME}(on LIVE) -->  Table(on TEST):\" | colorize yellow black; ssh $TEST_SERVER_USER@ACCOUNTDB pg_dump --clean --attribute-inserts -t ${TABLE_NAME} $ACCOUNT_DB_NAME | grep -a -v 'SET lock_timeout' | sed '/^\\unrestrict /d' | sed '/^\\restrict /d' | psql $ACCOUNT_DB_NAME | uniq -c && echo \"Table ${TABLE_NAME} done.\" | colorize green || echo \"Table ${TABLE_NAME} failed.\" | colorize red; online_reload_cgi_test ${TABLE_NAME};"

bash -c "${CMD}"

# Dump live
NOW=$(date +"%Y%m%dT%H%M%S")
pg_dump -U postgres ${ACCOUNT_DB_NAME} -t ${TABLE_NAME} > ${LOG_DIR}/${TABLE_NAME}_${NOW}_${EXEC_USER}_live.sql

$HOME/bin/send_chatbot_text_only_by_thread_tag "itemmall" "網頁工具操作" "資料表名稱 ${TABLE_NAME}, 測試機回朔正式機的資料結束, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10

$HOME/bin/send_chatbot_text_only_by_thread_tag "itemmall" "網頁工具操作" "資料表名稱 ${TABLE_NAME}, 差異確認 ${TOOLS_WEBSITE_URL}/files/check_table_diff_between_test_and_live.php?table_name=${TABLE_NAME}" minute 10

} # end main

# ── 執行 main，透過 tee 同時輸出到 stdout 和 log 檔 ─────────────────────────
main 2>&1 | tee -a "$LOG_FILE"
RC=${PIPESTATUS[0]}

[ -f "${LOCK_FILE}" ] && rm -f ${LOCK_FILE}
exit $RC
