#!/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/>.

"""
* Change all values 'win_compuer:school:*' to 'win_computer:school:*'.
* Change lowercase OUs in dc_*:school:<ou> to "correct case" OU.
"""

import logging
import sys

import univention.admin.uldap
from ucsschool.lib.models.school import School
from ucsschool.lib.models.utils import get_file_handler, get_stream_handler
from ucsschool.lib.roles import (
    role_dc_slave_admin,
    role_dc_slave_edu,
    role_memberserver_admin,
    role_memberserver_edu,
    role_win_computer,
)
from univention.config_registry import ConfigRegistry

LOG_FILE = "/var/log/univention/ucsschool-roles-migration.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"

ucr = ConfigRegistry()
ucr.load()

if ucr["server/role"] != "domaincontroller_master":
    print("This script can only be executed on the Primary Directory Node.")
    sys.exit(2)

logger = logging.getLogger("UcsSchoolRolesMigration")
logger.setLevel("DEBUG")
logger.addHandler(get_stream_handler("INFO"))
logger.addHandler(get_file_handler("DEBUG", LOG_FILE))

lo, po = univention.admin.uldap.getAdminConnection()
all_school_objs = School.get_all(lo)


def correct_case_ou(mixed_case_ou):
    for school in all_school_objs:
        if school.name.lower() == mixed_case_ou.lower():
            return school.name
    else:
        raise RuntimeError("Unknown OU {!r}.".format(mixed_case_ou))


for dn, attr in lo.search("ucsschoolRole=win_compuer:school:*", attr=["ucsschoolRole"]):
    old_roles = attr["ucsschoolRole"]
    new_roles = [
        "{}:school:{}".format(role_win_computer, role.decode("UTF-8").split(":", 2)[2]).encode("UTF-8")
        if role.startswith(b"win_compuer:school:")
        else role
        for role in old_roles
    ]
    logger.info('Changing "ucsschoolRole" of %r from %r to %r.', dn, old_roles, new_roles)
    lo.modify(dn, [("ucsschoolRole", old_roles, new_roles)])

for role in (role_dc_slave_edu, role_dc_slave_admin, role_memberserver_edu, role_memberserver_admin):
    for dn, attr in lo.search("(ucsschoolRole={}:school:*)".format(role), attr=["ucsschoolRole"]):
        old_roles = attr["ucsschoolRole"]
        mixed_case_ous = [old_role.decode("UTF-8").split(":", 2)[2] for old_role in old_roles]
        correct_case_ous = [correct_case_ou(ou) for ou in mixed_case_ous]
        new_roles = ["{}:school:{}".format(role, ou).encode("UTF-8") for ou in correct_case_ous]
        if old_roles != new_roles:
            logger.info('Changing "ucsschoolRole" of %r from %r to %r.', dn, old_roles, new_roles)
            lo.modify(dn, [("ucsschoolRole", old_roles, new_roles)])
