#!/bin/bash

# shellcheck source=/dev/null
[ -e /usr/share/univention-lib/ucr.sh ] && . /usr/share/univention-lib/ucr.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

#if is_ucr_true keycloak/ucs/setup; then
#	setup_ucs
#fi

if [ "$action" = "settings" ]; then
	univention-app reinitialize keycloak
fi
