#!/bin/bash
source $HOME/.gamerc

usage() {
	echo "Usage: $0 <status|restore|change> <datetime>"
	exit 1
}

ACTION=$1
DATETIME=$2

if [ "$ACTION" != "status" ] && [ "$ACTION" != "restore" ] && [ "$ACTION" != "change" ]; then
	usage
fi

# --- Preflight checks: fail BEFORE stopping game servers ---

# change: datetime is required and must be valid
if [ "$ACTION" == "change" ]; then
	[ -z "$DATETIME" ] && usage
	if ! date -d "$DATETIME" >/dev/null 2>&1; then
		echo "ERROR: invalid datetime: ${DATETIME}"
		exit 1
	fi
fi

# restore: chrony replaces ntpdate (removed since Debian 13)
if [ "$ACTION" == "restore" ] && ! command -v chronyd >/dev/null 2>&1; then
	echo "ERROR: chronyd not found, please install chrony first (sudo apt install chrony)"
	exit 1
fi

# One-shot time sync, works on both Debian 12 & 13
sync_time_now() {
	if systemctl is-active --quiet chrony; then
		# chronyd -q cannot run while the daemon is active
		sudo chronyc makestep
	else
		sudo chronyd -q "server ${NTP_SERVER} iburst"
	fi
}

if [ "$ACTION" == "status" ]; then
	NOW_DATETIME=$(date +"%Y-%m-%d %H:%M:%S")
	echo "NOW DATETIME: ${NOW_DATETIME}"
	pl
	echo
else
	# Warn if a time-sync daemon may revert the manual change
	if [ "$ACTION" == "change" ]; then
		for SVC in chrony systemd-timesyncd; do
			if systemctl is-active --quiet ${SVC}; then
				echo "WARNING: ${SVC} is active, the changed time may be synced back."
				echo "         Stop it first if needed: sudo systemctl stop ${SVC}"
			fi
		done
	fi

	echo "Stop Game Servers..."
	TestCtrl stop
	echo

	if [ "$ACTION" == "restore" ]; then
		echo "Restore DateTime to Now"
		if ! sync_time_now; then
			echo "ERROR: time sync failed, abort. (Game Servers remain stopped)"
			exit 1
		fi
		echo

	elif [ "$ACTION" == "change" ]; then
		echo "Change DateTime to ${DATETIME}"
		if ! sudo date -s "$DATETIME"; then
			echo "ERROR: failed to set datetime, abort. (Game Servers remain stopped)"
			exit 1
		fi
		echo
	fi

	PG_VERSION=$(psql --version | awk -F" " '{print $3}' | awk -F"." '{print $1}')

	echo "Restart Postgresql Database Server ${PG_VERSION} ..."
	sudo systemctl restart postgresql@${PG_VERSION}-main.service
	echo

	echo "Remove the logs on all servers current directory"
	shopt -s nullglob
	SERVER_DIRS=(~/servers*/*Server*)
	shopt -u nullglob
	if [ ${#SERVER_DIRS[@]} -gt 0 ]; then
		find "${SERVER_DIRS[@]}" -type f -name "*log*" -exec rm -f {} \;
	fi
	echo

	echo "Start Game Servers now..."
	TestCtrl start
	echo
fi
