#!/usr/share/ucs-test/runner python3
## desc: Creates DNS host record entry and try to resolve it
## bugs: [39269]
## roles:
##  - domaincontroller_master
## packages:
##   - univention-config
##   - univention-directory-manager-tools
## tags:
##  - skip_admember
## exposure: careful

import univention.testing.udm as udm_test
import univention.testing.strings as uts
from essential.dns_helper import resolveDnsEntry
from ipaddress import ip_address


if __name__ == '__main__':
	with udm_test.UCSTestUDM() as udm:
		zone = '%s.%s.' % (uts.random_name(), uts.random_name())
		pos = 'cn=dns,%s' % (udm.LDAP_BASE,)

		forward_zone_properties = {
			'zone': zone,
			'nameserver': udm.FQHN,
			'contact': '%s@%s.%s' % (uts.random_name(), uts.random_name(), uts.random_name()),
			'serial': '%s' % (uts.random_int()),
			'zonettl': '%s' % (uts.random_int(bottom_end=100, top_end=999)),
			'refresh': '%s' % (uts.random_int(bottom_end=10, top_end=99)),
			'expire': '%s' % (uts.random_int(bottom_end=10, top_end=99)),
			'ttl': '%s' % (uts.random_int(bottom_end=10, top_end=99)),
			'retry': '%s' % (uts.random_int()),
		}
		forward_zone = udm.create_object('dns/forward_zone', position=pos, **forward_zone_properties)

		# IPv4
		ip = uts.random_ip()
		host = uts.random_name()
		host_record_properties = {
			'name': host,
			'zonettl': '%s' % (uts.random_int(bottom_end=100, top_end=999)),
			'a': ip,
			'mx': '50 %s' % uts.random_string(),
			'txt': uts.random_string()
		}
		host_record = udm.create_object('dns/host_record', superordinate=forward_zone, **host_record_properties)

		qname = '%s.%s' % (host, zone)
		answers = resolveDnsEntry(qname, 'A')
		answer = [ip_address(u'%s' % (rdata.address,)) for rdata in answers]
		assert answer == [ip_address(u'%s' % (ip,))], 'resolved name "%s" != created ldap-object "%s"' % (answer, [ip])

		# IPv6
		ip = '2011:06f8:13dc:0002:19b7:d592:09dd:1041'  # create random_ipv6()-method?
		host = uts.random_name()
		host_record_properties.update({
			'name': host,
			'a': ip,
		})
		host_record = udm.create_object('dns/host_record', superordinate=forward_zone, **host_record_properties)

		qname = '%s.%s' % (host, zone)
		answers = resolveDnsEntry(qname, 'AAAA')
		answer = [ip_address(u'%s' % (rdata.address,)) for rdata in answers]
		assert answer == [ip_address(u'%s' % (ip,))], 'resolved name "%s" != created ldap-object "%s"' % (answer, [ip])
