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

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 ;;
        --source=*) EXEC_SOURCE="${1#*=}"; shift ;;
        --exec_user=*) EXEC_USER="${1#*=}"; shift ;;
        --action=*) ACTION="${1#*=}"; shift ;;
        --sub_parameter=*) SUB_PARAMETER="${1#*=}"; shift ;;
        --sub_parameter) SUB_PARAMETER=""; shift ;;
        *) shift ;;
    esac
done

MAIN_COMMAND="Ctrl"
EXEC_SOURCE="${EXEC_SOURCE:-terminal}"
PATCH_VERSION=$(ls -hld ~/patch/20* | awk -F" " '{print $(NF)}' | awk -F"/" '{print $(NF)}' | tail -n 1)

DATE=$(date +"%Y%m%d")
if [[ -n "$LOG_DIR_BASE" ]]; then
    LOG_DIR="${LOG_DIR_BASE}/${DATE}"
    FILES_DIR="$(dirname "$LOG_DIR_BASE")"
else
    LOG_DIR="/tmp/maintenance_action_log/${DATE}"
    FILES_DIR="${HOME}/www/tools/files"
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}/${ACTION}_${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} )"

SUB_COMMAND=$(psql -U postgres Tools -c "COPY (SELECT sub_command_name FROM web_maintenance_procedure_mapping WHERE procedure_name = '${ACTION}') TO STDOUT;")

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

case ${ACTION} in
    status)
        NOW_DATETIME=$(date +"%Y-%m-%d %H:%M:%S")
        CMD="echo \"NOW DATETIME: ${NOW_DATETIME}+08\";
            sendscript allall nosave <<< \"cat /proc/loadavg;ps -Ao pid,lstart,pcpu,s,cmd f|grep \\\"[A-Za-z]\+Server\\\"|grep -v SKServer\"
        "
        ;;
    stop_monitor)
        CMD="echo yes | ${MAIN_COMMAND} StopMonitor;"
        ;;
    lg_iptables_state)
        NOW_DATETIME=$(date +"%Y-%m-%d %H:%M:%S")
        CMD="${HOME}/bin/check_live_iptables"
        ;;
    lg_block)
        CMD="echo yes | ${MAIN_COMMAND} LGBlock;"
        ;;
    lg_allow)
        CMD="echo yes | ${MAIN_COMMAND} LGAllow;"
        ;;
    lg_stop)
        CMD="echo yes | ${MAIN_COMMAND} LGStop;"
        ;;
    lg_start)
        CMD="echo yes | ${MAIN_COMMAND} LGStart;"
        ;;
    lg_restart)
        CMD="echo yes | ${MAIN_COMMAND} LGRestart;"
        ;;
    live_stop)
        CMD="echo yes | ${MAIN_COMMAND} LIVEStop;"
        ;;
    live_stop_fast)
        CMD="echo yes | ${MAIN_COMMAND} LIVEStop ${SUB_COMMAND};"
        ;;
    live_start)
        CMD="echo yes | ${MAIN_COMMAND} LIVEStart;"
        ;;
    live_start_fast)
        CMD="echo yes | ${MAIN_COMMAND} LIVEStart ${SUB_COMMAND};"
        ;;
    dbbackup)
        CMD="echo yes | ${MAIN_COMMAND} DBbackup;"
        ;;
    server_sync_pre)
        CMD="echo yes | ${MAIN_COMMAND} gmsync_pre;"
        ;;
    server_sync_pre_check)
        CMD="echo yes | ${MAIN_COMMAND} gmsync_pre ${SUB_COMMAND};"
        ;;
    server_sync)
        CMD="echo yes | ${MAIN_COMMAND} gmsync;"
        ;;
    server_sync_local)
        CMD="echo yes | ${MAIN_COMMAND} gmsync ${SUB_COMMAND};"
        ;;
    dbpatch)
        CMD="echo yes | ${MAIN_COMMAND} dbpatch;"
        ;;
    dbpatch_fast)
        CMD="echo yes | ${MAIN_COMMAND} dbpatch ${SUB_COMMAND};"
        ;;
    client_sync)
        CMD="echo yes | ${MAIN_COMMAND} NEW_CDN_prepatch_sync ${SUB_COMMAND};"
        ;;
    translate_sync)
        CMD="echo yes | ${MAIN_COMMAND} NEW_CDN_prepatch_sync ${SUB_COMMAND};"
        ;;
    maintenance_sync)
        CMD="echo yes | ${MAIN_COMMAND} NEW_CDN_prepatch_sync ${SUB_COMMAND};"
        ;;
    notice_sync)
        CMD="echo yes | ${MAIN_COMMAND} NEW_CDN_prepatch_sync ${SUB_COMMAND};"
        ;;
    setup_sync)
        CMD="echo yes | ${MAIN_COMMAND} NEW_CDN_prepatch_sync ${SUB_COMMAND};"
        ;;
    force_sync)
        CMD="echo yes | ${MAIN_COMMAND} NEW_CDN_prepatch_sync ${SUB_COMMAND};"
        ;;
    h5_cdn_sync)
        CMD="echo yes | ${MAIN_COMMAND} H5_CDN_prepatch_sync;"
        ;;
    itemmall)
        if [[ -z "${SUB_PARAMETER}" ]]; then
            CMD="echo yes | ${MAIN_COMMAND} itemmall;"
        else
            CMD="echo yes | ${MAIN_COMMAND} itemmall ${SUB_PARAMETER};"
        fi
        ;;
    itemmall_diff)
        $HOME/bin/table_diff_web_loop_all
        if [ -f "${FILES_DIR}/itemmall_web_loop/table_diff_web_loop_all.log" ]; then
            DIFF_TABLE_LISTS=$(cat ${FILES_DIR}/itemmall_web_loop/table_diff_web_loop_all.log)
            CMD=""
            for table in ${DIFF_TABLE_LISTS}; do
                CMD="${CMD} echo yes | ${MAIN_COMMAND} itemmall ${table};"
            done
            ACTION="itemmall"
        fi
        ;;
    healthy_check)
        CMD="echo yes | ${MAIN_COMMAND} HealthyCheck;"
        ;;
    one-stop_services)
        CMD="
            ~/bin/send_chatbot_text_only \"正式機維護流程\" \"全部一條龍開始\";
            echo yes | ${MAIN_COMMAND} LGBlock;
            echo yes | ${MAIN_COMMAND} LIVEStop;
            echo yes | ${MAIN_COMMAND} DBbackup;
            echo yes | ${MAIN_COMMAND} gmsync;
            echo yes | ${MAIN_COMMAND} dbpatch;
            echo yes | ${MAIN_COMMAND} itemmall;
            echo yes | ${MAIN_COMMAND} NEW_CDN_prepatch_sync CLIENT;
            echo yes | ${MAIN_COMMAND} HealthyCheck;
            echo yes | ${MAIN_COMMAND} LIVEStart;
            ~/bin/send_chatbot_text_only \"正式機維護流程\" \"全部一條龍結束!\";
        "
        ;;
    *)
        echo "Unknown command for maintenance"
        ;;
esac

if [ "${ACTION}" != "status" -a "${ACTION}" != "lg_iptables_state" ]; then
    PROCEDURE_NAME_CHT=$(psql -U postgres Tools -c "COPY (SELECT procedure_name_cht FROM web_maintenance_procedure_mapping WHERE procedure_name = '${ACTION}') TO STDOUT;")
    $HOME/bin/send_chatbot_text_only_by_thread_tag "${ACTION}" "網頁工具操作" "正式機維護腳本 ${PROCEDURE_NAME_CHT} 開始, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10
fi

if [ "${ACTION}" == "itemmall_diff" ]; then
    if [ ! -f "${FILES_DIR}/itemmall_web_loop/table_diff_web_loop_all.log" ]; then
        $HOME/bin/send_chatbot_text_only_by_thread_tag "itemmall_diff" "網頁工具操作" "資料表沒有差異, 無須更新. 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10
    fi
fi

bash -c "${CMD}"

if [ "${ACTION}" != "status" -a "${ACTION}" != "lg_iptables_state" ]; then
    PROCEDURE_NAME_CHT=$(psql -U postgres Tools -c "COPY (SELECT procedure_name_cht FROM web_maintenance_procedure_mapping WHERE procedure_name = '${ACTION}') TO STDOUT;")
    $HOME/bin/send_chatbot_text_only_by_thread_tag "${ACTION}" "網頁工具操作" "正式機維護腳本 ${PROCEDURE_NAME_CHT} 結束, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10
fi

} # 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
