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

set -e

PROGNAME="`basename $0`"
ADAPTOR_CONFIG_DIR='/var/cache/grommunio-auth/adaptor-config'
GFILES_ADAPTOR_CONFIG='keycloak-grommunio-files.json'
GFILES_ADAPTOR_PUBKEY='keycloak-grommunio-files.bearer_pubkey'
GFILES_ADAPTOR_CFG="${ADAPTOR_CONFIG_DIR}/${GFILES_ADAPTOR_CONFIG}"


check_if_root () {
	local MY_EUID=$(id -u)
	if [ -n "$MY_EUID" -a $MY_EUID -ne 0 ]; then
		echo "${PROGNAME}: this program must be run as root" 1>&2
		exit 2
	fi
}

case "$PROGNAME" in
	setup-gk-app-g-files)
		check_if_root

		KC_ID=$(jq -r .resource "$GFILES_ADAPTOR_CFG")
		KC_SECRET=$(jq -r .credentials.secret "$GFILES_ADAPTOR_CFG")
		KC_URL=$(jq -r '."auth-server-url"' "$GFILES_ADAPTOR_CFG")
		KC_REALM=$(jq -r .realm "$GFILES_ADAPTOR_CFG")
		pushd /usr/share/grommunio-files > /dev/null
		sudo -u grofiles ./occ user_oidc:provider 'grommunio Keycloak' --clientid "$KC_ID" --clientsecret "$KC_SECRET" --discoveryuri "${KC_URL}realms/${KC_REALM}/.well-known/openid-configuration" --scope "openid profile" --unique-uid=0 --send-id-token-hint=1 --mapping-uid='preferred_username' --mapping-display-name=name --mapping-email=email --check-bearer=0 --group-provisioning=0
		#echo -n "Restarting/reloading g-files..."
		#systemctl try-reload-or-restart grommunio-files
		#echo " done."
		# Clean up stragglers
		shred "${ADAPTOR_CONFIG_DIR}/${GFILES_ADAPTOR_CONFIG}" || true
		rm -vf "${ADAPTOR_CONFIG_DIR}/${GFILES_ADAPTOR_CONFIG}" || true
		rm -vf "${ADAPTOR_CONFIG_DIR}/${GFILES_ADAPTOR_PUBKEY}" || true
		;;
	delete-gk-app-g-files)
		check_if_root
		echo -n "Deleting grommunio-files 'grommunio Keycloak' client..."
		pushd /usr/share/grommunio-files > /dev/null
		sudo -u grofiles ./occ user_oidc:provider:delete 'grommunio Keycloak' --force
		popd
		#echo -n "Restarting/reloading g-files..."
		#systemctl try-reload-or-restart grommunio-files
		#echo " done."
		;;
esac


