#!/bin/sh
# authentik management command (upstream "ak"):
#   ak create_recovery_key 10 akadmin
#   ak shell, ak migrate, ak dump_config, ak <django manage command>
# run as the authentik user (root drops to it)
APPDIR=/usr/share/authentik

# the same environment as the services (readable by root and authentik)
# (by a variable: an optional file, not a dependency for shell.req)
ENVFILE=/etc/authentik/authentik.env
if [ -r "$ENVFILE" ] ; then
	set -a
	. "$ENVFILE"
	set +a
fi

if [ "$(id -u)" = 0 ] ; then
	exec setpriv --reuid authentik --regid authentik --init-groups -- env HOME=/var/lib/authentik "$0" "$@"
fi

cd "$APPDIR" || exit
export PYTHONPATH="$APPDIR"
export TMPDIR="${TMPDIR:-/tmp}"
export PROMETHEUS_MULTIPROC_DIR="${PROMETHEUS_MULTIPROC_DIR:-$TMPDIR/authentik_prometheus_tmp}"
mkdir -p "$PROMETHEUS_MULTIPROC_DIR"

case "$1" in
	server|worker|allinone|healthcheck)
		exec /usr/lib/authentik/authentik "$@"
		;;
	dump_config)
		shift
		exec /usr/bin/python3 -m authentik.lib.config "$@"
		;;
	*)
		exec /usr/bin/python3 -m manage "$@"
		;;
esac
