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

USER_LIMIT_NEW_DAY="400"

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 時段

# ASIA 1 特殊開服時段 00:10 ~ 01:00
if { [ $init_total_min -ge 10 ] && [ $init_total_min -le 60 ]; }; then
    REGION_ID=1
    WORLDS_LIVE_RECORDS=$(ssh ACCOUNTDB "psql -U postgres N1Account -c \"COPY (WITH t1 AS (SELECT DISTINCT ON (id/1000) id, time_zone, maxnum_user, character_number, nochar_block_login FROM worlds WHERE maxnum_user > 0 GROUP BY id/1000, id HAVING id/1000 = ${REGION_ID} ORDER BY id/1000, id DESC) SELECT id FROM t1 WHERE character_number > ${USER_LIMIT_NEW_DAY}) TO STDOUT;\"")

## US 2 特殊開服時段 13:10 ~ 14:00
#elif { [ $init_total_min -ge 790 ] && [ $init_total_min -le 840 ]; }; then
#    REGION_ID=2
#    WORLDS_LIVE_RECORDS=$(ssh ACCOUNTDB "psql -U postgres N1Account -c \"COPY (WITH t1 AS (SELECT DISTINCT ON (id/1000) id, time_zone, maxnum_user, character_number, nochar_block_login FROM worlds WHERE maxnum_user > 0 GROUP BY id/1000, id HAVING id/1000 = ${REGION_ID} ORDER BY id/1000, id DESC) SELECT id FROM t1 WHERE character_number > ${USER_LIMIT_NEW_DAY}) TO STDOUT;\"")

# EU 3 特殊開服時段 07:10 ~ 08:00
elif { [ $init_total_min -ge 430 ] && [ $init_total_min -le 480 ]; }; then
    REGION_ID=3
    WORLDS_LIVE_RECORDS=$(ssh ACCOUNTDB "psql -U postgres N1Account -c \"COPY (WITH t1 AS (SELECT DISTINCT ON (id/1000) id, time_zone, maxnum_user, character_number, nochar_block_login FROM worlds WHERE maxnum_user > 0 GROUP BY id/1000, id HAVING id/1000 = ${REGION_ID} ORDER BY id/1000, id DESC) SELECT id FROM t1 WHERE character_number > ${USER_LIMIT_NEW_DAY}) TO STDOUT;\"")
else
    exec echo "blocked: $init_now falls within the restricted time period"
fi


if [ ! -z "${WORLDS_LIVE_RECORDS}" ]; then
    for cur_world_server_id in ${WORLDS_LIVE_RECORDS}; do
        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 ))
            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 WebTool -c \"COPY (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 ) TO STDOUT;\""
            RETURNING_WORLD_SERVER_ID=$(psql -U postgres WebTool -c "COPY (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) TO STDOUT;")
            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_NEW_DAY}; 新服 WS${NEW_WORLD_SERVER_ID} 加入開服排程資料表 ( ${FOUR_MINUTES_LATER_DATETIME} )"
                sleep 5
                echo
            fi
        else
            NEW_SET_ID=$(( cur_world_server_id / 100 + 1))
            NEW_WORLD_SERVER_ID="${NEW_SET_ID}01"
            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 WebTool -c \"COPY (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 ) TO STDOUT;\""
            RETURNING_WORLD_SERVER_ID=$(psql -U postgres WebTool -c "COPY (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) TO STDOUT;")
            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_NEW_DAY}; 新服 WS${NEW_WORLD_SERVER_ID} 加入開服排程資料表 ( ${FOUR_MINUTES_LATER_DATETIME} )"
                sleep 5
                echo
            fi
        fi
    done
else
    exec echo "unblocked: ${init_now} on Region ${REGION_ID}, but no record."
fi
