#!/usr/share/ucs-test/runner python
## desc: Test PTR records are removed when no ptr record would be left over and multiple IP addresses are assigned
## tags: [udm-computers,apptest]
## roles: [domaincontroller_master]
## bugs: [44710, 51736]
## exposure: careful
## packages:
##   - univention-config
##   - univention-directory-manager-tools

from __future__ import print_function
import univention.uldap
import univention.testing.udm
import univention.testing.strings as uts


if __name__ == '__main__':
	ldap = univention.uldap.getAdminConnection()
	with univention.testing.udm.UCSTestUDM() as udm:
		domainname = uts.random_string(numeric=False)
		tld = uts.random_string(numeric=False)
		dnsZone1 = udm.create_object('dns/forward_zone', zone='%s.%s' % (domainname, tld), nameserver='univention')
		dnsZone2 = udm.create_object('dns/forward_zone', zone='%s2.%s' % (domainname, tld), nameserver='univention')
		rdnsZone = udm.create_object('dns/reverse_zone', subnet='10.20.30', nameserver='univention')

		computer_name = uts.random_string()
		computer = udm.create_object('computers/windows', name=computer_name, ip='10.20.30.60', dnsEntryZoneForward='%s 10.20.30.60' % dnsZone1, dnsEntryZoneReverse='%s 10.20.30.60' % rdnsZone)
		udm.modify_object('computers/windows', dn=computer, append={'dnsEntryZoneForward': ['%s 10.20.30.60' % dnsZone2]})

		ptr_record = 'relativeDomainName=60,%s' % (rdnsZone,)
		udm._cleanup.setdefault('dns/ptr_record', []).append(ptr_record)  # Workaround for being able to modify it:
		udm.modify_object('dns/ptr_record', dn=ptr_record, append={'ptr_record': ['%s.%s2.%s.' % (computer_name, domainname, tld)]})

		remove = {
			'dnsEntryZoneForward': ['%s 10.20.30.60' % dnsZone1, '%s 10.20.30.60' % dnsZone2],
			'dnsEntryZoneReverse': ['%s 10.20.30.60' % rdnsZone],
		}
		append = {
			'dnsEntryZoneForward': ['%s 10.20.30.6' % dnsZone1, '%s 10.20.30.6' % dnsZone2],
			'dnsEntryZoneReverse': ['%s 10.20.30.6' % rdnsZone],
		}
		udm.modify_object('computers/windows', dn=computer, ip='10.20.30.6', remove=remove, append=append)
		univention.testing.utils.verify_ldap_object(ptr_record, should_exist=False)
		univention.testing.utils.verify_ldap_object('relativeDomainName=6,%s' % (rdnsZone,), {'pTRRecord': [b'%s.%s.%s.' % (computer_name, domainname, tld), b'%s.%s2.%s.' % (computer_name, domainname, tld)]})
