#!/bin/bash

CONFIG="$(cat /etc/univention/base.conf)"
DATADIR="/var/lib/univention-appcenter/apps/mattermost/data"
CONFIG_JSON="${DATADIR}/config/config.json"

if [ ! -e $CONFIG_JSON ]; then
	echo "Config file does not yet exist. Skipping configure."
	exit 0
fi

CONFIG_HOSTNAME="$(echo "$CONFIG" | sed -n 's/^mattermost\/hostname: \(.*\)/\1/p')"
CONFIG_DOCKERHOST="$(echo "$CONFIG" | sed -n 's/^docker\/host\/name: \(.*\)/\1/p')"
if [ -z ${CONFIG_HOSTNAME} ]; then
	# use default hostname if CONFIG_HOSTNAME is not set
	echo "setting default hostname"
	HOST="https://$CONFIG_DOCKERHOST:8234/"
else
	echo "using custom hostname"
	HOST="https://$CONFIG_HOSTNAME/"
fi

# read value of RequireEmailVerification, default to false if not set
CONFIG_RequireEmailVerification="$(echo "$CONFIG" | sed -n 's/^mattermost\/RequireEmailVerification: \(.*\)/\1/p')"
CONFIG_RequireEmailVerification=${CONFIG_RequireEmailVerification:-false}

# wait for Mattermost to become available before modifying the configuration
echo "waiting for Mattermost startup"
counter=0
until $(curl -k -f -s -o /dev/null -XPOST http://127.0.0.1:8065/api/v4/users/logout); do
	echo "waiting..."
	if [ $counter == 15 ]; then
		echo "Mattermost did not respond until the timeout was reached. Please check the docker logs command for more details."
		exit 1
	fi
	sleep 5
	counter=$((counter+1))
done

# update hostname in Mattermost
# apply email verification setting
jq ".ServiceSettings.SiteURL = \"$HOST\" | .EmailSettings.RequireEmailVerification= \"$CONFIG_RequireEmailVerification\"" $CONFIG_JSON | sponge $CONFIG_JSON

# reset settings of kwmserver
jq '.PluginSettings.Plugins += {"kopanowebmeetings":{"kwmserverinternalurl":"http://127.0.0.1:8778","kwmserverurl":"/","stunuri":"stun:stun.l.google.com:19302","turnsharedkey":null,"turnuri":null,"turnusername":"mattermost-kwm-user"}}' $CONFIG_JSON | sponge $CONFIG_JSON

# enable Kopano Web Meetings per default
jq '.PluginSettings.PluginStates += {"kopanowebmeetings":{"Enable":true}}' $CONFIG_JSON | sponge $CONFIG_JSON
