#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention Directory Manager Modules
#  check if users are member of their primary group
#
# Copyright 2004-2014 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 ldap
import sys
import os
import re
import univention.config_registry
import univention.admin.config
import univention.admin.modules
import univention.admin.objects
import univention.admin.uexceptions
from optparse import OptionParser

lo = None
co = None
position = None
configRegistry = univention.config_registry.ConfigRegistry()
configRegistry.load()
grp2childgrps = {}

class groupRecursionDetected(univention.admin.uexceptions.base):
	message='circular group recursion detected'
	def __init__(self, recursionlist):
		self.recursionlist = recursionlist


def get_ldap_connection(baseDN):
	if os.path.exists('/etc/ldap.secret'):
		univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, "using cn=admin,%s account" % baseDN)
		secretFileName = '/etc/ldap.secret'
		binddn = 'cn=admin,'+baseDN
	elif os.path.exists('/etc/machine.secret'):
		univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, "using %s account" % configRegistry.get('ldap/hostdn'))
		secretFileName = '/etc/machine.secret'
		binddn = configRegistry.get('ldap/hostdn')

	try:
		secretFile = open(secretFileName,'r')
	except IOError:
		univention.debug.debug(univention.debug.ADMIN, univention.debug.ERROR, "loading %s failed" % secretFileName)
		sys.exit(1)
	pwdLine = secretFile.readline()
	pwd = re.sub('\n','',pwdLine)

	try:
		lo=univention.admin.uldap.access(host=configRegistry['ldap/master'], base=baseDN, binddn=binddn, bindpw=pwd, start_tls=2)
	except Exception, e:
		univention.debug.debug(univention.debug.ADMIN, univention.debug.ERROR, 'authentication error: %s' % str(e))
		sys.exit(1)

	try:
		position = univention.admin.uldap.position(baseDN)
	except univention.admin.uexceptions.noObject:
		univention.debug.debug(univention.debug.ADMIN, univention.debug.ERROR, 'invalid position: %s' % baseDN)
		sys.exit(1)

	return lo, position




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

	if not dn in grp2childgrps:
		grpobj = univention.admin.objects.get(grp_module, co, 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():
	global lo, co, position

	univention.debug.init('/var/log/univention/check_group_recursion.log', 1, 0)

	basedn = configRegistry['ldap/base']

	parser = OptionParser()
	parser.add_option("-v", "--verbose", help="print debug output", dest="verbose", action="store_true")
	(options, args) = parser.parse_args()

	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)
	co = univention.admin.config.config()

	recursionCnt = 0

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

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

	univention.debug.debug(univention.debug.ADMIN, univention.debug.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()

