#!/bin/sh
# et-server's launcher: the engine's command line from /etc/default/et and the chosen
# mod, the one etadm builds (etadm's internal/etserver), then the engine in place of this shell.
set -e

BASE=/usr/lib/et
HOME_DIR=/var/lib/et

# dedicated is read only once set on the command line: a config can't turn it back. 1
# never heartbeats the masters whatever sv_master* say, 2 does.
dedicated=1
if [ "$ET_HEARTBEAT" = 1 ]; then
	dedicated=2
fi

# The mod, as etadm picks it (internal/mods): the one chosen in etadm's UI ($HOME_DIR/mod),
# else ET_MOD, else legacy, else the first installed. Installed: a folder with its game
# code, in fs_homepath or fs_basepath.
installed() {
	[ -n "$1" ] && [ "$1" != etmain ] && { [ -f "$HOME_DIR/$1/qagame.mp.i386.so" ] || [ -f "$BASE/$1/qagame.mp.i386.so" ]; }
}

mod=""
for m in "$(cat "$HOME_DIR/mod" 2>/dev/null || true)" "$ET_MOD" legacy; do
	if installed "$m"; then
		mod=$m
		break
	fi
done

# The first installed by name, as etadm sorts them.
if [ -z "$mod" ]; then
	mod=$(for q in "$HOME_DIR"/*/qagame.mp.i386.so "$BASE"/*/qagame.mp.i386.so; do
		[ -f "$q" ] && basename "$(dirname "$q")"
	done | grep -vx etmain | sort | head -n 1)
fi

if [ -z "$mod" ]; then
	# 2: exit 1 is a success for the unit (the engine's exit on SIGTERM).
	echo "et-server: no mod installed (apt install et-legacy, et-nq or et-jaymod)" >&2
	exit 2
fi

# ttycon 0: no terminal (systemd), com_ansiColor 0: plain text in the journal.
set -- +set dedicated "$dedicated" +set fs_basepath "$BASE" +set fs_homepath "$HOME_DIR" \
	+set fs_game "$mod" +set net_port "${ET_PORT:-27960}" \
	+set com_hunkmegs 128 +set com_zonemegs 48 +set ttycon 0 +set com_ansiColor 0

# Bots when et-omnibot is installed.
if [ -e "$BASE/omni-bot/omnibot_et.so" ]; then
	set -- "$@" +set omnibot_enable 1 +set omnibot_path "$BASE/omni-bot"
else
	set -- "$@" +set omnibot_enable 0
fi

set -- "$@" +exec server.cfg

# dedicated 1 forces an unlimited rate for LAN addresses (behind a relay, every player
# comes from its private address). After the config: No Quarter's sets it back to 1.
if [ "$dedicated" = 1 ]; then
	set -- "$@" +set sv_lanForceRate 0
fi

# What etadm keeps from its UI (the server's name, the game type's rotation), in
# fs_homepath's etmain, the one folder the engine searches whatever the mod: after the
# config, it holds over it, with or without etadm running the game.
if [ -f "$HOME_DIR/etmain/etadm.cfg" ]; then
	set -- "$@" +exec etadm.cfg
fi

# No Quarter's qagame links to liblua5.1.so, a link in fs_basepath.
export LD_LIBRARY_PATH="$BASE"

# ET_ARGS (/etc/default/et-server) last: they override the config.
# shellcheck disable=SC2086
exec "$BASE/etlded.i386" "$@" $ET_ARGS
