#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: test automatic reconnect of uldap.py
## tags: [apptest]
## roles: [domaincontroller_master,domaincontroller_backup,domaincontroller_slave]
## exposure: dangerous
## packages:
##   - ucs-school-import

import univention.testing.ucr as ucr_test
import univention.testing.utils as utils
import univention.testing.udm
import univention.testing.ucr
import univention.uldap
import univention.admin.uldap
from thread import start_new_thread
import traceback
import time
import subprocess
from ldap.filter import filter_format

def delayed_slapd_restart():
	global restart_finished
	time.sleep(3)
	print 'Restarting slapd'
	subprocess.call(['service', 'slapd', 'restart'])
	time.sleep(5)
	print 'Restarting slapd again'
	subprocess.call(['service', 'slapd', 'restart'])
	time.sleep(3)
	print 'Restart finished'
	restart_finished = True

restart_finished = False

def main():
	global restart_finished
	with ucr_test.UCSTestConfigRegistry() as ucr:
		with univention.testing.udm.UCSTestUDM() as udm:
			account = utils.UCSTestDomainAdminCredentials()

			user_dn, username = udm.create_user()

			# test with univention.uldap and univention.admin.uldap connection objects
			for access in (
					univention.uldap.access,
					univention.admin.uldap.access):

				# get connection
				lo = access(
					host=ucr['hostname'],
					base=ucr.get('ldap/base'),
					binddn=account.binddn,
					bindpw=account.bindpw,
					start_tls=2)

				if type(lo) == tuple:
					lo = lo[0]

				print 'Starting test set with connection %r' % (lo,)

				print 'Testing lo.search operation...'
				restart_finished = False
				start_new_thread(delayed_slapd_restart, ())
				filter_s = filter_format('(uid=%s)', (account.username,))
				try:
					while not restart_finished:
						lo.search(filter=filter_s)[0][0]
				except Exception as exc:
					print traceback.format_exc()
					utils.fail('lo.search() is not restart-safe with %r: %s' % (lo, exc,))

				# test lo.modify operation
				restart_finished = False
				start_new_thread(delayed_slapd_restart, ())
				try:
					old_description = ''
					while not restart_finished:
						new_description = 'Foo bar %s' % (time.time(),)
						lo.modify(user_dn, [['description', old_description, new_description]])
						old_description = new_description
				except Exception as exc:
					print traceback.format_exc()
					utils.fail('lo.modify() is not restart-safe with %r: %s' % (lo, exc,))




if __name__ == '__main__':
	main()
