#!/usr/share/ucs-test/runner bash
## desc: Test zarafa listener module that triggers the zarafa sync with LDAP
## bugs: [31870]
## packages:
##  - zarafa4ucs
## tags:
##  - apptest
## exposure: dangerous

. "$TESTLIBPATH/base.sh" || exit 137
. "$TESTLIBPATH/user.sh" || exit 137
. "$TESTLIBPATH/random.sh" || exit 137
. "/usr/share/univention-lib/all.sh" || exit 137

eval "$(/usr/sbin/ucr shell)"

RETVAL=100

stop_udm_cli_server

createZarafaUser () {
	# $1 == username
	# $2 == role (contact, user, admin, store)
	local OPTIONS=""
	if [ "$2" = "contact" ] ; then
		OPTIONS="--option=person --option=mail"
	fi
	udm-test users/user create \
		--position "cn=users,$ldap_base" \
		--set username="$1" \
		--set firstname="Firstname" \
		--set lastname="Lastname" \
		--set password="univention" \
		--set mailPrimaryAddress="$(random_mailaddress)@$domainname" \
		$OPTIONS \
		--set zarafa-role="$2"
	[ ! "$?" = "0" ] && fail_test 140 "cannot create contact $1"
}

wait_until_user_is_in_zarafa ()
{
	local TIMEOUT=120

	for((i=0;i<$TIMEOUT;i++)); do
		zarafa-admin -l | egrep -q "$USERNAME" && break
		echo -n '.'
		sleep 1
	done

	test $i = $TIMEOUT && return 1 || return 0
}

wait_until_user_is_removed_in_zarafa ()
{
	local TIMEOUT=120

	for((i=0;i<$TIMEOUT;i++)); do
		zarafa-admin -l | egrep -q "$USERNAME" || break
		echo -n '.'
		sleep 1
	done

	test $i = $TIMEOUT && return 1 || return 0
}

for zarafatype in contact store user admin ; do
	echo "Testing zarafa $zarafatype ..."
	USERNAME="z${zarafatype}-$(user_randomname)"
	createZarafaUser "$USERNAME" "$zarafatype"


	if [ "$zarafatype" = "contact" ] ; then
		wait_for_replication_and_postrun
		sleep 3
		zarafa-admin -l | egrep "$USERNAME" && fail_test 110 "zarafa $zarafatype should not be visible in zarafa user list"
	else
		wait_until_user_is_in_zarafa "$USERNAME" || fail_test 110 "zarafa $zarafatype is not visible in zarafa user list"
	fi

	user_remove "$USERNAME"
	wait_until_user_is_removed_in_zarafa "$USERNAME" || fail_test 110 "zarafa $zarafatype has not been removed from zarafa"
done

exit $RETVAL
