#!/bin/bash
# SPDX-License-Identifier: AGPL-3.0-or-later
# SPDX-FileCopyrightText: 2023 grommunio GmbH

set -e

PROGNAME="`basename $0`"
ADMIN_PASSWORD=''
AUTO_CONFIG='false'
KCADM='/opt/grommunio-keycloak/bin/kcadm.sh'
KCADM_CONFIG='/root/.keycloak/grommunio-auth.config'
AUTH_CONF='/etc/grommunio-auth/grommunio-auth.conf'
AUTH_CLIENT_ID='grommunio-auth'
AUTH_EXTRA_REALM_MAPPERS='["oidc-audience-mapper"]'
TMPL_DIR='/usr/share/grommunio-auth/templates'
ADAPTOR_SCRIPT_DIR='/usr/share/grommunio-auth/adaptor-config-scripts'
ADAPTOR_CONFIG_DIR='/var/cache/grommunio-auth/adaptor-config'

# Keycloak clients this script can set up, and where the application sits
# in URL space by default (appended to the site FQDN).  For each client
# there is a shared/grommunio-<name>/endpoint-url debconf question that
# overrides the default, a grommunio-client-<name>.json.esh template in
# TMPL_DIR, and the application package ships the adaptor script
# setup-gk-app-g-<name> / delete-gk-app-g-<name> in ADAPTOR_SCRIPT_DIR.
CLIENT_TABLE='
web	/web
chat	/chat
files	/files
meet	/meet
archive	/archive
admin	:8443
'

KEYCLOAK_SERVER='http://127.0.0.1:9080/auth'
KEYCLOAK_PUBLIC_URL=''
KEYCLOAK_LISTEN_PORT='9080'
ADAPTOR_CONFIG_AGE=480  # minutes

. /usr/share/grommunio-pkg-bits/scripts/setup-include.sh


# calc_keycloak_server uses the keycloak templates
SHARED_TEMPLATES='
shared/grommunio/auto-config
shared/grommunio/admin-password
shared/grommunio/admin-password-again
shared/grommunio/admin-password-mismatch
shared/grommunio/admin-password-must-enter
shared/grommunio/site-fqdn
shared/grommunio-keycloak/endpoint-url
shared/grommunio-keycloak/listen-address
shared/grommunio-web/endpoint-url
shared/grommunio-chat/endpoint-url
shared/grommunio-files/endpoint-url
shared/grommunio-meet/endpoint-url
shared/grommunio-admin/endpoint-url
shared/grommunio-auth/auto-client-setup
'

PKG_TEMPLATES='
grommunio-auth/management-description
grommunio-auth/client-select
grommunio-auth/client-operation
'

client_names () {
	echo "$CLIENT_TABLE" | awk '{ print $1 }'
}

client_default_path () {
	echo "$CLIENT_TABLE" | awk -v c="$1" '$1 == c { print $2 }'
}

kcadm () {
	# Keep our login session out of the admin's own ~/.keycloak/kcadm.config
	"$KCADM" "$@" --config "$KCADM_CONFIG"
}

kc_credentials () {
	mkdir -p -m 0700 "`dirname "$KCADM_CONFIG"`"
	( umask '0077'; kcadm config credentials --server "${KEYCLOAK_SERVER}" "$@" )
}

kc_login_admin () {
	# Log in to Keycloak with the admin password held in debconf
	db_get shared/grommunio/admin-password
	ADMIN_PASSWORD="$RET"
	if [ -z "$ADMIN_PASSWORD" ]; then
		echo "${PROGNAME}: no Keycloak admin password in debconf, can't log in." 1>&2
		exit 1
	fi
	kc_credentials --realm master --user admin --password "${ADMIN_PASSWORD}"
}

kc_login () {
	# Log in to Keycloak, preferring the grommunio-auth service account
	# over the admin password so that clients can be set up unattended
	[ -s "$AUTH_CONF" ] && . "$AUTH_CONF"
	calc_keycloak_server
	calc_keycloak_public_url
	if [ -z "$KEYCLOAK_CLIENT_SECRET" ] \
		|| ! kc_credentials --realm "${KEYCLOAK_REALM}" --client "${KEYCLOAK_CLIENT_ID}" \
			--secret "${KEYCLOAK_CLIENT_SECRET}" 2>/dev/null; then
		kc_login_admin
	fi
}

calc_client_urls () {
	# Work out the URLs of an application from the site FQDN, overridden
	# by its endpoint-url question.  A bare host name gets DEFAULT_PATH
	# appended, ie 'https://<host>/web' for flat URL space.
	local NAME="$1"
	local DEFAULT_PATH="$2"
	local SCHEME=''
	local FQDN=''
	local PORT=''
	local BASE_PATH=''
	local FURL_PORT=''
	local FQDN_PORT=''
	ENDPOINT_URL='127.0.0.1'
	ENDPOINT_FURL=''
	FQDN_URL=''
	FQDN_FURL=''
	db_get shared/grommunio/site-fqdn
	[ -n "$RET" ] && ENDPOINT_URL="$RET"
	if [ "$NAME" = 'meet' ]; then
		# jitsi-meet on Debian lives on its own virtual host
		if db_get jitsi-videobridge/jvb-hostname && [ -n "$RET" ]; then
			ENDPOINT_URL="https://${RET}"
		fi
	fi
	# Not every application has a question yet
	if db_get "shared/grommunio-${NAME}/endpoint-url" && [ -n "$RET" ]; then
		ENDPOINT_URL="$RET"
	fi
	if echo "$ENDPOINT_URL" | grep -qP '^[^/]+$'; then
		ENDPOINT_URL="https://${ENDPOINT_URL}${DEFAULT_PATH}"
	fi
	SCHEME=$(trurl "$ENDPOINT_URL" --get '{scheme}')
	FQDN=$(trurl "$ENDPOINT_URL" --get '{host}')
	PORT=$(trurl "$ENDPOINT_URL" --get '{port}')
	BASE_PATH=$(trurl "$ENDPOINT_URL" --get '{path}')
	[ "$BASE_PATH" = '/' ] && BASE_PATH=''
	FURL_PORT="$PORT"
	if [ "$FURL_PORT" = '' ]; then
		[ "$SCHEME" = 'http' ] && FURL_PORT='80'
		[ "$SCHEME" = 'https' ] && FURL_PORT='443'
	fi
	ENDPOINT_FURL="${SCHEME}://${FQDN}:${FURL_PORT}${BASE_PATH}"
	[ -n "$PORT" ] && FQDN_PORT=":${PORT}"
	FQDN_URL="${SCHEME}://${FQDN}${FQDN_PORT}"
	FQDN_FURL="${SCHEME}://${FQDN}:${FURL_PORT}"
	# Normalised, so templates can append paths to it
	ENDPOINT_URL="${FQDN_URL}${BASE_PATH}"
}

calc_keycloak_public_url () {
	# Where users and applications reach Keycloak
	calc_client_urls keycloak /auth
	KEYCLOAK_PUBLIC_URL="$ENDPOINT_URL"
}

service_account_setup () {
	# Service account with just enough rights to manage the realm's
	# clients, for setting them up without the admin password later on
	local CLIENT_JSON='/etc/grommunio-auth/grommunio-client-auth.json'
	local tmpdir=`mktemp -d`
	local TMP_CLIENT_JSON="${tmpdir}/grommunio-client-auth.json"
	local CID=''
	local SECRET=''

	esh -o "$TMP_CLIENT_JSON" "${TMPL_DIR}/grommunio-client-auth.json.esh"
	ucf --three-way --debconf-ok -Z "$TMP_CLIENT_JSON" "$CLIENT_JSON"
	ucfr grommunio-auth "$CLIENT_JSON"
	rm -rf "$tmpdir"

	CID=$(client_uuid "$AUTH_CLIENT_ID")
	if [ -z "$CID" ]; then
		CID=$(kcadm create clients -r grommunio -i -f "$CLIENT_JSON")
		# Keycloak 26.8.2 changed things, to access protocol-mappers, role must have
		# 'manage-realm' access
		kcadm add-roles -r grommunio --uusername "service-account-${AUTH_CLIENT_ID}" \
			--cclientid realm-management --rolename manage-realm \
			--rolename manage-clients
	fi
	SECRET=$(kcadm get "clients/${CID}/client-secret" -r grommunio --fields value --format csv --noquotes)

	local OLD_UMASK=`umask`
	umask '0077'
	cat > "$AUTH_CONF" <<-EOF
		KEYCLOAK_SERVER=${KEYCLOAK_SERVER}
		KEYCLOAK_REALM=grommunio
		KEYCLOAK_PUBLIC_URL=${KEYCLOAK_PUBLIC_URL}
		KEYCLOAK_CLIENT_ID=${AUTH_CLIENT_ID}
		KEYCLOAK_CLIENT_SECRET=${SECRET}
	EOF
	umask "$OLD_UMASK"
}

configure_auth () {
	db_get shared/grommunio/admin-password
	ADMIN_PASSWORD="$RET"
	if [ -z "$ADMIN_PASSWORD" ]; then
		# Upgrade - the realm is left alone, but pick up new applications
		"${GSETUP_PKG_SCRIPTS_DIR}/setup-gk-clients" || true
		return 0
	fi

	calc_keycloak_server
	calc_keycloak_public_url

	local AUTO_CLIENT_SETUP='true'
	db_get shared/grommunio-auth/auto-client-setup
	AUTO_CLIENT_SETUP="$RET"

	# Wait for keycloak to become available
	while ! ss -ltnH "( sport = :${KEYCLOAK_LISTEN_PORT} )" | grep "$KEYCLOAK_LISTEN_PORT" -q ; do
		sleep 1
	done
	sleep 3

	kc_login_admin
	local BOOTSTRAP=0
	local REALM_ID=$(kcadm get realms/grommunio --fields id --format csv --noquotes 2>/dev/null)
	if [ -z "$REALM_ID" ]; then
		local CREALM_ID=$(kcadm create realms -i -s realm=grommunio -s enabled=true)
		REALM_ID=$(kcadm get realms/grommunio --fields id --format csv --noquotes 2>/dev/null)
		BOOTSTRAP=1
	fi
	kcadm update realms/grommunio -s rememberMe=true -s ssoSessionMaxLifespanRememberMe=2592000
	kcadm update realms/grommunio -s "loginTheme=grommunio"

	local COMPONENT_IDS=$(kcadm get components -r grommunio --fields id,name,providerType --format csv --noquotes | fgrep grommunio |fgrep 'org.keycloak.storage.UserStorageProvider' |cut -d ',' -f 1)
	if [ -z "$COMPONENT_IDS" ]; then
		kcadm create components \
			-r grommunio \
			-s name="grommunio" \
			-s providerId="grommunio" \
			-s providerType="org.keycloak.storage.UserStorageProvider" \
			-s parentId="$REALM_ID" \
			-s 'config.enabled=["true"]' \
			-s 'config.cachePolicy=["DEFAULT"]'
	fi

	# Set up client scope
	local tmpdir=`mktemp -d`
	local CLIENT_SCOPE_JSON='/etc/grommunio-auth/grommunio-client-scope.json'
	local TMP_CLIENT_SCOPE_JSON="${tmpdir}/grommunio-client-scope.json"
	esh -o "$TMP_CLIENT_SCOPE_JSON" "${TMPL_DIR}/grommunio-client-scope.json.esh"
	ucf --three-way --debconf-ok -Z "$TMP_CLIENT_SCOPE_JSON" "$CLIENT_SCOPE_JSON"
	ucfr grommunio-auth "$CLIENT_SCOPE_JSON"

	local CSID=$(kcadm get client-scopes -r grommunio --fields id,name --format csv --noquotes|grep grommunio-client|cut -d ',' -f 1)
	if [ -z "$CSID" ]; then
#		CSID=$(kcadm create client-scopes -r grommunio -i \
#			-s name="grommunio-client" \
#			-s description="Grommunio Client scope" \
#			-s protocol="openid-connect")
		kcadm create "client-scopes" -x -r grommunio -f "$CLIENT_SCOPE_JSON"
	fi
	#kcadm update "client-scopes/${CSID}" -x -r grommunio -f "$CLIENT_SCOPE_JSON"

	# clean up
	rm -rf "$tmpdir"

	service_account_setup

	[ $BOOTSTRAP -eq 1 ] && sleep 3
	if [ $AUTO_CLIENT_SETUP = 'true' ]; then
		# Set up the clients of applications on this system
		client_setup_all
	fi

}

configure_auth_triggered () {
	# Set up clients of applications installed after grommunio-auth was
	# configured. Run as setup-gk-clients from the dpkg trigger on the
	# adaptor script dir and on upgrade, so it must not need the admin
	# password, and runs in its own process so its failure can be ignored.
	[ -s "$AUTH_CONF" ] || return 0
	db_get shared/grommunio-auth/auto-client-setup
	[ "$RET" = 'true' ] || return 0

	calc_keycloak_server
	if ! ss -ltnH "( sport = :${KEYCLOAK_LISTEN_PORT} )" | grep "$KEYCLOAK_LISTEN_PORT" -q ; then
		echo "${PROGNAME}: keycloak is not running, not setting up clients." 1>&2
		return 0
	fi
	client_setup_all
}


delete_auth () {
	# If client(s) installed on this system, remove them first
	local NAME=''
	for NAME in $(client_names); do
		if [ -x "${ADAPTOR_SCRIPT_DIR}/delete-gk-app-g-${NAME}" ]; then
			client_delete "$NAME"
		fi
	done

	calc_keycloak_server
	kc_login_admin
	local REALM_ID=$(kcadm get realms/grommunio --fields id --format csv --noquotes 2>/dev/null)
	if [ -n "$REALM_ID" ]; then
		kcadm delete realms/grommunio
	fi
	# Clean up any cached export files and the service account login
	rm -f "${ADAPTOR_CONFIG_DIR:?}"/* || true
	rm -f "$AUTH_CONF" "$KCADM_CONFIG" || true
}

client_uuid () {
	# Keycloak's id of a client, empty if it does not exist
	kcadm get clients -r grommunio -q clientId="$1" --fields id --format csv --noquotes 2>/dev/null || true
}

adaptor_config_write () {
	# Stage keycloak.json and the realm public key for the adaptor script
	local CID="$1"
	local ADAPTOR_CONFIG="$2"
	local ADAPTOR_PUBKEY="$3"
	local OLD_UMASK=`umask`
	umask '0077'
	kcadm get "clients/${CID}/installation/providers/keycloak-oidc-keycloak-json" -r grommunio \
		| jq --arg url "${KEYCLOAK_PUBLIC_URL}/" '."auth-server-url" = $url' > "$ADAPTOR_CONFIG"

	unset http_proxy https_proxy
	{
		echo "-----BEGIN PUBLIC KEY-----"
		curl -s "${KEYCLOAK_SERVER}/realms/grommunio" | jq -r .public_key | fold -w 64
		echo "-----END PUBLIC KEY-----"
	} > "$ADAPTOR_PUBKEY"
	umask "$OLD_UMASK"
}

client_mappers_ensure () {
	# Add the template's protocol mappers to an existing client, which an
	# older release may have created without them
	local CID="$1"
	local CLIENT_JSON="$2"
	local NAME=''
	local I=0
	local N=$(jq '.protocolMappers | length' "$CLIENT_JSON")
	local MAPPERS=$(kcadm get "clients/${CID}/protocol-mappers/models" -r grommunio \
		--fields name --format csv --noquotes)

	while [ $I -lt $N ]; do
		NAME=$(jq -r ".protocolMappers[${I}].name" "$CLIENT_JSON")
		if ! echo "$MAPPERS" | grep -qxF "$NAME"; then
			jq ".protocolMappers[${I}]" "$CLIENT_JSON" \
				| kcadm create "clients/${CID}/protocol-mappers/models" -r grommunio -f -
		fi
		I=$((I + 1))
	done
}

client_setup () {
	# Create the Keycloak client of an application if it does not exist,
	# and hand its configuration over to the application's adaptor script
	local NAME="$1"
	local DEFAULT_PATH="$2"
	local CLIENT_ID="grommunio-${NAME}"
	local CLIENT_JSON="/etc/grommunio-auth/grommunio-client-${NAME}.json"
	local ADAPTOR_CONFIG="${ADAPTOR_CONFIG_DIR}/keycloak-${CLIENT_ID}.json"
	local ADAPTOR_PUBKEY="${ADAPTOR_CONFIG_DIR}/keycloak-${CLIENT_ID}.bearer_pubkey"
	local ADAPTOR_SCRIPT="${ADAPTOR_SCRIPT_DIR}/setup-gk-app-g-${NAME}"
	local CID=''

	[ -z "$DEFAULT_PATH" ] && DEFAULT_PATH=$(client_default_path "$NAME")
	if [ -z "$DEFAULT_PATH" ]; then
		echo "${PROGNAME}: unknown client '${NAME}'." 1>&2
		exit 2
	fi

	kc_login
	calc_client_urls "$NAME" "$DEFAULT_PATH"

	# Set up client config
	local tmpdir=`mktemp -d`
	local TMP_CLIENT_JSON="${tmpdir}/grommunio-client-${NAME}.json"
	esh -o "$TMP_CLIENT_JSON" "${TMPL_DIR}/grommunio-client-${NAME}.json.esh" \
		endpoint_url="$ENDPOINT_URL" endpoint_furl="$ENDPOINT_FURL" \
		fqdn_url="$FQDN_URL" fqdn_furl="$FQDN_FURL"
	ucf --three-way --debconf-ok -Z "$TMP_CLIENT_JSON" "$CLIENT_JSON"
	ucfr grommunio-auth "$CLIENT_JSON"
	rm -rf "$tmpdir"

	CID=$(client_uuid "$CLIENT_ID")
	if [ -z "$CID" ]; then
		CID=$(kcadm create clients -r grommunio -i -f "$CLIENT_JSON")
	else
		client_mappers_ensure "$CID" "$CLIENT_JSON"
	fi

	adaptor_config_write "$CID" "$ADAPTOR_CONFIG" "$ADAPTOR_PUBKEY"

	# Run the application's adaptor config script if present
	[ -x "$ADAPTOR_SCRIPT" ] && "$ADAPTOR_SCRIPT" || true

	return 0
}

client_setup_all () {
	# Set up the clients of all applications installed on this system
	local NAME=''
	for NAME in $(client_names); do
		if [ -x "${ADAPTOR_SCRIPT_DIR}/setup-gk-app-g-${NAME}" ]; then
			client_setup "$NAME" "$(client_default_path "$NAME")"
		fi
	done
}

client_delete () {
	# Delete the Keycloak client of an application and undo its configuration
	local NAME="$1"
	local CLIENT_ID="grommunio-${NAME}"
	local ADAPTOR_DEL_SCRIPT="${ADAPTOR_SCRIPT_DIR}/delete-gk-app-g-${NAME}"
	local CID=''

	kc_login
	CID=$(client_uuid "$CLIENT_ID")
	if [ -n "$CID" ]; then
		kcadm delete "clients/${CID}" -r grommunio
	fi
	# Clean up any cached export files
	rm -f "${ADAPTOR_CONFIG_DIR}/keycloak-${CLIENT_ID}.json" || true
	rm -f "${ADAPTOR_CONFIG_DIR}/keycloak-${CLIENT_ID}.bearer_pubkey" || true

	# Run the application's adaptor config script if present
	[ -x "$ADAPTOR_DEL_SCRIPT" ] && "$ADAPTOR_DEL_SCRIPT" || true

	return 0
}

clean_adaptor_config () {
	# Remove all files in any tree
	find "${ADAPTOR_CONFIG_DIR}" -mmin "+${ADAPTOR_CONFIG_AGE}" -type f -print0 | xargs -0r /usr/bin/shred -u || true
	# Remove any directories
	find "${ADAPTOR_CONFIG_DIR}" -mmin "+${ADAPTOR_CONFIG_AGE}" -type d -print0 | grep -zv "^${ADAPTOR_CONFIG_DIR}\$" | xargs -0r /usr/bin/rm -rf || true
	return 0
}

case "$PROGNAME" in
	setup-grommunio-auth|setup-grommunio-auth-multi)
		check_if_root
		start_debconf -x grommunio-auth "$@"
		configure_auth configure ${ARGS}
		;;
	delete-grommunio-auth|delete-grommunio-auth-multi)
		check_if_root
		start_debconf -x grommunio-auth "$@"
		delete_auth
		;;
	setup-gk-client-*)
		check_if_root
		start_debconf -x grommunio-auth "$@"
		client_setup "${PROGNAME#setup-gk-client-}"
		;;
	delete-gk-client-*)
		check_if_root
		start_debconf -x grommunio-auth "$@"
		client_delete "${PROGNAME#delete-gk-client-}"
		;;
	setup-gk-clients)
		check_if_root
		# No questions are asked, but ucf --debconf-ok needs a frontend
		# rather than a debconf-communicate holding the config db locked.
		# confmodule reuses the frontend of a calling postinst, and
		# otherwise re-execs this script under a new one.
		[ -n "${DEBIAN_FRONTEND:-}" ] || export DEBIAN_FRONTEND='noninteractive'
		export DEBCONF_PACKAGE='grommunio-auth'
		. /usr/share/debconf/confmodule
		configure_auth_triggered
		;;
	clean-gk-adaptor-config)
		check_if_root
		clean_adaptor_config
		;;
esac
