#!/usr/share/ucs-test/runner python2.7
## desc: Test if a schema is still activated even if it was added twice
## tags:
##  - ldapextensions
##  - apptest
## roles-not:
##  - basesystem
## packages:
##  - python-univention-lib
## exposure: dangerous

from univention.testing.debian_package import DebianPackage
from univention.testing.strings import random_name, random_int
from univention.testing.utils import fail, verify_ldap_object
from univention.config_registry import ConfigRegistry
from ldap_extension_utils import *
from time import sleep

ucr = ConfigRegistry()
ucr.load()

package_name = get_package_name()
schema_name = get_schema_name()
join_script_name = '66%s.inst' % package_name
attribute_id = get_schema_attribute_id()

joinscript_buffer = '''#!/bin/sh
VERSION=1
. /usr/share/univention-join/joinscripthelper.lib
joinscript_init
UNIVENTION_APP_IDENTIFIER="%(package_name)s-1.0"
. /usr/share/univention-lib/ldap.sh
ucs_registerLDAPExtension "$@" --schema /usr/share/%(package_name)s/%(schema_name)s || die
exit 0
''' % {'package_name': package_name, 'schema_name': schema_name}

schema_buffer = '''
attributetype ( 1.3.6.1.4.1.10176.200.10999.%(attribute_id)s NAME 'univentionFreeAttribute%(attribute_id)s'
	DESC ' unused custom attribute %(attribute_id)s '
	EQUALITY caseExactMatch
	SUBSTR caseIgnoreSubstringsMatch
	SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
''' % {'attribute_id': attribute_id}

success = False

package = DebianPackage(name=package_name)
package.create_join_script_from_buffer(join_script_name, joinscript_buffer)
package.create_usr_share_file_from_buffer(schema_name, schema_buffer)
package.build()
package.install()

call_join_script(join_script_name)

# The ldap server needs a few seconds
sleep(5)

# register the second time
call_join_script(join_script_name)
expected_dn = 'cn=%s,cn=ldapschema,cn=univention,%s' % (schema_name, ucr.get('ldap/base'))
verify_ldap_object(expected_dn, {'univentionLDAPSchemaActive': ['TRUE']})

schema = fetch_schema_from_ldap_master()
attribute_identifier = "( 1.3.6.1.4.1.10176.200.10999.%(attribute_id)s NAME 'univentionFreeAttribute%(attribute_id)s" % {'attribute_id': attribute_id}

for attribute_entry in schema[1].ldap_entry().get('attributeTypes'):
	if attribute_entry.startswith(attribute_identifier):
		print 'The schema entry was found: %s' % attribute_entry
		success = True

package.uninstall()
package.remove()

if not success:
	fail('The attribue was not found: univentionFreeAttribute%(attribute_id)s' % {'attribute_id': attribute_id})
	sys.exit(100)

# vim: set ft=python :
