#!/bin/bash

set -x

VERSION=1
SERVICE="Mattermost"

. /usr/share/univention-join/joinscripthelper.lib
. /usr/share/univention-appcenter/joinscripthelper.sh
. /usr/share/univention-lib/ldap.sh
. /usr/share/univention-lib/base.sh

joinscript_init
eval "$(ucr shell)"

HOST="https://${hostname}.${domainname}:8234/"
DATADIR="/var/lib/univention-appcenter/apps/mattermost/data"
CONFIG_JSON="${DATADIR}/config/config.json"

LDAP_BIND_DN="$appcenter_apps_mattermost_hostdn"
LDAP_BIND_PW_FILE="$(joinscript_container_file /etc/machine.secret)"
LDAP_BIND_PW="$(< $LDAP_BIND_PW_FILE)"

CONFIG="$(joinscript_container_file /etc/univention/base.conf)"
ADM_PASSWORD="$(sed -n 's/^mattermost\/password: \(.*\)/\1/p' $CONFIG)"

CAFILE="$(joinscript_container_file /usr/local/share/ca-certificates/ucsCA.crt)"
cp /etc/univention/ssl/ucsCA/CAcert.pem "$CAFILE"
joinscript_run_in_container update-ca-certificates --fresh

ucs_addServiceToLocalhost "${SERVICE}" "$@"

# resolve ip for ldap host to avoid dns problems in docker
ldapip=$(getent ahostsv4 ${hostname}.${domainname}  | head -n 1 | cut -d ' ' -f 1)

# The App Center registers the schema automatically
# joinscript_register_schema "$@"

# create special apache config (should ideally use a subdomain, but we'll settle for a custom port for now)
cat <<-EOF >"/etc/apache2/sites-available/mattermost.conf"

##################################################
# generated by join script, do not edit manually #
##################################################

<VirtualHost *:8123>
        ServerName ${hostname}.${domainname}
        ServerAdmin webmaster@example.org

        ErrorLog \${APACHE_LOG_DIR}/mattermost-error.log
        CustomLog \${APACHE_LOG_DIR}/mattermost-access.log combined

        # Enforce HTTPS:
        RewriteEngine On
        RewriteCond %{HTTPS} !=on
        RewriteRule ^/?(.*) https://%{SERVER_NAME}:8234/$1 [R,L]
</VirtualHost>

<VirtualHost *:8234>
        SSLEngine on
        ServerName ${hostname}.${domainname}
        ServerAdmin webmaster@example.org

        SSLCertificateFile /etc/univention/ssl/${hostname}.${domainname}/cert.pem
        SSLCertificateKeyFile /etc/univention/ssl/${hostname}.${domainname}/private.key
        SSLCACertificateFile /etc/univention/ssl/ucsCA/CAcert.pem

        ErrorLog \${APACHE_LOG_DIR}/mattermost-error.log
        CustomLog \${APACHE_LOG_DIR}mattermost-access.log combined

        RewriteEngine On
        RewriteCond %{REQUEST_URI} ^/api/v1/websocket [NC,OR]
        RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR]
        RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
        RewriteRule .* ws://127.0.0.1:8065%{REQUEST_URI} [P,QSA,L]
        RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
        RewriteRule .* http://127.0.0.1:8065%{REQUEST_URI} [P,QSA,L]
        RequestHeader set X-Forwarded-Proto "https"

        RequestHeader unset If-Modified-Since
        RequestHeader unset If-None-Match

        <LocationMatch "/api/(?<version>v[0-9]+)/(?<users>users/)?websocket$">
                Require all granted
                ProxyPassReverse ws://127.0.0.1:8065/api/%{env:MATCH_VERSION}/%{env:MATCH_USERS}websocket
                ProxyPassReverseCookieDomain 127.0.0.1 ${hostname}.${domainname}
        </LocationMatch>
        <Location />
                Require all granted
                ProxyPassReverse http://127.0.0.1:8065/
                ProxyPassReverseCookieDomain 127.0.0.1 ${hostname}.${domainname}
        </Location>

        ProxyPreserveHost On
        ProxyRequests Off
</VirtualHost>
EOF

cat <<-EOF >"/etc/apache2/ucs-sites.conf.d/mattermost.conf"

###########################################################
# generated by code app join script, do not edit manually #
###########################################################

Redirect 301 /mattermost http://${hostname}.${domainname}:8123
EOF

# add custom ports to ports.conf
grep -q -F 'Listen 8123' /etc/apache2/ports.conf || echo 'Listen 8123' >> /etc/apache2/ports.conf
grep -q -F 'Listen 8234' /etc/apache2/ports.conf || echo 'Listen 8234' >> /etc/apache2/ports.conf

a2enmod rewrite proxy proxy_http proxy_wstunnel
a2ensite mattermost
invoke-rc.d apache2 reload

# add custom ports to firewall
ucr set \
	security/packetfilter/package/mattermost/tcp/8123/all="ACCEPT" \
	security/packetfilter/package/mattermost/tcp/8123/all/en="Mattermost http" \
	security/packetfilter/package/mattermost/tcp/8234/all="ACCEPT" \
	security/packetfilter/package/mattermost/tcp/8234/all/en="Mattermost https" \
	security/packetfilter/package/mattermost/tcp/465/all="ACCEPT" \
	security/packetfilter/package/mattermost/tcp/465/all/en="SSMTP"
[ -x "/etc/init.d/univention-firewall" ] && invoke-rc.d univention-firewall restart

# create dialog in user manager to make users mattermost users
univention-directory-manager settings/extended_attribute create "$@" \
	--position "cn=custom attributes,cn=univention,$ldap_base" \
	--set name='mattermostUserActivated' \
	--set module=users/user \
	--set tabName='Mattermost' \
	--set shortDescription='Create user in Mattermost (requires Mattermost E10 & E20). The user must have a primary mailaddress' \
	--set longDescription='The user can login to Mattermost using his Univention credentials (only possible with Mattermost E10 and E20)' \
	--set translationShortDescription='"de_DE" "Benutzer in Mattermost erstellen (Benötigt Mattermost E10 & E20).  Der Benutzer muss eine primäre Mailadresse besitzen"' \
	--set translationLongDescription='"de_DE" "Der Benutzer kann mit seinen Univention Zugangsdaten auf Mattermost zugreifen (nur möglich in Mattermost E10 und E20)"' \
	--set objectClass='mattermostUser' \
	--set syntax=boolean \
	--set mayChange=1 \
	--set ldapMapping='mattermostActivated' \
	--set multivalue=0 \
	--set tabPosition=1 \
	--set default=1

# add links to mattermost for convenience
PORTAL="ucs/web/overview/entries/admin/mattermost"
ucr set \
  ${PORTAL}/description="Mattermost login" \
  ${PORTAL}/description/de="Login für Mattermost" \
  ${PORTAL}/label?"Mattermost" \
  ${PORTAL}/label/de?"Mattermost" \
  ${PORTAL}/link="$HOST" \
  ${PORTAL}/priority?95

PORTAL="ucs/web/overview/entries/admin/mattermost-doc"
ucr set \
  ${PORTAL}/description="Mattermost Admin Documentation" \
  ${PORTAL}/description/de="Mattermost Admin Dokumentation" \
  ${PORTAL}/icon?"/univention/js/dijit/themes/umc/icons/scalable/apps-mattermost_20170915113130.svg" \
  ${PORTAL}/label?"Mattermost Documentation" \
  ${PORTAL}/label/de?"Mattermost Dokumentation" \
  ${PORTAL}/link="https://documentation.kopano.io/kopano_mattermost_manual/" \
  ${PORTAL}/priority?100

echo "waiting for Mattermost startup"
until $(curl -k -f -s -o /dev/null -XPOST http://127.0.0.1:8065/api/v4/users/logout); do
	printf '.'
	sleep 5
done

joinscript_run_in_container mattermost-platform version

# Get localized username for Administrator
adminuser="$(custom_username Administrator)"
adminuser_dn="$(ucs_convertUID2DN $adminuser)"

# Mailaddress set for admin?
if udm users/user list "$@" --filter uid="$adminuser" | grep -q "mailPrimaryAddress: None"; then
	# create initial mail domain object(s) if missing
	# Default; create new object with $domainname as mail domain
	# can be overridden by mail/default/domains
	domain_list="$domainname"
	domain="$domainname"
	if [ "$mail_default_domains" ] ; then
		domain_list="$mail_default_domains"
	fi
	if ! udm mail/domain list "$@" | grep -q "^DN:"; then
		# no mail domain object found


		# 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
			udm mail/domain create "$@" --ignore_exists \
				--position "cn=domain,cn=mail,$ldap_base" \
				--set name="$domain" || die
		done
	fi

	# set default mailaddress
	udm users/user modify "$@" --dn "$adminuser_dn" --set mailPrimaryAddress="Administrator@$domain"
fi

email=$(univention-ldapsearch -LLL uid=administrator mailPrimaryAddress  | grep "^mailPrimaryAddress: " | sed s/"^mailPrimaryAddress: "// | head -n1)

if [ ! -e $DATADIR/init ]; then
	# precreate an admin user
	joinscript_run_in_container mattermost-platform user create --email="$email" --password="$ADM_PASSWORD" --username=Administrator --system_admin
	joinscript_run_in_container mattermost-platform team create --name univention --display_name "Univention default team"
	joinscript_run_in_container mattermost-platform team add univention Administrator
	touch $DATADIR/init
else
	joinscript_run_in_container mattermost-platform user password Administrator "$ADM_PASSWORD"
fi

# configuring mattermost

# how mattermost modifies their config https://github.com/mattermost/mattermost-server/blob/1222e6cd4172657143202882e7189274352e2cd5/Makefile#L396-L404
sed -i'' -e 's|"SiteURL": "",|"SiteURL": "'$HOST'",|g' \
$CONFIG_JSON

# Enterprise version specific, only works with license
sed -i'' -e 's|"LdapServer": "",|"LdapServer": "'${ldapip}'",|g' \
 -e 's|"LdapPort": 389,|"LdapPort": 7389,|g' \
 -e 's|"BaseDN": "",|"BaseDN": "'${ldap_base}'",|g' \
 -e 's|"BindUsername":.*|"BindUsername": "'${LDAP_BIND_DN}'",|g' \
 -e 's|"BindPassword":.*|"BindPassword": "'${LDAP_BIND_PW}'",|g' \
 -e 's|"UserFilter": "",|"UserFilter": "(\&(objectClass=mattermostUser)(mattermostActivated=1))",|g' \
 -e 's|"FirstNameAttribute": "",|"FirstNameAttribute": "givenName",|g' \
 -e 's|"LastNameAttribute": "",|"LastNameAttribute": "sn",|g' \
 -e 's|"EmailAttribute": "",|"EmailAttribute": "mailPrimaryAddress",|g' \
 -e 's|"UsernameAttribute": "",|"UsernameAttribute": "uid",|g' \
 -e 's|"IdAttribute": "",|"IdAttribute": "uid",|g' \
 -e 's|"SyncIntervalMinutes": 60,|"SyncIntervalMinutes": 60,|g' $CONFIG_JSON

# Enable ldap auth by default (only has an effect with ldap license)
sed -i -e "/\LdapSettings/,/Enable/ s/false/true/" $CONFIG_JSON


# configure mail relay
echo "configuring mail relay"
ucr set mail/postfix/inet/interfaces=all \
		mail/postfix/virtual/enabled=true \
		mail/postfix/ldap/timeout=mail_postfix_ldap_timeout # workaround to rewrite postfix ldap configfiles for appliance
service postfix restart

sed -i'' \
 -e 's|"SendEmailNotifications": false,|"SendEmailNotifications": true,|g' \
 -e 's|"SMTPServer": "",|"SMTPServer": "'${hostname}.${domainname}'",|g' \
 -e 's|"SMTPPort": "",|"SMTPPort": "465",|g' \
 -e '/\EmailSettings/,/ConnectionSecurity/ s/"ConnectionSecurity": ""/"ConnectionSecurity": "TLS"/' \
 $CONFIG_JSON

# disable for now since sending does not seem to work
# 	 -e 's|"RequireEmailVerification": false,|"RequireEmailVerification": true,|g' \

joinscript_save_current_version
exit 0
