#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020-2021 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/>.

"""
List OX users in "Domain Admins" as primary group, created after release of
OX App Suite version 7.10.3-ucs3 (11.06.2020), see Bug #51993.
"""


import sys
from univention.lib.misc import custom_groupname
from univention.config_registry import ConfigRegistry
from univention.admin import uldap


print("Looking for OX users that have 'Domain Admins' as primary group and have")
print("been created after 2020-06-11 (release of OX App Suite version 7.10.3-ucs3):\n")

ucr = ConfigRegistry()
ucr.load()
ldap_base = ucr["ldap/base"]
admins_group_name = custom_groupname("Domain Admins")
admins_group_dn = "cn={},cn=groups,{}".format(admins_group_name, ldap_base)
lo, po = uldap.getMachineConnection()

admins_group_gid = lo.get(admins_group_dn)["gidNumber"][0].decode('utf-8')
res = lo.search(
    "(&(gidNumber={})(isOxUser=*)(createTimestamp>=20200611000000Z))".format(admins_group_gid),
    attr=["createTimestamp", "mailPrimaryAddress", "uid"]
)

if not res:
    print("None found.")
    sys.exit(0)

print("   Creation date    | 'username' (email)")
print("--------------------+------------------------------------------")
res.sort(key=lambda x: x[1]["createTimestamp"])
for dn, attrs in res:
    d_s = attrs["createTimestamp"][0].decode('utf-8')
    date_s = "{}-{}-{} {}:{}:{}".format(d_s[:4], d_s[4:6], d_s[6:8], d_s[8:10], d_s[10:12], d_s[12:14])
    username = attrs["uid"][0].decode('utf-8')
    email = attrs.get("mailPrimaryAddress", [b"no email"])[0].decode('utf-8')
    print("{} | {!r} ({})".format(date_s, username, email))
