#!/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) 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_DATEIME=$(date -d "+4 minutes" +"%Y-%m-%d %H:%M:%S")

        #echo "psql -U postgres WebTool -c \"UPDATE db_setup SET is_purchased = 1, is_locked = 1, block_previous_world = 1, schedule_time = '${FOUR_MINUTES_LATER_DATEIME}' WHERE is_commercial = 1 AND world_id = '${NEW_WORLD_SERVER_ID}' AND ( schedule_time IS NULL or is_locked = 0 )\""
        psql -U postgres WebTool -c "UPDATE db_setup SET is_purchased = 1, is_locked = 1, block_previous_world = 1, schedule_time = '${FOUR_MINUTES_LATER_DATEIME}' WHERE is_commercial = 1 AND world_id = '${NEW_WORLD_SERVER_ID}' AND ( schedule_time IS NULL or is_locked = 0 )"
        $HOME/bin/send_chatbot_text_only "系統腳本" "[開新服人數檢查] SET${NEW_SET_ID} > WS${NEW_WORLD_SERVER_ID} 加入開服排程資料庫 ( ${FOUR_MINUTES_LATER_DATEIME} )"
        sleep 5
        echo
    fi
done

