#!/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

apache_config () {
	# create apache config
	mkdir -p  /var/lib/univention-appcenter/apps/keycloak/config/
	cat <<%EOF > /var/lib/univention-appcenter/apps/keycloak/config/vhost.conf
ProxyPreserveHost On
SSLProxyEngine On
SSLProxyCheckPeerCN on
SSLProxyCheckPeerExpire on
RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-Port "443"
ProxyPass / http://127.0.0.1:8180/
ProxyPassReverse / http://127.0.0.1:8180/
%EOF
}

theme_config() {
	THEME_DIR="/usr/share/univention-web/themes"
	THEME_SRC="$THEME_DIR/$(basename "$(ucr get keycloak/theme)").css"
	THEME_DST="/var/lib/univention-appcenter/apps/keycloak/conf/UCS/login/resources/css/theme.css"
	if [ ! -e "$THEME_SRC" ]; then
		echo "$THEME_SRC does not exist"
		exit 1
	fi

	[ -e "$THEME_DST" ] && rm "$THEME_DST"
	cp "$THEME_SRC" "$THEME_DST"
}

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

apache_config
theme_config
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
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'
kc_db_url = None
app = Apps().find("keycloak")
for setting in app.get_settings():
    if setting.name == "kc/db/url":
        kc_db_url = setting.get_value(app) or kc_db_url
    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) or app_name

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 = kc_db_url or data['uri']
    kc_db_password = kc_db_password or data['password']
    kc_db_username = kc_db_username or data['username']
    data['installations'].append(fqdn)
    data['installations'] = list(set(data['installations']))
except NoObject:
    # URL not found in UCR or LDAP - use current host configuration
    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 or default_url,
        'password': kc_db_password or default_password,
        'username': kc_db_username,
        'installations': [fqdn],
    }
raw_value = json.dumps(data).encode('ascii')
obj.props.data = Base64Bzip2BinaryProperty('data', raw_value=raw_value)
obj.save()

kc_db_url = kc_db_url or default_url
cfg = urlparse(kc_db_url)
print(kc_db_url)
print(kc_db_password or default_password)
print(urlparse(cfg.path).scheme.replace("postgresql", "postgres").replace("sqlserver", "mssql"))
print(kc_db_username)
%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]}"

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
