#!/usr/bin/env bash
# Runs a Tidewall dedicated server and turns SIGTERM or SIGINT into a clean stop: the
# server tells everyone connected it is shutting down, logs its statistics and exits 0.
# The engine can't catch signals itself, so this wrapper creates the server's
# --stop-file when one arrives, and kills the server only if it hasn't gone after
# TIDEWALL_STOP_SECONDS (default 15).
#
#   tidewall-server [server options...]      e.g. --config=/etc/tidewall/server.cfg
#
# Where things are, overridable from the environment:
#   TIDEWALL_HOME     the install: engine/godot and game/ (default /opt/tidewall)
#   TIDEWALL_ENGINE   the engine binary (default $TIDEWALL_HOME/engine/godot)
#   TIDEWALL_GAME     the game's project directory (default $TIDEWALL_HOME/game)
#   TIDEWALL_STATE    a writable directory for the engine's own files and the stop file
#                     (default $RUNTIME_DIRECTORY under systemd, else /tmp/tidewall-server)
set -u

home="${TIDEWALL_HOME:-/opt/tidewall}"
engine="${TIDEWALL_ENGINE:-$home/engine/godot}"
game="${TIDEWALL_GAME:-$home/game}"
state="${TIDEWALL_STATE:-${RUNTIME_DIRECTORY:-/tmp/tidewall-server}}"
grace="${TIDEWALL_STOP_SECONDS:-15}"
stop_file="$state/stop"

mkdir -p "$state/data" "$state/config" "$state/cache"
rm -f "$stop_file"
# The engine writes its user data and caches here, so the install can stay read-only.
export XDG_DATA_HOME="$state/data" XDG_CONFIG_HOME="$state/config" XDG_CACHE_HOME="$state/cache"

"$engine" --headless --path "$game" -- --server --stop-file="$stop_file" "$@" &
child=$!

request_stop() {
	touch "$stop_file"
	# If it hasn't stopped in time, stop it the hard way.
	( sleep "$grace"; kill -KILL "$child" 2>/dev/null ) &
}
trap request_stop TERM INT

wait "$child"
code=$?
# A trapped signal interrupts wait; keep waiting until the server has really gone.
while kill -0 "$child" 2>/dev/null; do
	wait "$child"
	code=$?
done
exit "$code"
