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

#DATA=$(psql -U postgres WebTool -c "COPY (SELECT world_id, set_id, tag_name, is_public, is_purchased, schedule_time, EXTRACT(EPOCH FROM schedule_time)::INTEGER AS schedule_time_timestamp, EXTRACT(EPOCH FROM now())::INTEGER AS now_timestamp FROM db_setup WHERE is_commercial = 1 AND is_purchased = 1 AND is_public = 0 AND schedule_time IS NOT NULL AND EXTRACT(EPOCH FROM now())::INTEGER >= EXTRACT(EPOCH FROM schedule_time)::INTEGER ORDER BY schedule_time) TO STDOUT WITH DELIMITER ',';")

#SET_ID_LISTS=$(psql -U postgres WebTool -c "COPY (SELECT world_id FROM db_setup WHERE is_commercial = 1 AND is_purchased = 1 AND is_public = 0 AND schedule_time IS NOT NULL AND EXTRACT(EPOCH FROM now())::INTEGER >= EXTRACT(EPOCH FROM schedule_time)::INTEGER ORDER BY schedule_time) TO STDOUT WITH DELIMITER ',';")

SET_ID_LISTS=$1

for new_world_server_id in ${SET_ID_LISTS}; do
	echo "### ${new_world_server_id} ###"
	STATE=$(ssh SUBMIT "psql -U postgres N1Account -c \"COPY (SELECT state FROM worlds WHERE id = ${new_world_server_id}) TO STDOUT;\"")
	if [ ${STATE} -eq 1 ]; then
		echo "$HOME/bin/reset_server_world_id_silent_mode_rs_submit ${new_world_server_id}"
		STATUS=$($HOME/bin/reset_server_world_id_silent_mode_rs_submit ${new_world_server_id})
		if [ ${STATUS} -eq 0 ]; then
			$HOME/bin/send_chatbot_text_only_test "系統腳本" "[滾服流程] [送審機] s${new_world_server_id} 重置伺服器天數回到第一天"
			countdown_seconds 30
			echo "ssh SUBMIT \"psql -U postgres N1Account -c \"UPDATE worlds SET maxnum_user = 1200 WHERE id = ${new_world_server_id};\"\""
			ssh SUBMIT "psql -U postgres N1Account -c \"UPDATE worlds SET maxnum_user = 1200 WHERE id = ${new_world_server_id};\""
			$HOME/bin/send_chatbot_text_only_test "系統腳本" "[滾服流程] [送審機] s${new_world_server_id} 開放對外入口"
			if [ $((${new_world_server_id} % 100)) -ne 1 ]; then
				old_world_server_id=$((${new_world_server_id} - 1))
				echo "ssh SUBMIT \"psql -U postgres N1Account -c \"UPDATE worlds SET nochar_block_login = 1 WHERE id = ${old_world_server_id};\"\""
				ssh SUBMIT "psql -U postgres N1Account -c \"UPDATE worlds SET nochar_block_login = 1 WHERE id = ${old_world_server_id};\""
				$HOME/bin/send_chatbot_text_only_test "系統腳本" "[滾服流程] [送審機] s${old_world_server_id} 入口已關閉"
			fi
			$HOME/bin/send_chatbot_text_only_test "系統腳本" "[滾服流程] [送審機] s${new_world_server_id} 已完成對外所有流程"
		elif [ ${STATUS} -eq 1 ]; then
			echo "[送審機] Call CGI reset_server+${new_world_server_id} Failed, please wait for the next run!"
			continue
		fi
	elif [ ${STATE} -eq 0 ]; then
		echo "[送審機] ${new_world_server_id} 關閉中..." 
		continue
	fi
	echo
done
