#!/bin/bash
[ "$2" == "" ] && exec echo "Usage: $0 <patch directory's name> <execute by who>"

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

REMOTE_PATCH_DIRS="${COUNTRY_CODE}"
PN=$1
EXEC_USER=$2

LOG_DIR="${HOME}/www/tools/files/test_patch_log/"
[ -d "$LOG_DIR" ] || { mkdir -p "$LOG_DIR"; chmod -R 777 "$LOG_DIR"; }

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

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

CHECK_LOCAL_DIR_EXIST=$([ -d "${HOME}/patch/${PN}" ] && echo '1' || echo '0')

if [ "${CHECK_LOCAL_DIR_EXIST}" -eq 0 ]; then
    CHECK_DIR_EXIST=$(lftp http://$REMOTE_PATCH_SERVER/$COUNTRY_CODE/ -e "cd ${PN} && echo '1' || echo '0'; bye" 2> /dev/null)
    
    $HOME/bin/send_chatbot_text_only_by_thread_tag "test_patch" "網頁工具操作" "測試機版本 ${PN}, 更新開始, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10

    if [ "${CHECK_DIR_EXIST}" -eq 0 ]; then
        check_filename="/tmp/test_patch_check_monitor.log"
        echo "測試機版本更新失敗,\n出版機沒有不存在這個版本 ${PN},\n麻煩請找研發確認看看!" > $check_filename
        echo -e "測試機版本更新失敗,\n出版機沒有不存在這個版本 ${PN},\n麻煩請找研發確認看看!" > ${LOG_DIR}/${LOG_FILE}
        exec $HOME/bin/send_messages_with_pic_failed INFO test_patch_check  "測試機版本更新" 1> /dev/null 2> /dev/null
    else
        #mkdir ~/patch/${PN}
        #cd ~/patch/${PN}
        #lftp http://${REMOTE_PATCH_SERVER}/${REMOTE_PATCH_DIRS}/${PN} -e "mget *;exit"
        #echo yes | TestCtrl patch TEST ${PN} noftp | tee -a ${LOG_DIR}/${LOG_FILE}
        echo yes | TestCtrl patch TEST ${PN} >> ${LOG_DIR}/${LOG_FILE}
        cat ${LOG_DIR}/${LOG_FILE} | aha | tee -a ${LOG_DIR}/${HTML_OUTPUT_FILE}
    fi
elif [ "${CHECK_LOCAL_DIR_EXIST}" -eq 1 ]; then
    $HOME/bin/send_chatbot_text_only_by_thread_tag "test_patch" "網頁工具操作" "測試機版本 ${PN}, 更新開始, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10

    echo yes | TestCtrl patch TEST ${PN} noftp >> ${LOG_DIR}/${LOG_FILE}
    cat ${LOG_DIR}/${LOG_FILE} | aha | tee -a ${LOG_DIR}/${HTML_OUTPUT_FILE}
fi

$HOME/bin/send_chatbot_text_only_by_thread_tag "test_patch" "網頁工具操作" "測試機版本 ${PN}, 更新結束, 執行人員 by ${EXEC_USER_NICK_NAME}" minute 10

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