#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2019-2023 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
# <http://www.gnu.org/licenses/>.

from __future__ import absolute_import

import logging
from argparse import ArgumentParser

import ldap
from ldap.filter import filter_format
from six.moves.urllib_parse import quote

import univention.uldap
from ucsschool.lib.models.utils import get_file_handler, get_stream_handler
from univention.admin.uldap import getAdminConnection
from univention.config_registry import ConfigRegistry

LOG_FILE = "/var/log/univention/ucsschool-fix-slave-objects.log"
LOG_DEBUG_FMT = "%(asctime)s %(levelname)-5s %(funcName)s:%(lineno)d  %(message)s"
LOG_INFO_FMT = "%(message)s"
LOG_DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"

logger = logging.getLogger("main")


def get_s4_lo():
    ucr = ConfigRegistry()
    ucr.load()
    tls_mode = 0 if ucr.get("connector/s4/ldap/ssl") == "no" else 2

    protocol = ucr.get("connector/s4/ldap/protocol", "ldap").lower()
    ldap_host_s4 = ucr.get("connector/s4/ldap/host")
    ldap_port_s4 = int(ucr.get("connector/s4/ldap/port"))
    ldap_base_s4 = ucr.get("connector/s4/ldap/base")
    ldap_binddn_s4 = ucr.get("connector/s4/ldap/binddn")
    ldap_bindpw_s4 = None
    if ucr.get("connector/s4/ldap/bindpw"):
        ldap_bindpw_s4 = open(ucr["connector/s4/ldap/bindpw"]).read().strip("\n")
    ldap_certificate_s4 = ucr.get("connector/s4/ldap/certificate")
    if protocol == "ldapi":
        socket = quote(ucr.get("connector/s4/ldap/socket", ""), "")
        ldap_uri_s4 = "%s://%s" % (protocol, socket)
    else:
        ldap_uri_s4 = "%s://%s:%d" % (protocol, ldap_host_s4, ldap_port_s4)

    lo_s4 = univention.uldap.access(
        host=ldap_host_s4,
        port=ldap_port_s4,
        base=ldap_base_s4,
        binddn=ldap_binddn_s4,
        bindpw=ldap_bindpw_s4,
        start_tls=tls_mode,
        ca_certfile=ldap_certificate_s4,
        uri=ldap_uri_s4,
    )
    lo_s4.lo.set_option(ldap.OPT_REFERRALS, 0)
    return lo_s4


def fix_slave(lo, lo_s4, slave_dn, slave_attrs, dry_run=True):
    logger.debug("Checking %r", slave_dn)
    logger.debug("Attributes: %r", slave_attrs)
    roles = slave_attrs.get("ucsschoolRole", [])
    object_classes = slave_attrs.get("objectClass", [])
    slave_cn = slave_attrs.get("cn", [b""])[0].decode("UTF-8")

    mod_role = {
        "old": roles,
        "new": [role for role in roles if not role.startswith(b"win_computer:school:")],
    }
    mod_oc = {
        "old": object_classes,
        "new": [oc for oc in object_classes if oc not in (b"univentionWindows", b"ucsschoolComputer")],
    }

    if mod_role["old"] != mod_role["new"] or mod_oc["old"] != mod_oc["new"]:
        logger.info("Will modify: %s", slave_dn)
        logger.info("Roles: %r", mod_role)
        logger.info("ObjectClass: %r", mod_oc)
        if not dry_run:
            lo.modify(
                slave_dn,
                (
                    ("ucsschoolRole", mod_role["old"], mod_role["new"]),
                    ("objectClass", mod_oc["old"], mod_oc["new"]),
                ),
            )

        for slave_s4_dn, slave_s4_attr in lo_s4.search(
            filter_format("(&(cn=%s)(userAccountControl:1.2.840.113556.1.4.803:=4096))", [slave_cn]),
            attr=["userAccountControl"],
        ):
            if slave_s4_dn is None:
                continue  # referals
            slave_account_control = int(slave_s4_attr["userAccountControl"][0].decode("ASCII"))
            new_slave_account_control = int(slave_account_control) & ~4096 | 8192 | 524288
            if slave_account_control == new_slave_account_control:
                continue

            mod_account_control = [
                (
                    "userAccountControl",
                    slave_s4_attr["userAccountControl"],
                    [str(new_slave_account_control).encode("ASCII")],
                )
            ]
            logger.info("userAccountControl: %r", mod_account_control)

            # reset userAccountControl from workstation/server (4096) to DC (532480)
            if not dry_run:
                lo_s4.modify(slave_s4_dn, mod_account_control)

        if dry_run:
            logger.info("DRY-RUN: skipping modification")


def main():
    description = """This script searches and checks for UCS@school school server objects in LDAP.
If one of the wrong object classes (univentionWindows, ucsschoolComputer) is found,
the wrong object class will be removed and the ucsschoolRole attribute corrected accordingly."""
    parser = ArgumentParser(description=description)
    parser.add_argument("--dry-run", action="store_true", help="do not make any changes")
    parser.add_argument("--verbose", action="store_true", help="show detailed log output")
    options = parser.parse_args()

    logger.setLevel("DEBUG")
    logger.addHandler(get_stream_handler("DEBUG" if options.verbose else "INFO"))
    logger.addHandler(get_file_handler("DEBUG", LOG_FILE))

    logger.info("Looking for affected Replica Directory Node objects...")
    lo, po = getAdminConnection()
    lo_s4 = get_s4_lo()
    slaves = lo.search(
        filter="(univentionObjectType=computers/domaincontroller_slave)",
        attr=["objectClass", "ucsschoolRole", "cn"],
    )
    for slave_dn, slave_attrs in slaves:
        fix_slave(lo, lo_s4, slave_dn, slave_attrs, dry_run=options.dry_run)


if __name__ == "__main__":
    main()
