#!/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 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"
}

for zarafatype in contact store user admin ; do
	echo "Testing zarafa $zarafatype ..."
	USERNAME="z${zarafatype}-$(user_randomname)"
	createZarafaUser "$USERNAME" "$zarafatype"
	if [ "$zarafatype" = "contact" ] ; then
		zarafa-admin -l | egrep "\<$USERNAME\>" && echo "WARNING: zarafa $zarafatype should not be visible in zarafa user list"
	else
		zarafa-admin -l | egrep "\<$USERNAME\>" && echo "WARNING: zarafa $zarafatype should not visible in zarafa user list that fast!"
	fi
	echo "Wait for listeners postrun..."
	sleep 20s # TODO ideally the script will poll every second
	if [ "$zarafatype" = "contact" ] ; then
		zarafa-admin -l | egrep "\<$USERNAME\>" && fail_test 110 "zarafa $zarafatype should not be visible in zarafa user list"
	else
		zarafa-admin -l | egrep "\<$USERNAME\>" || fail_test 110 "zarafa $zarafatype is not visible in zarafa user list"
	fi
	user_remove "$USERNAME"
	sleep 20s # wait for listeners postrun
	zarafa-admin -l | egrep "\<$USERNAME\>" && fail_test 110 "zarafa $zarafatype has not been removed from zarafa"
done

exit $RETVAL
