#!/bin/bash

set -e
eval "$(ucr shell)"
. /usr/share/univention-lib/ucr.sh

while [ $# -gt 0 ]; do
	case "$1" in
		"--error-file")
			shift
			errorfile="$1"
			shift
			;;
		"--old-version")
			shift
			old_version="$1"
			shift
			;;
		"--version")
			shift
			version="$1"
			shift
			;;
		*)
			shift
			;;
	esac
done

# set the default for the appsetting for updates
if [ -n "$old_version" ]; then
        if dpkg --compare-versions "$old_version" lt 26.7.0-nubus1; then
                ucr set keycloak/deploy/resources/limits/memory="3g"
        fi
fi

if ! is_ucr_false keycloak/check-postgres-version; then

	# check for postgres >= 12 since Keycloak 26
	if [ -n "$old_version" ]; then

		if dpkg --compare-versions "$old_version" lt 26.1.4-ucs1; then

			# upgrade path: a database configuration should already exist
			postgres="$(python3 -c '
import sys
import json

from univention.udm import UDM

udm = UDM.machine().version(2)

keycloak_data_objs = list(udm.get("settings/data").search("cn=keycloak"))
if keycloak_data_objs:
    keycloak_data_obj = keycloak_data_objs[0]
else:
    sys.exit(0)

data = json.loads(keycloak_data_obj.props.data.raw)

# just check postgres
if not data.get("driver", "") == "org.postgresql.Driver":
    sys.exit(0)

username = data["username"]
password = data["password"]
uri_parts = data["uri"].split("postgresql://")

if uri_parts:
    uri = uri_parts[1]
else:
    sys.exit(0)

import psycopg2
db_connection_string = "postgresql://%s:%s@%s" % (username, password, uri)
conn = psycopg2.connect(db_connection_string)


print(str(conn.server_version)[:-4])
')"
			if [ -n "$postgres" ] && [ "$postgres" -lt 12 ]; then
				echo "It seems you are using Postgres $postgres as the database management system for Keycloak." >> "$errorfile"
				echo "Starting with Keycloak 26, at least Postgres 12 is required." >> "$errorfile"
				echo "Please update Postgres. You may want to follow this article: <a href=""https://help.univention.com/t/updating-from-postgresql-11-to-postgresql-15/22162 target="_blank">https://help.univention.com/t/updating-from-postgresql-11-to-postgresql-15/22162</a>" >> "$errorfile"
				echo 'You can skip this test with by setting ucr variable "keycloak/check-postgres-version" to "false".' >>"$errorfile"
				echo "But be aware that Keycloak 26 will not work with PostgreSQL 11." >> "$errorfile"
				exit 1
			fi
		fi
	# else: no keycloak data or no postgresql:// in database uri. second case is cleary ok, first case should not happen, but handling it is out of scope of this check
	else
		# new installation. getting database information is more a heuristic as we do not have access to App Settings
		# we _assume_ that the Keycloak installation would be configured against a local Postgres...
		set +e
		dpkg-query -W -f '${Status}' postgresql-11 | grep -q ^install
		p11="$?"
		dpkg-query -W -f '${Status}' postgresql-15 | grep -q ^install
		p15="$?"
		set -e
		if [ "$p11" = "0" ] && [ "$p15" = "1" ]; then
			echo "We cannot reliably determine the database management system you will be using. But it may be that you would be using Postgres 11." >> "$errorfile"
			echo "Starting with Keycloak 26, at least Postgres 12 is required." >> "$errorfile"
			echo "Please update Postgres. You may want to follow this article: <a href=""https://help.univention.com/t/updating-from-postgresql-11-to-postgresql-15/22162 target="_blank">https://help.univention.com/t/updating-from-postgresql-11-to-postgresql-15/22162</a>" >> "$errorfile"
			echo 'You can skip this test with by setting ucr variable "keycloak/check-postgres-version" to "false".' >>"$errorfile"
			echo "But be aware that Keycloak 26 will not work with PostgreSQL 11." >> "$errorfile"
			exit 1
		fi
	fi
fi


# create password
pwdfile="/etc/keycloak.secret"
[ -e "$pwdfile" ] || makepasswd --chars 20 > "$pwdfile"
chmod 640 "$pwdfile"

default_sso_fqdn="ucs-sso-ng.$(ucr get domainname)"
ussl_path="/etc/univention/ssl"
[[ "$default_sso_fqdn" != ${default_sso_fqdn,,} ]] && ln -s "$ussl_path/$default_sso_fqdn" "$ussl_path/${default_sso_fqdn,,}" || true

# apache template
keycloak_template_path=/etc/univention/templates/files/etc/apache2/sites-available/univention-keycloak.conf
echo "Installing univention-keycloak apache template"
	cat <<%EOF >"$keycloak_template_path"
@%@UCRWARNING=# @%@

@!@
import os.path
sso_fqdn = configRegistry.get('keycloak/server/sso/fqdn', 'ucs-sso-ng.%s' % configRegistry.get('domainname'))
config = {'ssofqdn': sso_fqdn}

# check if we need to create a keycloak apache config
if configRegistry.is_true('keycloak/apache/config', True):

    fqdn = '%s.%s' % (configRegistry.get('hostname'), configRegistry.get('domainname'))
    kc_fqdn = configRegistry.get('keycloak/server/sso/fqdn')
    sso_path = configRegistry.get('keycloak/server/sso/path', '/').rstrip('/')

    proxy_config = f'''
    ProxyPreserveHost On
    RequestHeader set X-Forwarded-Proto "https"
    RequestHeader set X-Forwarded-Port "443"
    ProxyPass {sso_path}/ http://127.0.0.1:8180{sso_path}/
    ProxyPassReverse {sso_path}/ http://127.0.0.1:8180{sso_path}/
    '''

    ssl_certificate = configRegistry.get("keycloak/apache2/ssl/certificate", "/etc/univention/ssl/%s/cert.pem" % sso_fqdn)
    if not os.path.isfile(ssl_certificate):
        ssl_certificate = "/etc/univention/ssl/ucs-sso-ng.ucs.test/cert.pem"
    ssl_certificate_key = configRegistry.get("keycloak/apache2/ssl/key", "/etc/univention/ssl/%s/private.key" % sso_fqdn)
    if not os.path.isfile(ssl_certificate_key):
        ssl_certificate_key = "/etc/univention/ssl/ucs-sso-ng.ucs.test/private.key"
    ssl_ca_certificate = configRegistry.get("keycloak/apache2/ssl/ca", "/etc/univention/ssl/ucsCA/CAcert.pem")

    config.update({
        "fqdn": fqdn,
        "kc_fqdn": kc_fqdn,
        "sso_path": sso_path,
        "ssl_certificate": ssl_certificate,
        "ssl_certificate_key": ssl_certificate_key,
        "ssl_ca_certificate": ssl_ca_certificate,
        "custom_CSP": configRegistry.get('keycloak/csp/frame-ancestors', ''),
        "cookies_samesite": configRegistry.get('keycloak/cookies/samesite', 'None'),
        "domain": configRegistry.get('domainname'),
        "proxy_config": proxy_config,
    })

    # header and content policy settings
    print('''
<If "%%{HTTP_HOST} == '%(kc_fqdn)s' &&  %%{REQUEST_URI} =~ m#^%(sso_path)s/.*#  && %%{HTTPS} == \'on\'">
       Header edit Content-Security-Policy " *frame-ancestors [^;]*;" " frame-ancestors \'self\' https://*.%(domain)s https://login.microsoftonline.com %(custom_CSP)s; "
       Header edit Set-Cookie ^(.*)$ \$1;Secure;SameSite=%(cookies_samesite)s
</If>
''' % config)  # noqa: W605

    # non-virtual host config
    if not configRegistry.is_true('keycloak/server/sso/virtualhost', True):
        print('''
RewriteCond %%{HTTPS} off
RewriteRule ^%(sso_path)s/$ https://%%{HTTP_HOST}%%{REQUEST_URI} [L,R=301]

<IfModule mod_ssl.c>
    %(proxy_config)s
</IfModule>
IncludeOptional /var/lib/univention-appcenter/apps/keycloak/data/local-univention-keycloak.conf
''' % config)

    # virtual host config
    else:
        print('''
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName %(ssofqdn)s

    SSLEngine on
    SSLProxyEngine on''' % config)

        # check if cert files exist
        if os.path.isfile(config["ssl_certificate"]):
            print("    SSLCertificateFile %(ssl_certificate)s" % config)
        if os.path.isfile(config["ssl_certificate_key"]):
            print("    SSLCertificateKeyFile %(ssl_certificate_key)s" % config)
        if os.path.isfile(config["ssl_ca_certificate"]):
            print("    SSLCACertificateFile %(ssl_ca_certificate)s" % config)

        print('''
    Alias "/univention" "/var/www/univention"
    Alias "/favicon.ico" "/var/www/favicon.ico"
    ProxyPass /univention !
    ProxyPass /favicon.ico !
    %(proxy_config)s

    RewriteEngine on
    RewriteCond %%{HTTP_HOST} ^%(ssofqdn)s$
    RewriteCond %%{REQUEST_URI} ^/univention/(login|management|self-service|portal|server-overview)/$
    RewriteRule ^/univention/(.*)$ %%{REQUEST_SCHEME}://%(fqdn)s/univention/\$1 [L,QSA,R=301,END]
    IncludeOptional /var/lib/univention-appcenter/apps/keycloak/data/local-univention-keycloak.conf
</VirtualHost>
<VirtualHost *:80>
   ServerName %(ssofqdn)s

   Alias /.well-known/acme-challenge/ /var/www/.well-known/acme-challenge/

   <Directory /var/www/.well-known/acme-challenge/>
       AllowOverride None
       Options +FollowSymLinks
       Require all granted
   </Directory>

   RewriteEngine On
   RewriteRule ^/(?!\\.well-known/acme-challenge/) https://%(ssofqdn)s%%{REQUEST_URI} [R=301,L]
</VirtualHost>
</IfModule>
''' % config)  # noqa: W605
@!@

%EOF
chmod 644 "$keycloak_template_path"

# keycloak settings/data acl
mkdir -p /var/lib/univention-appcenter/apps/keycloak/conf/
keycloak_acl_path=/var/lib/univention-appcenter/apps/keycloak/conf/67keycloak.acl
echo "Installing Keycloak data/settings acl"
	cat <<%EOF >"$keycloak_acl_path"
@!@
from univention.lib.misc import custom_groupname
from ldap.dn import escape_dn_chars
base = configRegistry['ldap/base']
domain_admins = escape_dn_chars(custom_groupname('Domain Admins'))

print('''

access to filter="(&(univentionObjectType=settings/data)(cn=keycloak))" attrs=univentionData
   by group/univentionGroup/uniqueMember="cn=%s,cn=groups,%s" read
   by set="user/univentionObjectType & [computer/domaincontroller_master]" read
   by set="user/univentionObjectType & [computer/domaincontroller_backup]" read
   by * none
''' % (domain_admins, base))
@!@

%EOF
chmod 644 "$keycloak_acl_path"

# apache template info
keycloak_info_path=/etc/univention/templates/info/univention-keycloak.info
echo "Installing Keycloak apache template info"
	cat <<%EOF >"$keycloak_info_path"
Type: file
File: etc/apache2/sites-available/univention-keycloak.conf
User: root
Group: root
Mode: 644
Variables: domainname
Variables: hostname
Variables: keycloak/server/sso/fqdn
Variables: keycloak/server/sso/path
Variables: keycloak/server/sso/virtualhost
Variables: keycloak/apache/config
Variables: keycloak/apache2/ssl/certificate
Variables: keycloak/apache2/ssl/key
Variables: keycloak/apache2/ssl/ca
Variables: keycloak/apache2/ssl/certificatechain
Variables: keycloak/csp/frame-ancestors
Variables: keycloak/cookies/samesite

%EOF
chmod 644 "$keycloak_info_path"

# translation template info
keycloak_translation_info_path_de=/etc/univention/templates/info/messages_de.properties.info
keycloak_translation_info_path_en=/etc/univention/templates/info/messages_en.properties.info
echo "Installing Keycloak translation template info"
	cat <<%EOF >"$keycloak_translation_info_path_de"
Type: file
File: var/lib/univention-appcenter/apps/keycloak/conf/UCS/login/messages/messages_de.properties
Variables: keycloak/login/messages/de/*

%EOF
	cat <<%EOF >"$keycloak_translation_info_path_en"
Type: file
File: var/lib/univention-appcenter/apps/keycloak/conf/UCS/login/messages/messages_en.properties
Variables: keycloak/login/messages/en/*

%EOF
chmod 644 "$keycloak_translation_info_path_de"
chmod 644 "$keycloak_translation_info_path_en"

#translation template
keycloak_translation_login_path_de=/etc/univention/templates/files/var/lib/univention-appcenter/apps/keycloak/conf/UCS/login/messages/messages_de.properties
keycloak_translation_login_path_en=/etc/univention/templates/files/var/lib/univention-appcenter/apps/keycloak/conf/UCS/login/messages/messages_en.properties
mkdir -p /etc/univention/templates/files/var/lib/univention-appcenter/apps/keycloak/conf/UCS/login/messages/
echo "Installing Keycloak transaltion template"
	cat <<%EOF >"$keycloak_translation_login_path_de"
@%@UCRWARNING=# @%@
tryAgain=Erneut versuchen
updatePasswordTitle=Das Passwort ist abgelaufen und muss erneuert werden.
loginTitleHtml=Anmelden bei @%@domainname@%@
loginTitle=Univention Corporate Server Single-Sign On
accountDisabled=Das Benutzerkonto ist deaktiviert.
accountExpired=Das Benutzerkonto ist abgelaufen.
accountLocked=Das Benutzerkonto ist gesperrt.
invalidUserMessage=Authentisierung ist fehlgeschlagen. Bitte melden Sie sich erneut an.
@!@
for key in configRegistry:
    if key.startswith('keycloak/login/messages/de/'):
        name = key.split('keycloak/login/messages/de/')[1]
        value = configRegistry[key]
        print(f"{name}={value}")
@!@

%EOF
	cat <<%EOF >"$keycloak_translation_login_path_en"
@%@UCRWARNING=# @%@
tryAgain=Try again
updatePasswordTitle=The password has expired and must be renewed.
loginTitleHtml=Login at @%@domainname@%@
loginTitle=Univention Corporate Server Single-Sign On
accountDisabled=The account is disabled.
accountExpired=The account has expired.
accountLocked=The account is locked.
invalidUserMessage=The authentication has failed, please login again.
@!@
for key in configRegistry:
    if key.startswith('keycloak/login/messages/en/'):
        name = key.split('keycloak/login/messages/en/')[1]
        value = configRegistry[key]
        print(f"{name}={value}")
@!@

%EOF
chmod 644 "$keycloak_translation_login_path_de"
chmod 644 "$keycloak_translation_login_path_en"
ucr commit /var/lib/univention-appcenter/apps/keycloak/conf/UCS/login/messages/messages_de.properties
ucr commit /var/lib/univention-appcenter/apps/keycloak/conf/UCS/login/messages/messages_en.properties

# postgresql 11 template
postgresql_keycloak_template_path=/etc/univention/templates/files/etc/postgresql/11/main/pg_hba.conf.d/50-keycloak.conf
mkdir -p "$(dirname "$postgresql_keycloak_template_path")"
echo "Installing 50-keycloak postgresql 11 template"
	cat <<%EOF >"$postgresql_keycloak_template_path"
@!@
ips = configRegistry.get('keycloak/database/connection', '0.0.0.0/0')
for ip in ips.split():
    print('host    keycloak         keycloak         %s          md5' % ip)
@!@

%EOF
chmod 644 "$postgresql_keycloak_template_path"

# postgresql 15 template
postgresql_keycloak_template_path=/etc/univention/templates/files/etc/postgresql/15/main/pg_hba.conf.d/50-keycloak.conf
mkdir -p "$(dirname "$postgresql_keycloak_template_path")"
echo "Installing 50-keycloak postgresql 15 template"
	cat <<%EOF >"$postgresql_keycloak_template_path"
@!@
ips = configRegistry.get('keycloak/database/connection', '0.0.0.0/0')
for ip in ips.split():
    print('host    keycloak         keycloak         %s          md5' % ip)
@!@

%EOF
chmod 644 "$postgresql_keycloak_template_path"

# postgresql 17 template
postgresql_keycloak_template_path=/etc/univention/templates/files/etc/postgresql/17/main/pg_hba.conf.d/50-keycloak.conf
mkdir -p "$(dirname "$postgresql_keycloak_template_path")"
echo "Installing 50-keycloak postgresql 17 template"
	cat <<%EOF >"$postgresql_keycloak_template_path"
@!@
ips = configRegistry.get('keycloak/database/connection', '0.0.0.0/0')
for ip in ips.split():
    print('host    keycloak         keycloak         %s          md5' % ip)
@!@

%EOF
chmod 644 "$postgresql_keycloak_template_path"

# postgresql template info
pg_keycloak_info_path=/etc/univention/templates/info/50-keycloak.info
echo "Installing 50-keycloak postgresql template info"
	cat <<%EOF >"$pg_keycloak_info_path"
Type: subfile
Multifile: etc/postgresql/11/main/pg_hba.conf
Subfile: etc/postgresql/11/main/pg_hba.conf.d/50-keycloak.conf
Variables: keycloak/database/connection

Type: subfile
Multifile: etc/postgresql/15/main/pg_hba.conf
Subfile: etc/postgresql/15/main/pg_hba.conf.d/50-keycloak.conf
Variables: keycloak/database/connection

Type: subfile
Multifile: etc/postgresql/17/main/pg_hba.conf
Subfile: etc/postgresql/17/main/pg_hba.conf.d/50-keycloak.conf
Variables: keycloak/database/connection

%EOF
chmod 644 "$pg_keycloak_info_path"

# keycloak ispn configuration template
keycloak_template_ispn_conf_path=/var/lib/univention-appcenter/apps/keycloak/conf/cache-ispn-jdbc-ping-template.xml
echo "Installing keycloak ispn configuration template"
cat <<'%EOF' >"$keycloak_template_ispn_conf_path"
<?xml version="1.0" encoding="UTF-8"?>
<infinispan
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:infinispan:config:11.0 http://www.infinispan.org/schemas/infinispan-config-11.0.xsd"
    xmlns="urn:infinispan:config:11.0">

  <!-- custom stack goes into the jgroups element -->
  <jgroups>
    <stack name="jdbc-ping-tcp" extends="tcp">
      <TCP external_addr="${env.JGROUPS_DISCOVERY_EXTERNAL_IP}" bind_port="7600" />
      <JDBC_PING connection_driver="${env.KC_DB_DRIVER}"
                 connection_username="${env.KC_DB_USERNAME}" connection_password="${env.KC_DB_PASSWORD}"
                 connection_url="${env.KC_DB_URL}"
		 initialize_sql="CREATE TABLE IF NOT EXISTS JGROUPSPING (own_addr varchar(200) NOT NULL, bind_addr VARCHAR(200) NOT NULL, created timestamp NOT NULL, cluster_name varchar(200) NOT NULL, ping_data ${env.KC_DB_PING_DATATYPE}, constraint PK_JGROUPSPING PRIMARY KEY (own_addr, cluster_name));"
		 insert_single_sql="INSERT INTO JGROUPSPING (own_addr, bind_addr, created, cluster_name, ping_data) values (?,'${env.JGROUPS_DISCOVERY_EXTERNAL_IP:127.0.0.1}',NOW(), ?, ?);"
		 delete_single_sql="DELETE FROM JGROUPSPING WHERE own_addr=? AND cluster_name=?;"
		 select_all_pingdata_sql="SELECT ping_data FROM JGROUPSPING WHERE cluster_name=?;"
                 info_writer_sleep_time="500"
                 remove_all_data_on_view_change="true"
                 stack.combine="REPLACE"
                 stack.position="MPING" />
    </stack>
  </jgroups>

  <cache-container name="keycloak">
    <!-- custom stack must be referenced by name in the stack attribute of the transport element -->
    <transport lock-timeout="60000" stack="jdbc-ping-tcp"/>
    <local-cache name="realms">
      <encoding>
        <key media-type="application/x-java-object"/>
        <value media-type="application/x-java-object"/>
      </encoding>
      <memory max-count="10000"/>
    </local-cache>
    <local-cache name="users">
      <encoding>
        <key media-type="application/x-java-object"/>
        <value media-type="application/x-java-object"/>
      </encoding>
      <memory max-count="10000"/>
    </local-cache>
    <distributed-cache name="sessions" owners="2">
      <expiration lifespan="-1"/>
    </distributed-cache>
    <distributed-cache name="authenticationSessions" owners="2">
      <expiration lifespan="-1"/>
    </distributed-cache>
    <distributed-cache name="offlineSessions" owners="2">
      <expiration lifespan="-1"/>
    </distributed-cache>
    <distributed-cache name="clientSessions" owners="2">
      <expiration lifespan="-1"/>
    </distributed-cache>
    <distributed-cache name="offlineClientSessions" owners="2">
      <expiration lifespan="-1"/>
    </distributed-cache>
    <distributed-cache name="loginFailures" owners="2">
      <expiration lifespan="-1"/>
    </distributed-cache>
    <local-cache name="authorization">
      <encoding>
        <key media-type="application/x-java-object"/>
        <value media-type="application/x-java-object"/>
      </encoding>
      <memory max-count="10000"/>
    </local-cache>
    <replicated-cache name="work">
      <expiration lifespan="-1"/>
    </replicated-cache>
    <local-cache name="keys">
      <encoding>
        <key media-type="application/x-java-object"/>
        <value media-type="application/x-java-object"/>
      </encoding>
      <expiration max-idle="3600000"/>
      <memory max-count="1000"/>
    </local-cache>
    <distributed-cache name="actionTokens" owners="2">
      <encoding>
        <key media-type="application/x-java-object"/>
        <value media-type="application/x-java-object"/>
      </encoding>
      <expiration max-idle="-1" lifespan="-1" interval="300000"/>
      <memory max-count="-1"/>
    </distributed-cache>
  </cache-container>
</infinispan>

%EOF
chmod 644 "$keycloak_template_ispn_conf_path"

exit 0
