#!/bin/bash
VERSION=5

. /usr/share/univention-appcenter/joinscripthelper.sh

joinscript_init

eval "$(univention-config-registry shell)"

ucs_addServiceToLocalhost "$SERVICE" "$@"

# create initial mail domain object(s) if missing
if ! udm mail/domain list "$@" | grep -q "^DN:" ; then
	# no mail domain object found

        # Default; create new object with $domainname as mail domain
	# can be overridden by mail/default/domains
	domain_list="$domainname"
	if [ "$mail_default_domains" ] ; then
		domain_list="$mail_default_domains"
	fi

	# create required containers
	udm container/cn create "$@" --ignore_exists --position "$ldap_base" --set name="mail" || die
	udm container/cn create "$@" --ignore_exists --position "cn=mail,$ldap_base" --set name="domain" || die

	# create new object
	for domain in $domain_list ; do
                echo "Create new maildomain for $domain."
		udm mail/domain create "$@" --ignore_exists \
			--position "cn=domain,cn=mail,$ldap_base" \
			--set name="$domain" || die
	done
fi

# customize proxy settings
echo "Activate Apache2 module proxy_wstunnel for Rocket.Chat websocket reverse proxy configuration"
a2enmod proxy_wstunnel

echo "Add custom reverse proxy configuration"
port="$(ucr get appcenter/apps/rocketchat/ports/3000)"

cat << EOF > /etc/apache2/ucs-sites.conf.d/rocketchat.conf
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule ^/rocketchat/(.*) ws://127.0.0.1:$port/rocketchat/\$1 [P,L]
RewriteCond %{HTTP:Upgrade} !=websocket [NC]
RewriteRule ^/rocketchat/(.*) http://127.0.0.1:$port/rocketchat/\$1 [P,L]    
EOF
service apache2 reload

# add Rocket.Chat SAML Service Provider to UCS and activate it

udm saml/serviceprovider create "$@" \
    --ignore_exists \
    --position "cn=saml-serviceprovider,cn=univention,$ldap_base" \
    --set isActivated=TRUE \
    --set Identifier="https://$hostname.$domainname/rocketchat/_saml/metadata/UCS" \
    --set NameIDFormat="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" \
    --set simplesamlAttributes=TRUE \
    --set AssertionConsumerService="https://$hostname.$domainname/rocketchat/_saml/validate/UCS" \
    --set singleLogoutService="https://$hostname.$domainname/rocketchat/_saml/logout/UCS" \
    --set simplesamlNameIDAttribute="mailPrimaryAddress" \
    --set LDAPattributes="uid" \
    --set LDAPattributes="mailPrimaryAddress" \
    --set LDAPattributes="cn" \
    --set serviceProviderOrganizationName="Rocket.Chat" \
    --set serviceproviderdescription="Rocket.Chat"


if [[ $saml_idp_ldap_get_attributes != *"cn" ]]; then
    ucr set saml/idp/ldap/get_attributes="$saml_idp_ldap_get_attributes, 'cn'"
fi


joinscript_save_current_version
exit 0
