#!/usr/share/ucs-test/runner python3
## -*- coding: utf-8 -*-
## desc: create OX context in udm and check permissions
## tags: [apptest]
## roles: [domaincontroller_master,domaincontroller_backup]
## exposure: dangerous
## packages:
##   - univention-ox
## bugs: [51562]

import subprocess
import univention.testing.strings as uts
import univention.testing.udm as testing_udm
import univention.testing.ucr as testing_ucr
from univention.ox.listener_tools import ListenerTools_RuntimeError, get_master_credentials, ox_call


ox_master_admin, ox_master_pass = get_master_credentials()


def get_context_permissions(context_id):
	p = subprocess.Popen(
		[
			"/opt/open-xchange/sbin/getmoduleaccessforcontext",
			"-A", ox_master_admin,
			"-P", ox_master_pass,
			"-c", str(context_id)
		],
		stderr=subprocess.PIPE,
		stdout=subprocess.PIPE,
	)
	stdout, stderr = p.communicate()
	return stdout.split()


def get_ox_version():
	p = subprocess.Popen(
		[
			"dpkg-query",
			"-W", "-f",
			"${Version}", "univention-ox"
		],
		stderr=subprocess.PIPE,
		stdout=subprocess.PIPE,
	)
	stdout, stderr = p.communicate()
	return stdout.strip()


def test(context_id):
	with testing_udm.UCSTestUDM() as udm, testing_ucr.UCSTestConfigRegistry() as ucr:
		ldap_base = ucr.get("ldap/base")
		mail_home_server = "{}.{}".format(ucr.get("hostname"), ucr.get("domainname"))
		udm.create_object(
		  "oxmail/oxcontext",
		  position="cn=open-xchange,{}".format(ldap_base),
		  contextid=context_id,
		  hostname=mail_home_server,
		  oxDBServer=mail_home_server,
		  oxintegrationversion=get_ox_version(),
		  oxContextName="context{}".format(context_id),
		  name="context{}".format(context_id),
		)
		template_id = ucr.get("ox/context/id", "10")
		template_keys, template_values = get_context_permissions(template_id)
		context_keys, context_values = get_context_permissions(context_id)
		assert template_keys == context_keys
		assert context_values == template_values


context_id = uts.random_int(1000, 300000)
try:
	test(context_id)
finally:
	try:
		ox_call(
			[
				"deletecontext",
				"--adminuser", ox_master_admin,
				"--adminpass={}".format(ox_master_pass),
				"-c", context_id,
			]
		)
	except ListenerTools_RuntimeError as exc:
		print(exc)
