#!/bin/bash

while getopts u:p:d:n:o: option; do
	case "${option}"
	in
		u) USER=${OPTARG};;
		p) PASSWORD=${OPTARG};;
		d) DATABASE=${OPTARG};;
		n) ACCOUNTUSER=${OPTARG};;
		o) ACCOUNTPASS=${OPTARG};;
	esac
done

if [ -z "${USER}" ] || [ -z "${DATABASE}" ] || [ -z "${ACCOUNTUSER}" ] || [ -z "${ACCOUNTPASS}" ]; then
	echo "usage: $0 -u <mysql-user> -p <mysql-password> -d <mattermost-database> -n <mattermost-dbuser> -o <mattermost-dbpass>"
	exit 1
fi

function do_query {
	if [ -z "${PASSWORD}" ]; then
		echo "$@" | mysql -u"${USER}"
	else
		echo "$@" | mysql -u"${USER}" -p"${PASSWORD}"
	fi
	local status=$?
	if [ $status -ne 0 ]; then
		echo "Error with executing $1" >&2
	fi
	return $status
}

do_query "CREATE DATABASE IF NOT EXISTS ${DATABASE};"
do_query "CREATE USER '${ACCOUNTUSER}'@'127.0.0.1' IDENTIFIED BY '${ACCOUNTPASS}';"
do_query "GRANT ALL PRIVILEGES ON ${DATABASE}.* TO '${ACCOUNTUSER}'@'127.0.0.1';"

if [ $? -ne 0 ]; then
	echo -e "Something went wrong with creating the Mattermost database credentials, please check above output.\nMost possible causes are incorrect logon credentials."
else
	echo -e "Creation of DB and DB User successful."
fi

sed -i -s "s#^ *\"DataSource\":.*#        \"DataSource\": \"${ACCOUNTUSER}:${ACCOUNTPASS}@tcp\(127.0.0.1:3306\)\/${DATABASE}?charset=utf8mb4,utf8\&readTimeout=30s\&writeTimeout=30s\",#g" /etc/mattermost/config.json


if [ $? -ne 0 ]; then
	echo "Something went wrong with adapting the Mattermost configuration."
else
	echo "Mattermost configuration has been adapted successfully. Please restart mattermost to use the new settings."
fi
