#!/bin/sh
# etadm takes the game of et-server's install over: etadm.service instead of et-server's
# own service (they conflict, the start of one stops the other). Called by etadm's
# postinst and et-server's: whichever is configured last finds both. Nothing to do
# without et-server: etadm is then the binary alone.
#   etadm-takeover            (re)starts etadm.service
#   etadm-takeover reload     a running etadm takes a new binary over, the game stays
set -e

if [ ! -x /usr/libexec/et-server ] || ! getent passwd et >/dev/null; then
	exit 0
fi

# etadm's secrets: UI logins, session key, API token. et only.
install -d -o et -g et -m 0700 /etc/etadm
if [ ! -s /etc/etadm/token ]; then
	(umask 077; head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > /etc/etadm/token)
	chown et:et /etc/etadm/token
fi

[ -d /run/systemd/system ] || exit 0

systemctl daemon-reload
systemctl disable et-server.service >/dev/null 2>&1 || true
systemctl enable etadm.service >/dev/null 2>&1

if [ "$1" = reload ] && systemctl is-active -q etadm.service; then
	systemctl reload etadm.service
	exit 0
fi

systemctl restart etadm.service
