#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: move OX user from one context into another
## tags: [apptest]
## exposure: dangerous
## packages:
##   - univention-ox (>= 8.1.0-72)
##   - open-xchange-authentication-ucs (>= 7.8.4-0)
## bugs: [43264]

import univention.testing.udm as testing_udm
import univention.testing.ucr as testing_ucr
import univention.testing.strings as uts
import univention.testing.utils as utils
import essential.common


with essential.common.OXTestEnv() as oxenv, \
		testing_udm.UCSTestUDM() as udm, \
		testing_ucr.UCSTestConfigRegistry() as ucr, \
		essential.common.OXTestEmptyQueue():

	context_id_A, context_id_B = oxenv.create_contexts(2)

	oxenv.check_if_context_exists_in_ldap(context_id_A)
	oxenv.check_if_context_exists_in_ox(context_id_A)

	oxenv.check_if_context_exists_in_ldap(context_id_B)
	oxenv.check_if_context_exists_in_ox(context_id_B)

	print('*** Creating user in OX context {}...'.format(context_id_A))
	mail_domain = ucr.get('mail/hosteddomains').split()[-1].strip()
	ox_user_password = uts.random_string()
	ox_user_dn, ox_username = udm.create_user(
		mailPrimaryAddress='{}@{}'.format(uts.random_username(), mail_domain),
		password=ox_user_password,
		isOxUser='OK',
		oxContext=context_id_A)
	utils.wait_for_replication()

	oxenv.check_if_user_exists_in_context(ox_username, context_id_A)  # should exist in A
	oxenv.check_if_user_exists_in_context(ox_username, context_id_B, expected=False)  # should NOT exist in B
	oxenv.check_if_user_can_login(ox_username, ox_user_password)

	print('*** Moving user {} from context {} to context {}'.format(ox_username, context_id_A, context_id_B))
	udm.modify_object('users/user', dn=ox_user_dn, oxContext=context_id_B)
	utils.wait_for_replication()

	oxenv.check_if_user_exists_in_context(ox_username, context_id_B)  # should exist in B
	oxenv.check_if_user_exists_in_context(ox_username, context_id_A, expected=False)  # should NOT exist in A
	oxenv.check_if_user_can_login(ox_username, ox_user_password)
