#!/usr/bin/python

# Copyright 2022-2023 Univention GmbH
#
# http://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/>.

import os
from argparse import ArgumentParser

from ldif import LDIFParser, LDIFWriter
from utils import replace_string_in_ldap_entry

from univention.config_registry import ConfigRegistry

ucr = ConfigRegistry()
ucr.load()


class ReplaceLDAPBase(LDIFParser):
    """
    only changes the ldap-base
    does not change attributes like univentionShareHost
    """

    def __init__(self, input, output, old_ldap_base, new_ldap_base):
        LDIFParser.__init__(self, input)
        self.writer = LDIFWriter(output)
        self.old_ldap_base = old_ldap_base
        self.new_ldap_base = new_ldap_base

    def replace_ldap_base(self, dn, entry):
        # type: (str, Dict[str, List[bytes]]) -> Tuple[str, Dict[str, List[bytes]]]
        return replace_string_in_ldap_entry(
            dn, entry, self.old_ldap_base, self.new_ldap_base
        )

    def handle(self, dn, entry):  # type: (str, Dict[str, List[bytes]]) -> None
        dn, entry = self.replace_ldap_base(dn, entry)
        self.writer.unparse(dn, entry)


def _replace_ldap_base(input_file, output_file, old_ldap_base, new_ldap_base):
    # print("{} -> {}".format(input_file, output_file))
    with open(output_file, "w") as fout, open(input_file, "r") as fin:
        parser = ReplaceLDAPBase(fin, fout, old_ldap_base, new_ldap_base)
        parser.parse()


def main():
    parser = ArgumentParser()
    parser.add_argument("--old_ldap_base", "-b", required=False)
    parser.add_argument("--new_ldap_base", "-n", required=False)
    parser.add_argument("inputfolder")
    opt = parser.parse_args()

    old_ldap_base = opt.old_ldap_base or "dc=dummy,dc=base"
    new_ldap_base = opt.new_ldap_base or ucr["ldap/base"]
    print("{} -> {}".format(old_ldap_base, new_ldap_base))
    input_folder = opt.inputfolder

    for filename in os.listdir(input_folder):
        f = os.path.join(input_folder, filename)
        output_file, ext = os.path.splitext(f)
        if os.path.isfile(f) and ext == ".tmpl":
            _replace_ldap_base(f, output_file, old_ldap_base, new_ldap_base)


if __name__ == "__main__":
    main()
