#!/usr/share/ucs-test/runner python3
## desc: Validate adoption of network properties during creation for all computer roles
## tags: [udm-computers, SKIP]
## roles: [domaincontroller_master]
## exposure: careful
## bugs: [15758]
## packages:
##   - univention-config
##   - univention-directory-manager-tools


import univention.testing.udm as udm_test
import univention.testing.strings as uts
import univention.testing.utils as utils
import univention.config_registry as configRegistry


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

	for role in udm_test.UCSTestUDM.COMPUTER_MODULES:
		if role == 'computers/macos':
			continue

		computerProperties = {
			'mac': '01:23:45:67:89:ab',
			'name': uts.random_name()
		}

		with udm_test.UCSTestUDM() as udm:
			dNSCn = 'cn=dns,%s' % (ucr['ldap/base'],)

			forwardZoneName = '%s.%s' % (uts.random_name(), uts.random_name())

			forwardZone = udm.create_object('dns/forward_zone', zone=forwardZoneName, position=dNSCn, nameserver=uts.random_string(numeric=False))
			reverseZone = udm.create_object('dns/reverse_zone', subnet='10.20.30', position=dNSCn, nameserver=uts.random_string(numeric=False))
			dhcpService = udm.create_object('dhcp/service', service=uts.random_name())
			networkProperties = {
				'name': uts.random_name(),
				'network': '10.20.30.0',
				'netmask': '24',
				'dnsEntryZoneForward': forwardZone,
				'dnsEntryZoneReverse': reverseZone,
				'dhcpEntryZone': dhcpService,
				'ipRange': '10.20.30.2 10.20.30.254'
			}
			network = udm.create_object('networks/network', **networkProperties)

			computer = udm.create_object(role, network=network, **computerProperties)
			aRecord = utils.get_ldap_connection().getAttr(computer, 'aRecord')[0]

			# FIXME: workaround for remaining locks
			udm.addCleanupLock('aRecord', aRecord)
			udm.addCleanupLock('mac', '01:23::89:ab')

			# verify that properties have been adopted correctly during creation
			utils.verify_ldap_object(computer, {'univentionNetworkLink': [network]})

			if aRecord not in ['10.20.30.%s' % str(oktett) for oktett in range(2, 255)]:
				utils.fail('IP address of computer not in range of it\'s network')
			utils.verify_ldap_object('relativeDomainName=%s,%s' % (computerProperties['name'], forwardZone), {'aRecord': [aRecord]})
			utils.verify_ldap_object('relativeDomainName=%s,%s' % (aRecord.split(".")[-1], reverseZone), {'pTRRecord': ['%s.%s.' % (computerProperties['name'], forwardZoneName)]})
			utils.verify_ldap_object('cn=%s,%s' % (computerProperties['name'], dhcpService), {'univentionDhcpFixedAddress': [aRecord]})
