#!/usr/bin/python3
# SPDX-FileCopyrightText: 2005-2026 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

"""Set missing univentionObjectType attributes on UDM objects."""

import argparse
import sys

import ldap

import univention.admin.uexceptions
from univention.admin.modules import identify, update
from univention.admin.uldap import getAdminConnection
from univention.config_registry import ucr


def warning_suppressed(dn: str, attributes: dict[str, list[bytes]]) -> bool:
    # cn=admin,$ldap_base cn=backup,$ldap_base
    ocs = set(attributes['objectClass'])
    if set(attributes.keys()) == {'objectClass', 'userPassword', 'cn', 'sn'} and ocs == {b'top', b'person'}:
        if attributes['sn'] == attributes['cn'] and len(attributes['cn']) == 1 and attributes['cn'][0] in (b'admin', b'backup'):
            return True
    # Kerberos principal objects
    if ocs == {b'top', b'account', b'krb5Principal', b'krb5KDCEntry'}:
        return True
    if ocs == {b'top', b'person', b'krb5Principal', b'krb5KDCEntry'}:
        return True
    # samba idmap objects
    return ocs == {b'sambaIdmapEntry', b'sambaSidEntry'}


def main(args: argparse.Namespace) -> bool:
    errors_occurred = False
    search_filter = '(objectClass=*)' if args.verify else '(!(objectClass=univentionObject))'
    update()

    ldap_connection, _po = getAdminConnection()
    if args.action is not True:
        ldap_connection.modify = lambda dn, changes: sys.stdout.write('Would modify %r\n' % (dn, ))

    for dn, attributes in ldap_connection.search(filter=search_filter, base=args.base, attr=['*', 'entryUUID']):
        if dn.endswith(',cn=temporary,cn=univention,%s' % ucr.get('ldap/base')):
            continue

        modules = identify(dn, attributes)
        if not modules or any(module.module == 'kerberos/kdcentry' for module in modules):  # Bug #47846
            if not warning_suppressed(dn, attributes):
                print('Warning: No match for %r' % (dn, ), file=sys.stderr)
                if args.verbose:
                    for attr in ('objectClass', 'univentionObjectType'):
                        for value in attributes.get(attr, []):
                            print('\t%s: %s' % (attr, value.decode('UTF-8')))
            continue

        new_object_classes = attributes['objectClass'][:]
        changes = []
        if b'univentionObject' not in new_object_classes:
            new_object_classes.append(b'univentionObject')
            changes = [
                ('objectClass', attributes['objectClass'], new_object_classes),
                ('univentionObjectType', [], [modules[0].module.encode('UTF-8')]),
            ]

        if not attributes.get('univentionObjectIdentifier'):
            changes.append(('univentionObjectIdentifier', [], attributes['entryUUID']))

        if len(modules) > 1:
            print('Warning: UDM identified multiple object types for %s: %s - using the first' % (dn, modules), file=sys.stderr)
            errors_occurred = True

        if changes:
            try:
                ldap_connection.modify(dn, changes)
            except univention.admin.uexceptions.ldapError as exc:
                if not isinstance(exc.original_exception, ldap.INVALID_SYNTAX):
                    raise
                # This indicates that LDAP schema extensions are missing (Bug #26304)
                print('ERROR: Could not set univentionObjectType! (%s)\nIt seems that the corresponding LDAP schema extensions are not installed correctly.' % exc, file=sys.stderr)
                errors_occurred = True

    return errors_occurred


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Set the attribute univentionObjectType for each directory object')
    parser.add_argument('--verbose', action='store_true', default=False, help='do not hide warnings for unmatched component objects')
    parser.add_argument('-v', '--verify', action='store_true', default=False, help='check objects with already set univentionObjectType')
    parser.add_argument('-b', '--base', default='', help='only modify objects at or below SEARCHBASE', metavar='SEARCHBASE')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-n', '--no-action', dest='action', action='store_false', help='do not modify the directory, show what would have been done')
    group.add_argument('-a', '--action', dest='action', action='store_true', help='do modify the directory')

    args = parser.parse_args()
    sys.exit(int(main(args)))
