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

"""
Check if users are member of their primary group
"""

from __future__ import print_function

import sys
from argparse import ArgumentParser

import univention.config_registry
import univention.debug as ud

import univention.admin.modules
import univention.admin.objects
import univention.admin.uexceptions

lo = None
position = None
grp2childgrps = {}


class groupRecursionDetected(univention.admin.uexceptions.base):
	message = 'circular group recursion detected'

	def __init__(self, recursionlist):
		self.recursionlist = recursionlist


def get_ldap_connection(baseDN):
	try:
		return univention.admin.uldap.getAdminConnection()
	except Exception:
		return univention.admin.uldap.getMachineConnection()


def checkChilds(grp_module, dn, parents, verbose=False, exception=False):
	global grp2childgrps, lo

	if dn not in grp2childgrps:
		grpobj = univention.admin.objects.get(grp_module, None, lo, position='', dn=dn, attr=None)
		grpobj.open()
		childs = grpobj['nestedGroup']
		grp2childgrps[dn] = childs
	else:
		childs = grp2childgrps[dn]

	new_parents = parents + [dn.lower()]
	for childgrp in childs:
		if verbose:
			print('%s+--> %s' % ('|    ' * (len(parents) + 1), childgrp))
		if childgrp.lower() in new_parents:
			recursionlist = new_parents[new_parents.index(childgrp.lower()):] + [childgrp]
			raise groupRecursionDetected(recursionlist)

		checkChilds(grp_module, childgrp, new_parents, verbose)


def main():
	# type: () -> None
	parser = ArgumentParser(description=__doc__)
	parser.add_argument("-v", "--verbose", help="print debug output", dest="verbose", action="store_true")
	options = parser.parse_args()

	global lo, position

	ud.init('/var/log/univention/check_group_recursion.log', ud.FLUSH, ud.NO_FUNCTION)

	configRegistry = univention.config_registry.ConfigRegistry()
	configRegistry.load()
	basedn = configRegistry['ldap/base']

	univention.admin.modules.update()
	lo, position = get_ldap_connection(basedn)
	grp_module = univention.admin.modules.get('groups/group')
	univention.admin.modules.init(lo, position, grp_module)

	recursionCnt = 0

	grpobjlist = univention.admin.modules.lookup(grp_module, None, lo, scope='sub', superordinate=None, base=basedn, filter=None)
	print('Number of groups: %d' % len(grpobjlist))
	ud.debug(ud.ADMIN, ud.ERROR, 'Testing %d groups...' % len(grpobjlist))
	for i, group in enumerate(grpobjlist):
		if options.verbose:
			print()
			print('|--> %s' % group.dn)
		else:
			print('Testing group #%d\r' % i, end='')
			sys.stdout.flush()

		try:
			checkChilds(grp_module, group.dn, [], options.verbose)
		except groupRecursionDetected as e:
			txtring = ''
			for dn in e.recursionlist:
				txtring += '--> %s\n' % dn
			ud.debug(ud.ADMIN, ud.ERROR, 'Recursion detected: %s\n%s' % (group.dn, txtring))
			print()
			print('Recursion detected:')
			for dn in e.recursionlist:
				print('--> %s' % dn)
			recursionCnt += 1

	ud.debug(ud.ADMIN, ud.ERROR, 'Tests have been finished. %d group(s) with circular recursion found.' % recursionCnt)
	if options.verbose:
		print()
		print('Tests have been finished. %d group(s) with circular recursion found.' % recursionCnt)


if __name__ == '__main__':
	main()
