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

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

MAIN_COMMAND="Ctrl"
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")
LOG_DIR="${HOME}/www/tools/files/maintenance_action_log/${DATE}"
[ -d "${LOG_DIR}" ] || { mkdir -p "${LOG_DIR}"; sudo chmod 777 -R "${LOG_DIR}"; }

# 精準判斷執行來源
if echo "$*" | grep -q -- '--source=web'; then
    export EXEC_SOURCE="web"
fi

# 解析 key=value 類參數
for arg in "$@"; do
    case $arg in
        --exec_user=*) EXEC_USER="${arg#*=}" ;;
        --action=*) ACTION="${arg#*=}" ;;
        --sub_parameter*) SUB_PARAMETER="${arg#*=}" ;;
    esac
done

NOW=$(date +"%Y%m%dT%H%M%S")
LOG_FILE="${ACTION}_${NOW}_${EXEC_USER}.log"
HTML_OUTPUT_FILE=$(echo ${LOG_FILE} | sed 's/log/html/')

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

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} )"

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 "$HOME/www/tools/files/itemmall_web_loop/table_diff_web_loop_all.log" ]; then
            DIFF_TABLE_LISTS=$(cat $HOME/www/tools/files/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 "$HOME/www/tools/files/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

#echo ${CMD}
bash -c "${CMD}" >> ${LOG_DIR}/${LOG_FILE}
cat ${LOG_DIR}/${LOG_FILE} | aha | tee -a ${LOG_DIR}/${HTML_OUTPUT_FILE}

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

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