#!/bin/bash
#
# App join script
#
# Copyright 2021 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

## joinscript api: bindpwdfile

VERSION="2"

. /usr/share/univention-join/joinscripthelper.lib
. /usr/share/univention-lib/all.sh

joinscript_init

app_id="keycloak"

ucs_addServiceToLocalhost "$app_id" "$@"

domainname="$(ucr get domainname)"
hostname="$(ucr get hostname)"
ldap_base="$(ucr get ldap/base)"
sso_url="$(ucr get keycloak/server/sso/fqdn)"

url_prefix="$(ucr get keycloak/url/prefix)"
if [ -n "$url_prefix" ]; then
	univention-add-vhost "$url_prefix.$hostname.$domainname" 443 \
	--conffile /var/lib/univention-appcenter/apps/$app_id/config/vhost.conf "$@"
	service apache2 reload
fi

COMPONENT_ID=$(univention-app get $app_id component_id | cut -f 2 -d ':' | tr -d '[:space:]')
ucr set \
	ucs/web/overview/entries/admin/$app_id/description/de="Keycloak" \
	ucs/web/overview/entries/admin/$app_id/description="Keycloak" \
	ucs/web/overview/entries/admin/$app_id/label="Keycloak" \
	ucs/web/overview/entries/admin/$app_id/link="https://$sso_url/admin/" \
	ucs/web/overview/entries/admin/$app_id/icon="/univention/js/dijit/themes/umc/icons/scalable/apps-$COMPONENT_ID.svg" \
	ucs/web/overview/entries/admin/$app_id/link-target='newwindow'

## Only make the portal tile for the Keycloak App visible once a Domain Admin is logged in on the portal
domain_admins_dn=$(univention-ldapsearch -LLL "(&(cn=Domain Admins)(objectClass=univentionGroup))" 1.1 | ldapsearch-decode64 | sed -n 's/^dn: //p')
udm portals/entry modify "$@" \
	--dn "cn=keycloak,cn=entry,cn=portals,cn=univention,$ldap_base" \
	--append allowedGroups="$domain_admins_dn" || die

eval "$(ucr shell)"

# check if we need to create a new certificate
if [ "$server_role" = "domaincontroller_master" ]; then
	if [ -z "$keycloak_server_sso_certificate_generation" ] || is_ucr_true keycloak/server/sso/certificate/generation; then
		univention-certificate new -name "${keycloak_server_sso_fqdn}" -days "${ssl_default_days:-1825}" || die
		create_or_download=true
	fi
else
	if [ -z "$keycloak_server_sso_certificate_download" ] || is_ucr_true keycloak/server/sso/certificate/download; then
		ucs_parseCredentials "$@"
		NAMETMP=${binddn:4} # Remove uid=
		HOSTACCOUNT=${NAMETMP%%,*} # remove from first , to end
#       univention-ssh $bindpwdfile $HOSTACCOUNT@$ldap_master "/usr/sbin/univention-certificate new -name "${keycloak_server_sso_fqdn}" -days "${ssl_default_days:-1825}""
		univention-scp $bindpwdfile "-r $HOSTACCOUNT@$ldap_master:/etc/univention/ssl/${keycloak_server_sso_fqdn}/ /etc/univention/ssl/" || die
		create_or_download=true
	fi
fi


# Re-create Apache configuration after the certificate generation

[ -x /usr/sbin/univention-config-registry ] && univention-config-registry register univention-keycloak || true
ucr commit /etc/apache2/sites-available/univention-keycloak.conf
a2ensite univention-keycloak
systemctl restart apache2

sso_hostname="$(echo "$keycloak_server_sso_fqdn"  | cut -d '.' -f 1)"
sso_domainname="$(echo "$keycloak_server_sso_fqdn"  | cut -d '.' -f 2-)"

if [ -z "$keycloak_server_sso_autoregistration" ] || is_ucr_true keycloak/server/sso/autoregistration; then
	/usr/share/univention-directory-manager-tools/univention-dnsedit "$@" --ignore-exists \
		"$sso_domainname" add a "$sso_hostname" "$(get_default_ip_address)" || die
	if is_localhost_in_admember_mode; then
		ucs_parseCredentials "$@"
		if [ -n "$binddn" ] && [ -n "$bindpwdfile" ]; then
			add_host_record_in_ad "$binddn" "" "$bindpwdfile" \
				"$keycloak_server_sso_fqdn" "$(get_default_ip_address)" || die
		fi
	fi
fi

i=0; while [ "$(docker inspect -f "{{.State.Health.Status}}" "keycloak")" != "healthy" ] && [ "$((++i))" -lt 100 ]; do  sleep 2; done; if [ "$i" -eq 100 ]; then echo "ERROR: Container did not come up healthy"; exit 1; fi
univention-keycloak init "$@" || die

joinscript_save_current_version

exit 0
