#!/bin/sh
set -eu

group=authentik
config_file='/etc/authentik/config.yml'

setcap 'cap_net_bind_service=+ep' /usr/share/webapps/authentik/server

if [ $(grep '@@SECRET_KEY@@' "$config_file") ]; then
	echo "* Generating random secret in $config_file" >&2

	secret_key="$(pwgen -s 50 1)"
	sed -i "s|@@SECRET_KEY@@|$secret_key|" "$config_file"
	chown root:$group "$config_file"
	chmod 0640 "$config_file"
fi

if [ "${0##*.}" = 'post-upgrade' ]; then
	cat >&2 <<-EOF
	*
	* To finish Authentik upgrade run:
	*
	*     authentik-manage migrate
	*
	EOF
else
	cat >&2 <<-EOF
	*
	* 1. Adjust settings in /etc/authentik/config.yml.
	*
	* 2. Create database for Authentik:
	*
	*     psql -c "CREATE ROLE authentik PASSWORD 'top-secret' INHERIT LOGIN;"
	*     psql -c "CREATE DATABASE authentik OWNER authentik ENCODING 'UTF-8';"
	*
	* 3. Run "authentik-manage migrate"
	* 4. Setup admin user at https://<your server>/if/flow/initial-setup/
	*
	EOF
fi