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

source $HOME/.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 ;;
        *) shift ;;
    esac
done

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

DATE=$(date +"%Y%m%d")
if [[ -n "$LOG_DIR_BASE" ]]; then
    LOG_DIR="${LOG_DIR_BASE}/${DATE}"
else
    LOG_DIR="/tmp/test_patch_log/${DATE}"
fi
[ -d "$LOG_DIR" ] || { mkdir -p "$LOG_DIR"; chmod -R 777 "$LOG_DIR" 2>/dev/null; }

NOW=$(date +"%Y%m%dT%H%M%S")
LOG_FILE="${LOG_DIR}/${PN}_${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} )"

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

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麻煩請找研發確認看看!"
        $HOME/bin/send_messages_with_pic_failed INFO test_patch_check "測試機版本更新" 1> /dev/null 2> /dev/null
    else
        echo yes | TestCtrl patch TEST ${PN}
    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
fi

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

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