#!/usr/share/ucs-test/runner python3
## desc: Rename a container/ou with un-moveable subobjects from lower to upper case
## tags: [udm,apptest]
## roles: [domaincontroller_master]
## exposure: careful
## packages:
##   - univention-config
##   - univention-directory-manager-tools

import pytest

import univention.testing.utils as utils
import univention.testing.udm as udm_test
from univention.testing.ucs_samba import wait_for_drs_replication
import univention.testing.strings as uts
import univention.config_registry as configRegistry
import ldap.filter
import ldap.dn


if __name__ == '__main__':
	ucr = configRegistry.ConfigRegistry()
	ucr.load()

	with udm_test.UCSTestUDM() as udm:
		user_name = uts.random_string()
		network_name = uts.random_string()

		ou_name = uts.random_string()
		ou_name_new = ou_name.upper()

		ou = udm.create_object('container/ou', name=ou_name)
		wait_for_drs_replication('ou=%s' % ou_name)
		user = udm.create_user(position=ou, username=user_name)
		network = udm.create_object('networks/network', position=ou, name=network_name, network='1.1.1.1', netmask='24')

		with pytest.raises(udm_test.UCSTestUDM_ModifyUDMObjectFailed) as exc:
			udm.modify_object('container/ou', dn=ou, name=ou_name_new)
		# This operation is not allowed on this object: Unable to move object ayj9blkm9k (networks/network) in subtree, trying to revert changes.
		assert 'Unable to move object' in str(exc.value)

		new_ou = 'ou=%s,%s' % (ldap.dn.escape_dn_chars(ou_name_new), ucr.get('ldap/base'))
		new_user = 'uid=%s,ou=%s,%s' % (ldap.dn.escape_dn_chars(user_name), ldap.dn.escape_dn_chars(ou_name_new), ucr.get('ldap/base'))
		utils.verify_ldap_object(new_ou, should_exist=True)
		utils.verify_ldap_object(new_user, should_exist=True)

		lo = utils.get_ldap_connection()
		for dn, entry in lo.search(filter=ldap.filter.filter_format('ou=%s', [ou_name])):
			if entry.get('ou')[0] != ou_name.encode('UTF-8'):
				utils.fail('ou = %s; expected: %s' % (entry.get('ou')[0], ou_name))
