#!/usr/share/ucs-test/runner bash
## desc: Test rolechange (user, admin, none)
## bugs: [31870]
## packages:
##  - zarafa4ucs
## tags:
##  - apptest
## exposure: dangerous

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

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

RETVAL=100

stop_udm_cli_server

changeRoleZarafaUser () {
	# $1 == username
	# $2 == role (user, admin)
	udm-test users/user modify \
		--dn "uid=$1,cn=users,$ldap_base" \
		--set zarafa-role="$2"
	[ ! "$?" = "0" ] && fail_test 140 "cannot change role of $1 to $2"
}

checkRoleZarafaUser () {
	# $1 == username
	# $2 == role (contact, user, admin, store)
	attrs="$(univention-ldapsearch -xLLL -b "uid=$1,cn=users,$ldap_base")"
	zAccount="0"
	zAdmin="0"
	echo "$attrs" | egrep "^zarafaAccount: 1$" && zAccount="1"
	echo "$attrs" | egrep "^zarafaAdmin: 1$" && zAdmin="1"

	case $2 in
		user)
			[ "$zAccount" = "1" -a "$zAdmin" = "0" ]
			return
			;;
		admin)
			[ "$zAccount" = "1" -a "$zAdmin" = "1" ]
			return
			;;
		none)
			[ "$zAccount" = "0" -a "$zAdmin" = "0" ]
			return
			;;
		*)
			echo "UNKNOWN ZARAFA USER ROLE: $2"
			return 1
			;;
	esac
}

for zarafatype in user admin none ; do
	for zarafatypeB in user admin none ; do
		# skip noop-changes
		[ "$zarafatype" = "$zarafatypeB" ] && continue
		echo "Testing $zarafatype ==> $zarafatypeB ..."

		USERNAME="z${zarafatype}-$(user_randomname)"
		createZarafaUser "$USERNAME" "$zarafatype"
		wait_for_replication
		changeRoleZarafaUser "$USERNAME" "$zarafatypeB"
		wait_for_replication
		checkRoleZarafaUser "$USERNAME" "$zarafatypeB" || fail_test 110 "Failed to switch from $zarafatype to $zarafatypeB:"
		wait_for_replication
		user_remove "$USERNAME"
		wait_for_replication
	done
done

wait_for_replication_and_postrun

exit $RETVAL
