#!/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="1200"

WORLDS_LIVE_RECORDS=$(ssh ACCOUNTDB "psql -U postgres N1Account -c \"COPY (WITH t1 AS (SELECT DISTINCT ON (id/100) id, time_zone, maxnum_user, character_number, nochar_block_login FROM worlds WHERE maxnum_user > 0 AND id/100 NOT IN (10,20,30,21) GROUP BY id/100, id ORDER BY id/100, id DESC) SELECT id AS world_id FROM t1 WHERE character_number > ${USER_LIMIT}) TO STDOUT;\"")

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

        CHECK_REGION_ID=$(( cur_world_server_id / 1000 ))

        now=$(date +"%H:%M")
        after4=$(date -d "+4 minutes" +"%H:%M")

        h=${after4%%:*}
        m=${after4##*:}

        h=$((10#$h))
        m=$((10#$m))

        total_min=$((h*60 + m))

        case ${CHECK_REGION_ID} in
            # 轉換成 UTC+8 時段
            # ASIA 1 禁止開服時段 14:00 ~ 23:59 & 00:00 ~ 01:00
            1)  
                if { [ $total_min -ge 840 ] && [ $total_min -le 1439 ]; } || { [ $total_min -ge 0 ] && [ $total_min -le 60 ]; }; then
                    ACTION="X"
                else
                    ACTION="O"
                fi
                ;;
            # US 2 禁止開服時段 03:00 ~ 14:00
            2)  
                if { [ $total_min -ge 180 ] && [ $total_min -le 840 ]; }; then
                    ACTION="X"
                else
                    ACTION="O"
                fi
                ;;
            # EU 3 禁止開服時段 02:00 ~ 08:00
            3)  
                if { [ $total_min -ge 120 ] && [ $total_min -le 480 ]; }; then
                    ACTION="X"
                else
                    ACTION="O"
                fi                   
                ;;
            *)
                ACTION="X"
                echo "Unknown Region ID"
                ;;
        esac

        if [ "${ACTION}" == "O" ]; then
            #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}; 新服 WS${NEW_WORLD_SERVER_ID} 加入開服排程資料表 ( ${FOUR_MINUTES_LATER_DATETIME} )"
                sleep 5
                echo
            fi
        else
            echo "Region ID: ${CHECK_REGION_ID}, WSID: ${NEW_WORLD_SERVER_ID}, SCHEDULE TIME: ${FOUR_MINUTES_LATER_DATETIME} falls within the restricted time period."
            echo
        fi
    fi
done

