#!/bin/bash

set -x

VERSION=2
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)"

CONFIG="$(joinscript_container_file /etc/univention/base.conf)"

DATADIR="/var/lib/univention-appcenter/apps/mattermost/data"
CONFIG_JSON="${DATADIR}/config/config.json"

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

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

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)

# fix ports added in the wrong configuration file
if joinscript_check_specific_version_executed 1; then ucr commit /etc/apache2/ports.conf; fi

a2enmod rewrite proxy proxy_http proxy_wstunnel
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 portal (link to actual mattermost will be set by configure_host)
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

# make sure the configure script was properly run (setting hostname could fail initially since the docker container did not yet start)
univention-app configure mattermost

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 valid license file)
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"/' \
 -e 's|"FeedbackEmail": "",|"FeedbackEmail": "'${email}'",|g' \
 $CONFIG_JSON

# setting up automatic backup
cat <<-EOF >"/etc/cron.daily/mattermost-backup"

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

DEST=/var/lib/univention-appcenter/apps/mattermost/data/backup
mkdir -p $DEST
univention-app shell mattermost mysqldump --user=mmuser --password=THISISMYMMDBPASSWORD --databases mattermost > $DEST/mattermost.sql

EOF

chmod +x /etc/cron.daily/mattermost-backup

joinscript_save_current_version
exit 0
