#!/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="4"

. /usr/share/univention-join/joinscripthelper.lib
. /usr/share/univention-lib/all.sh
. /usr/share/univention-ssl/make-certificates.sh

joinscript_init

app_id="keycloak"

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


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

# register LDAP acl to hide settings/data attribute. Contains database password
ucs_registerLDAPExtension "$@" \
	--ucsversionstart "4.4-0" --ucsversionend "5.99-0" \
	--packagename "$app_id" \
	--packageversion "1" \
	--acl "/var/lib/univention-appcenter/apps/$app_id/conf/67keycloak.acl" || die

## as variables were changed we need the new ones
psql_pwd_path="/etc/postgresql-keycloak.secret"
machine_secret="/etc/machine.secret"

eval "$(ucr shell)"
ucs_parseCredentials "$@"
primary="$ldap_master"
# check if we need to create a new certificate
if [ "$server_role" = "domaincontroller_backup" ]; then
	univention-scp "$machine_secret" "-r $hostname\$@$primary:/etc/univention/ssl/${keycloak_server_sso_fqdn}/ /etc/univention/ssl/" || die
	chgrp -R "DC Backup Hosts" "/etc/univention/ssl/$keycloak_server_sso_fqdn/"
fi

keycloak_db_host_dn=$(univention-ldapsearch -LLL univentionService="$app_id DB" 1.1 | sed -ne "s/^dn: //p")
if [ -z "$keycloak_db_host_dn" ]; then
       ucs_addServiceToLocalhost "$app_id DB" "$@"
else
       keycloak_db_host=$(ucs_getAttrOfDN "cn" "$keycloak_db_host_dn")
       univention-scp $machine_secret "-r $hostname\$@$keycloak_db_host:/etc/keycloak.secret /etc/keycloak.secret" || die
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

## TODO: Is this needed on non "master" kc installations ?
[ -x /usr/sbin/univention-config-registry ] && univention-config-registry register 50-keycloak || true
ucr commit /etc/postgresql/11/main/pg_hba.conf
service postgresql restart

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


univention-app restart keycloak
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
echo "Container is healthy, configuring Keycloak"
univention-keycloak --keycloak-url "https://$keycloak_server_sso_fqdn" init || die

for umc in $(univention-ldapsearch -LLL univentionService="Univention Management Console" displayName | sed -n 's/displayName: //p' | tr ";" "\n")
do
	univention-keycloak "$@" --keycloak-url "https://$keycloak_server_sso_fqdn" saml/sp create --metadata-url="https://$umc.$domainname/univention/saml/metadata" --umc-uid-mapper
	if [ "$?" != "0" ]; then
		echo "Error creating a saml serviceprovider for the umc of $umc.$domainname"
	fi

done

# another restart for the cache initialization
univention-app restart keycloak

ucs_addServiceToLocalhost "$app_id" "$@"

joinscript_save_current_version

exit 0
