#!/bin/bash

EXEC_USER="$1"
MANAGE_DIR="$2"
USER=$(whoami)

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

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

$HOME/bin/send_chatbot_text_only_by_thread_tag "modify_s_rootcmds" "網頁工具操作" "S_RootCmds.ini on 測試機, 更新開始, 執行人員 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_n1 | awk -F" " '{print $1}')
MD5_TEST_WEB=$(md5sum ${MANAGE_DIR}/S_RootCmds.ini_test_n1 | awk -F" " '{print $1}')
MD5_LIVE_ORIG=$(md5sum /home/${USER}/bin/S_RootCmds.ini_live_n1 | awk -F" " '{print $1}')
MD5_LIVE_WEB=$(md5sum ${MANAGE_DIR}/S_RootCmds.ini_live_n1 | 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_n1 ${MANAGE_DIR}/${TODATE}/S_RootCmds.ini_test_n1_${NOW}_${EXEC_USER}
    sudo cp -arf /home/${USER}/bin/S_RootCmds.ini_live_n1 ${MANAGE_DIR}/${TODATE}/S_RootCmds.ini_live_n1_${NOW}_${EXEC_USER}

    # sync test
    if [ "${MD5_TEST_ORIG}" != "${MD5_TEST_WEB}" ]; then
        echo "sudo cp -arf ${MANAGE_DIR}/S_RootCmds.ini_test_n1 /home/${USER}/bin/." >> ${MANAGE_DIR}/to_log.txt
        sudo cp -arf ${MANAGE_DIR}/S_RootCmds.ini_test_n1 /home/${USER}/bin/.
    fi

    # sync live
    if [ "${MD5_LIVE_ORIG}" != "${MD5_LIVE_WEB}" ]; then
        echo "sudo cp -arf ${MANAGE_DIR}/S_RootCmds.ini_live_n1 /home/${USER}/bin/." >> ${MANAGE_DIR}/to_log.txt
        sudo cp -arf ${MANAGE_DIR}/S_RootCmds.ini_live_n1 /home/${USER}/bin/.
    fi

    $HOME/bin/send_chatbot_text_only_by_thread_tag "modify_s_rootcmds" "網頁工具操作" "S_RootCmds.ini 更新完成, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10
fi

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