#!/bin/bash

set -x
#set -e

create_user () {
	local username=$1
	univention-app shell mattermost mattermost-platform user create --email="$username@kopano.intranet" --password="$username" --username=$username
}

change_password () {
	local username="$1"
	local new_password="$2"
	univention-app shell mattermost mattermost-platform user password "$username" "$new_password"
}

create_team () {
	local teamname="$1"
	univention-app shell mattermost mattermost-platform team create --name $teamname --display_name "$teamname - created by test"
}

add_user_team () {
	local teamname="$1"
	local username="$2"
	univention-app shell mattermost mattermost-platform team add $teamname $username
}

get_token () {
	local response="$1"
	token=$(cat "$response" | grep Token: | tr -d '[:space:]' | cut -d ':' -f2)
	echo $token
}


mattermost_login () {
	local username="$1"
	local password="$2"
	local data="{\"login_id\":\"$username\",\"password\":\"$password\"}"
	local url="http://127.0.0.1:8065/api/v4/users/login"
	local out=$(mktemp)
	curl -o $out -i -d "$data" "$url" || die 110 "Failed connect to Mattermost"
	local token="$(get_token $out)"
	rm $out
	if [ ! -z "${token// }" ]; then
		echo $token
		return 0
	fi
	return 1
}

remove_user () {
	local username="$1"
	univention-app shell mattermost mattermost-platform user delete $username --confirm
}

die () {
	echo "$1" >&2
	exit 1
}

username1="user01"
username2="user02"

trap "{
	remove_user "$username1"
	remove_user "$username2"
}" EXIT

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 == 45 ]; 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


create_user "$username1"
create_user "$username2"

# Try to login with pre created admin
#mattermost_login "Administrator" "mattermost" || die "Login was denied"

# Try to login with correct password
mattermost_login "$username1" "$username1" || die "Login was denied"
# Try to login with wrong password
mattermost_login "$username1" "univention" && die "Login with wrong password"

# create teams
create_team testset
add_user_team testset $username1
curl -i -H "Authorization: Bearer $(mattermost_login $username1 $username1)" http://127.0.0.1:8065/api/v4/

# Try to login with correct password
mattermost_login "$username2" "$username2" || die "Login was denied"
# Change password of user
change_password "$username2" "golden-ticket"
# Try login with new password
mattermost_login "$username2" "golden-ticket" || die "Login was denied"
# Try to login with old password
mattermost_login "$username2" "$username2" && die "Login with wrong password"

echo "Tests were succesful!"
exit 0
