#!/usr/share/ucs-test/runner python3
## desc: Creates DNS srv record 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.strings as uts
import univention.testing.udm as udm_test
from essential.dns_helper import resolveDnsEntry


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 / IPv6
		host = uts.random_name()
		ipv4 = uts.random_ip()
		ipv6 = '2011:06f8:13dc:0002:19b7:d592:09dd:1041'  # create random_ipv6()-method?
		host_record_properties = {
			'name': host,
			'zonettl': '%s' % (uts.random_int(bottom_end=100, top_end=999)),
			'a': [ipv4, ipv6],
			'mx': '50 %s' % uts.random_string(),
			'txt': uts.random_string()
		}
		host_record = udm.create_object('dns/host_record', superordinate=forward_zone, **host_record_properties)

		service = uts.random_string()
		protocol = 'tcp'
		extension = uts.random_string()
		priority = 1
		weight = 100
		port = uts.random_int(top_end=65535)
		fqhn = '%s.%s' % (host, zone)
		srv_record_properties = {
			'name': '%s %s %s' % (service, protocol, extension),
			'location': '%d %d %s %s' % (priority, weight, port, fqhn),
			'zonettl': '128'
		}
		srv_record = udm.create_object('dns/srv_record', superordinate=forward_zone, **srv_record_properties)

		zoneName = '_%s._%s.%s.%s' % (service, protocol, extension, zone)
		answers = resolveDnsEntry(zoneName, 'SRV')
		answer = [rdata.target.to_text() for rdata in answers]
		assert answer == [fqhn], 'resolved name "%s" != created ldap-object "%s"' % (answer, [fqhn])
