#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2004-2021 Univention GmbH
#
# https://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <https://www.gnu.org/licenses/>.

"""
Script for converting wrong class b network entries
"""

from __future__ import print_function

import ldap
from ldap.filter import filter_format
import sys

import univention.config_registry
import univention.uldap


def main():
	# type: () -> None
	ucr = univention.config_registry.ConfigRegistry()
	ucr.load()

	baseDN = ucr['ldap/base']

	if ucr.get('interfaces/eth0/netmask') != "255.255.0.0":
		print('Only for Class B')
		sys.exit(1)

	lo = univention.uldap.getAdminConnection().lo

	computers = lo.search_s(baseDN, ldap.SCOPE_SUBTREE, 'objectClass=univentionHost', ['aRecord'])

	for computerdn, attrs in computers:
		print('DN: %s' % computerdn)
		if 'aRecord' in attrs:
			entry = attrs['aRecord'][0].decode('utf-8').split(u'.')[2:4]
			for reverse in lo.search_s('cn=dns,%s' % baseDN, ldap.SCOPE_SUBTREE, filter_format('(&(relativeDomainName=%s)(pTRRecord=%s*))', (u'.'.join(entry), ldap.dn.str2dn(computerdn)[0][0][1]))):
				print('Wrong DNS Reverse Entry for %s: %s' % (computerdn, reverse[0]))
				entry.reverse()
				entry = u'.'.join(entry)
				lo.modrdn_s(reverse[0], u'relativeDomainName=%s' % entry)
				break


if __name__ == "__main__":
	main()
