#!/bin/bash

SCRIPT_NAME=$(basename "$0")
LOCK_FILE="/tmp/${SCRIPT_NAME}.lock"

exec 200>"${LOCK_FILE}"
flock -n 200 || {
        echo "Another instance is running. Exiting."
        exit 1
}

countdown_seconds () {
        seconds=$1
        for ((i=seconds; i>0; i--)); do
                echo "$i"
                sleep 1
        done
}

OPEN_NEW_WORLD="0"
USER_LIMIT="600"

init_now=$(date +"%H:%M")

# 拆成時與分，轉成分鐘
init_h=${init_now%%:*}
init_m=${init_now##*:}
init_total_min=$((10#$init_h * 60 + 10#$init_m))

# 轉換成 UTC+8 時段

# 特殊開服時段 00:10 ~ 00:30
if (( init_total_min >= 10 && init_total_min <= 30 )); then
    LAST_PUBLIC_WORLD_INFO=$(ssh -o StrictHostKeyChecking=no ACCOUNTDB "psql -U postgres -d N1Account -qAt -c \"SELECT id, character_number FROM worlds WHERE maxnum_user > 0 ORDER BY id DESC LIMIT 1;\"")
    echo "$LAST_PUBLIC_WORLD_INFO"

    IFS='|' read -r LAST_PUBLIC_WORLD_ID CURRENT_LAST_PUBLIC_WORLD_ID_CHAR_NUM <<< "$LAST_PUBLIC_WORLD_INFO"
    LAST_PUBLIC_SET_ID=$((LAST_PUBLIC_WORLD_ID / 100))

    if [ "${CURRENT_LAST_PUBLIC_WORLD_ID_CHAR_NUM}" -ge "${USER_LIMIT}" ]; then
        OPEN_NEW_WORLD="1"
    fi
else
    exec echo "blocked: $init_now falls within the restricted time period"
fi


if [ "${OPEN_NEW_WORLD}" -eq 1 ]; then
    cur_world_server_id="${LAST_PUBLIC_WORLD_ID}"
    echo "### CUR WSID: ${cur_world_server_id} ###"
    CHECK_WORLD_SERVER_ID=$(( cur_world_server_id % 100 ))

    if [ "${CHECK_WORLD_SERVER_ID}" -lt 99 ]; then
        NEW_WORLD_SERVER_ID=$(( cur_world_server_id + 1 ))
        NEW_SET_ID=$(( cur_world_server_id / 100 ))
    else
        NEW_SET_ID=$(( cur_world_server_id / 100 + 1))
        NEW_WORLD_SERVER_ID="${NEW_SET_ID}01"
    fi

    CURRENT_DATETIME=$(date +"%Y-%m-%d %H:%M:%S")
    FOUR_MINUTES_LATER_DATETIME=$(date -d "+4 minutes" +"%Y-%m-%d %H:%M:%S")
    #echo "psql -U postgres -d WebTool -qAt -c \"UPDATE db_setup SET is_purchased = 1, is_locked = 1, block_previous_world = 1, schedule_time = '${FOUR_MINUTES_LATER_DATETIME}' WHERE is_commercial = 1 AND world_id = '${NEW_WORLD_SERVER_ID}' AND ( schedule_time IS NULL or is_locked = 0 ) RETURNING world_id;\""
    RETURNING_WORLD_SERVER_ID=$(psql -U postgres -d WebTool -qAt -c "UPDATE db_setup SET is_purchased = 1, is_locked = 1, block_previous_world = 1, schedule_time = '${FOUR_MINUTES_LATER_DATETIME}' WHERE is_commercial = 1 AND world_id = '${NEW_WORLD_SERVER_ID}' AND ( schedule_time IS NULL or is_locked = 0 ) RETURNING world_id;")

    if [ "${RETURNING_WORLD_SERVER_ID}" == "${NEW_WORLD_SERVER_ID}" ]; then
        $HOME/bin/send_chatbot_text_only "系統腳本" "[自動開服前置作業_跨日規則(台版)] SET${NEW_SET_ID} > 舊服 WS${cur_world_server_id} 已經超過單服設定上限人數 ${USER_LIMIT} ( 角色數量 ${CURRENT_LAST_PUBLIC_WORLD_ID_CHAR_NUM} ); 新服 WS${NEW_WORLD_SERVER_ID} 加入開服排程資料表 ( ${FOUR_MINUTES_LATER_DATETIME} )"
        sleep 5
        echo
    fi
fi
