#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: computerroom module settings checks
## roles: [domaincontroller_master, domaincontroller_slave]
## tags: [apptest,ucsschool]
## exposure: dangerous
## packages: [ucs-school-umc-computerroom]

from essential.computerroom import Room, Computers
from univention.testing.ucsschool import UMCConnection as OrgUMCConnection
from univention.testing.network import NetworkRedirector
from univention.testing.ucs_samba import wait_for_s4connector
import univention.testing.ucr as ucr_test
import univention.testing.ucsschool as utu
from httplib import HTTPException


class UMCConnection(OrgUMCConnection):
	"""Reauthenticates if ran into session timeout."""

	def __init__(self, *args, **kwargs):
		self.__username = None
		self.__password = None
		super(UMCConnection, self).__init__(*args, **kwargs)

	def auth(self, username, password, *args, **kwargs):
		self.__username = username
		self.__password = password
		print 'UMCConnection: authenticate with %r %r' % (username, password)
		super(UMCConnection, self).auth(username, password, *args, **kwargs)

	def request(self, *args, **kwargs):
		try:
			return super(UMCConnection, self).request(*args, **kwargs)
		except HTTPException as exc:
			if not str(exc).startswith('401') or not self.__password:
				raise
			print '#### FAILED request due to session timeout: %s; args=%r' % (exc, (args, kwargs))
			self.auth(self.__username, self.__password)
			return super(UMCConnection, self).request(*args, **kwargs)


def main():
	with utu.UCSTestSchool() as schoolenv, ucr_test.UCSTestConfigRegistry() as ucr, NetworkRedirector() as nethelper:
		school, oudn = schoolenv.create_ou(name_edudc=ucr.get('hostname'))
		teacher, teacher_dn = schoolenv.create_user(school, is_teacher=True)
		open_ldap_co = schoolenv.open_ldap_connection()

		# importing random 2 computers
		computers = Computers(open_ldap_co, school, 2, 0, 0)
		created_computers = computers.create()

		# setting computer rooms contains the created computers
		room = Room(school, host_members=created_computers[0].dn)
		# Creating the rooms
		schoolenv.create_computerroom(
			school,
			name=room.name,
			description=room.description,
			host_members=room.host_members
		)

		umc_connection = UMCConnection(ucr.get('hostname'))
		umc_connection.auth(teacher, 'univention')

		# preparing the network loop
		nethelper.add_loop(created_computers[0].ip, created_computers[1].ip)

		# the actual test
		room.test_settings(
			school,
			teacher,
			teacher_dn,
			created_computers[1].ip,
			ucr,
			umc_connection)


if __name__ == '__main__':
	main()
