#!/bin/bash


# shellcheck source=/dev/null
[ -e /usr/share/univention-lib/ucr.sh ] && . /usr/share/univention-lib/ucr.sh
. /usr/share/univention-lib/all.sh

action=$1

if [ -n "$action" ] && [ "$action" = "remove" ]; then
	exit 0
fi

# we need to commit the apache conf because that may have changed during an update
ucr commit /etc/apache2/sites-available/univention-keycloak.conf

service apache2 reload

chmod 640 "/etc/postgresql-keycloak.secret"
chgrp "DC Backup Hosts" "/etc/postgresql-keycloak.secret"
chgrp "DC Backup Hosts" "/etc/keycloak.secret"

data="$(python3 <<-%EOF
import json
from string import Template
from urllib.parse import urlparse

from univention.config_registry import ConfigRegistry, handler_set
from univention.udm import UDM
from univention.udm.binary_props import Base64Bzip2BinaryProperty
from univention.udm.exceptions import NoObject
from univention.appcenter.app_cache import Apps


ucr = ConfigRegistry().load()
fqdn = f'{ucr.get("hostname")}.{ucr.get("domainname")}'
ldap_base = ucr.get('ldap/base')
superordinate = f'cn=univention,{ldap_base}'
app_name = 'keycloak'
mod = UDM.admin().version(2).get('settings/data')
with open('/etc/postgresql-keycloak.secret', 'r') as fd:
    default_password = fd.read().strip()

default_url = f'jdbc:postgresql://{fqdn}:5432/keycloak?sslmode=require'

# (1) get current app settings
app = Apps().find("keycloak")
for setting in app.get_settings():
    if setting.name == "kc/db/url":
        kc_db_url = setting.get_value(app)
    if setting.name == "kc/db/password":
        kc_db_password = setting.get_value(app)
    if setting.name == "kc/db/username":
        kc_db_username = setting.get_value(app)
    if setting.name == "keycloak/server/sso/fqdn":
        kc_sso_fqdn = setting.get_value(app)
    if setting.name == "keycloak/server/sso/path":
        kc_sso_path = setting.get_value(app) if setting.get_value(app) else '/'


# (2) get settings from domain config, fallback app settings
try:
    # URL not found in UCR, try in LDAP first
    obj = mod.get(f'cn={app_name},cn=data,{superordinate}')

    data = json.loads(obj.props.data.raw)
    kc_db_url = data['uri'] or kc_db_url
    kc_db_password = data['password'] or kc_db_password
    kc_db_username = data['username'] or kc_db_username
    data['installations'].append(fqdn)
    data['installations'] = list(set(data['installations']))
# (3) no domain settings use app settings (or local defaults) as fallback
except NoObject:
    # URL not found in UCR or LDAP - use current host configuration or defaults
    kc_db_url = kc_db_url or default_url
    cfg = urlparse(kc_db_url)
    kc_db_kind = urlparse(cfg.path).scheme.replace("postgresql", "postgres").replace("sqlserver", "mssql")
    obj = mod.new(superordinate)
    obj.position = f'cn=data,{superordinate}'
    obj.props.name = app_name
    obj.props.data_type = 'string'
    data = {
        'uri': kc_db_url,
        'password': kc_db_password or default_password,
        'username': kc_db_username or app_name,
        'installations': [fqdn],
    }
else:
    cfg = urlparse(kc_db_url)
    kc_db_kind = urlparse(cfg.path).scheme.replace("postgresql", "postgres").replace("sqlserver", "mssql")


raw_value = json.dumps(data).encode('ascii')
obj.props.data = Base64Bzip2BinaryProperty('data', raw_value=raw_value)
obj.save()



print(kc_db_url)
print(kc_db_password or default_password)
print(kc_db_kind)
print(kc_db_username)


# create a policy from keycloak/server/sso/fqdn and keycloak/server/sso/path
# to ucs/server/sso/uri
# only update the policy if the policy matches the old value
if not ucr.is_true('ucs/server/sso/uri/autopolicy', False):
    exit(0)

setting_name = 'ucs/server/sso/uri'
old_value = ucr.get(setting_name)
new_value = f'https://{kc_sso_fqdn}{kc_sso_path}'
policy_name = "sso_uri_domainwide_setting"
mod = UDM.admin().version(2).get('policies/registry')
position = f'cn=config-registry,cn=policies,{ldap_base}'
try:
    # URL not found in UCR, try in LDAP first
    policy_obj = mod.get(f'cn={policy_name},{position}')
    if policy_obj.props.registry and policy_obj.props.registry.get(setting_name) == old_value:
        # update ucr policy
        policy_obj.props.registry = {setting_name: new_value}
        policy_obj.save()
except NoObject:
    # URL not found in UCR or LDAP - use current host configuration or defaults
    policy_obj = mod.new()
    policy_obj.position = position
    policy_obj.props.name = policy_name
    policy_obj.props.registry = {setting_name: new_value}
    policy_obj.save()
    base_obj = UDM.admin().version(2).get('container/dc').get(f'{ldap_base}')
    base_obj.policies += [policy_obj.dn]
    base_obj.save()
handler_set([f'{setting_name}={new_value}'])

%EOF
)" || die
opts=( $(echo -e "$data" | awk -F'\n'  '{print $1, $2}') );
kc_db_url="${opts[0]}"
kc_db_password="${opts[1]}"
kc_db_kind="${opts[2]}"
kc_db_username="${opts[3]}"

# update ucr policies
/usr/lib/univention-directory-policy/univention-policy-update-config-registry

univention-app configure keycloak --set "kc/db/url=$kc_db_url" "kc/db/username=$kc_db_username" "kc/db/password=$kc_db_password" "kc/db/kind=$kc_db_kind" --run-script=no >/dev/null #dont log infos
univention-app reinitialize keycloak

if [ "$action" = "settings" ]; then
	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"
fi

# add UCS rootCA to trusted CA certificates
univention-app shell keycloak keytool -cacerts -import -alias ucsCA -file /etc/pki/ca-trust/extracted/pem/ucsCAcert.pem -storepass "changeit" -noprompt

# add additional ca certificates
docker exec -i -u root keycloak bash <<'EOF'
test -d /var/lib/univention-appcenter/apps/keycloak/conf/ca-certificates || exit 0
while read cert; do
        alias="$(basename "$cert")"
        echo "adding $alias to cacerts cert store"
        keytool -cacerts -import -alias "$alias" -file "$cert" -storepass "changeit" -noprompt || true
done < <(ls /var/lib/univention-appcenter/apps/keycloak/conf/ca-certificates/*.pem)
EOF
