#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# UCS@school lib
#  module: Create role specific shares
#
# Copyright 2014-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 sys

from six.moves import input

import univention.admin.modules as udm_modules
import univention.config_registry
from ucsschool.lib.roleshares import create_roleshares
from ucsschool.lib.school_umc_ldap_connection import MACHINE_READ, LDAP_Connection, set_credentials

udm_modules.update()


@LDAP_Connection(MACHINE_READ)
def dn_from_username(username, ucr=None, ldap_machine_read=None, ldap_position=None):
    if not ucr:
        ucr = univention.config_registry.ConfigRegistry()
        ucr.load()

    ldap_filter = "(username=%s)" % (username,)
    try:
        udm_obj = udm_modules.lookup(
            "users/user",
            None,
            ldap_machine_read,
            scope="sub",
            base=ucr.get("ldap/base"),
            filter=str(ldap_filter),
        )[0]
    except IndexError:
        return None
    else:
        return udm_obj.dn


if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser()
    parser.add_argument(
        "--create", required=True, dest="roleshares", action="append", help="create role share"
    )
    parser.add_argument("--school", dest="schools", action="append", help="select school")
    parser.add_argument("--binddn", help="udm binddn")
    parser.add_argument("--bindpwd", help="udm bindpwd")
    parser.add_argument("--bindpwdfile", help="udm bindpwdfile")
    opts = parser.parse_args()

    ucr = univention.config_registry.ConfigRegistry()
    ucr.load()

    if opts.binddn and opts.bindpwd:
        binddn = opts.binddn
        password = opts.bindpwd
    elif opts.binddn and opts.bindpwdfile:
        binddn = opts.binddn
        with open(opts.bindpwdfile) as fp:
            password = fp.read()
    elif ucr["server/role"] in ("domaincontroller_master", "domaincontroller_backup"):
        try:
            with open("/etc/ldap.secret") as fp:
                password = fp.read()
            binddn = "cn=admin,{}".format(ucr["ldap/base"])
            print("Using cn=admin account")
        except IOError as exc:
            print("Cannot read /etc/ldap.secret: {}".format(exc))
            sys.exit(1)
    else:
        username = input("Administrator name: ")
        if opts.bindpwd:
            password = opts.bindpwd
        else:
            password = input("Password: ")

        binddn = dn_from_username(username, ucr)
        if not binddn:
            print("User not found")
            sys.exit(1)

    set_credentials(binddn, password)  # for @LDAP_Connection(USER_*)

    create_roleshares(opts.roleshares, opts.schools, ucr)
