#!/bin/bash

EXEC_USER="$1"
MANAGE_DIR="$2"
NICK_NAME="$3"   # caller (s_rootcmds_manage.php) 查 userinfo.note 後傳入
USER=$(whoami)

# 依專案別尾綴（與 sibling s_rootcmds_syncToLive/verify_servers 同慣例）；讀不到 GAME_TYPE 預設 n1，N1 行為不變
source "$HOME/.gamerc" 2>/dev/null || true
LOWER_GAME_TYPE=$(echo "${GAME_TYPE:-N1}" | tr 'A-Z' 'a-z')

if [ -z "${MANAGE_DIR}" ]; then
    MANAGE_DIR="/home/${USER}/www/tools/files/s_rootcmds_manage"
fi

EXEC_USER_NICK_NAME="${EXEC_USER} ( ${NICK_NAME} )"

$HOME/bin/send_chatbot_text_only_by_thread_tag "modify_s_rootcmds" "網頁工具操作" "測試機 S_RootCmds.ini 同步檢查開始, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10

[ -f "${MANAGE_DIR}/to_log.txt" ] && rm -rf "${MANAGE_DIR}/to_log.txt"

MD5_TEST_ORIG=$(md5sum /home/${USER}/bin/S_RootCmds.ini_test_${LOWER_GAME_TYPE} | awk -F" " '{print $1}')
MD5_TEST_WEB=$(md5sum ${MANAGE_DIR}/S_RootCmds.ini_test_${LOWER_GAME_TYPE} | awk -F" " '{print $1}')
MD5_LIVE_ORIG=$(md5sum /home/${USER}/bin/S_RootCmds.ini_live_${LOWER_GAME_TYPE} | awk -F" " '{print $1}')
MD5_LIVE_WEB=$(md5sum ${MANAGE_DIR}/S_RootCmds.ini_live_${LOWER_GAME_TYPE} | awk -F" " '{print $1}')

if [ "${MD5_TEST_ORIG}" == "${MD5_TEST_WEB}" -a "${MD5_LIVE_ORIG}" == "${MD5_LIVE_WEB}" ]; then
    $HOME/bin/send_chatbot_text_only_by_thread_tag "modify_s_rootcmds" "網頁工具操作" "測試機 S_RootCmds.ini 無變動, 無須更新. 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10
else
    # backup
    TODATE=$(date +"%Y%m%d")
    NOW=$(date +"%Y%m%dT%H%M%S")
    sudo mkdir -p ${MANAGE_DIR}/${TODATE}
    sudo cp -arf /home/${USER}/bin/S_RootCmds.ini_test_${LOWER_GAME_TYPE} ${MANAGE_DIR}/${TODATE}/S_RootCmds.ini_test_${LOWER_GAME_TYPE}_${NOW}_${EXEC_USER}
    sudo cp -arf /home/${USER}/bin/S_RootCmds.ini_live_${LOWER_GAME_TYPE} ${MANAGE_DIR}/${TODATE}/S_RootCmds.ini_live_${LOWER_GAME_TYPE}_${NOW}_${EXEC_USER}

    # sync test
    if [ "${MD5_TEST_ORIG}" != "${MD5_TEST_WEB}" ]; then
        echo "sudo cp -arf ${MANAGE_DIR}/S_RootCmds.ini_test_${LOWER_GAME_TYPE} /home/${USER}/bin/." >> ${MANAGE_DIR}/to_log.txt
        sudo cp -arf ${MANAGE_DIR}/S_RootCmds.ini_test_${LOWER_GAME_TYPE} /home/${USER}/bin/.
        $HOME/bin/send_chatbot_text_only_by_thread_tag "modify_s_rootcmds" "網頁工具操作" "更新測試機 (S_RootCmds.ini_test_${LOWER_GAME_TYPE}) 完成, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10
    fi

    # sync live
    if [ "${MD5_LIVE_ORIG}" != "${MD5_LIVE_WEB}" ]; then
        echo "sudo cp -arf ${MANAGE_DIR}/S_RootCmds.ini_live_${LOWER_GAME_TYPE} /home/${USER}/bin/." >> ${MANAGE_DIR}/to_log.txt
        sudo cp -arf ${MANAGE_DIR}/S_RootCmds.ini_live_${LOWER_GAME_TYPE} /home/${USER}/bin/.
        $HOME/bin/send_chatbot_text_only_by_thread_tag "modify_s_rootcmds" "網頁工具操作" "更新測試機 (S_RootCmds.ini_live_${LOWER_GAME_TYPE}) 完成, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10
    fi
fi

$HOME/bin/send_chatbot_text_only_by_thread_tag "modify_s_rootcmds" "網頁工具操作" "測試機 S_RootCmds.ini 同步結束, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10
