#!/usr/share/ucs-test/runner python
## desc: ucs-school-helpdesk-check
## roles: [domaincontroller_master]
## tags: [apptest]
## exposure: dangerous
## packages: [ucs-school-umc-helpdesk]

from univention.config_registry import handler_set
from univention.lib.umc_connection import UMCConnection
import subprocess
import sys
import time
import univention.testing.ucr as ucr_test
import univention.testing.ucsschool as utu
import univention.testing.utils as utils

def main():
	subprocess.call(['/usr/bin/newaliases']) # Workaround for bug 31837
	# initializing mail data
	message = time.time() * 1000
	message = '%.30f' % message
	category = 'Sonstige'
	passwd = 'univention'
	with utu.UCSTestSchool()  as schoolenv:
		# creating ou & a teacher
		schoolName, oudn = schoolenv.create_ou(displayName='')
		userName, userdn = schoolenv.create_user(
			schoolName,
			is_teacher=True,
			password=passwd)
		with ucr_test.UCSTestConfigRegistry() as ucr:
			handler_set(['ucsschool/helpdesk/recipient=root@localhost'])
			host = ucr.get('hostname')
			connection = UMCConnection(host)
			connection.auth(userName, passwd)
			params = {
				'username': userName,
				'school': schoolName,
				'category': category,
				'message': message,
				}
			result = connection.request('helpdesk/send', params)
			if not result:
				utils.fail('Message was not sent successfully')
	# time out for waiting for the message to be delivered	in seconds
	timeOut = 60
	# periodically checking the receipt of the same sent mail
	for i in xrange(timeOut):
		if message in open('/var/mail/systemmail').read():
			print 'Unique id was found in systemmail'
			returnValue = 0
			break
		else:
			returnValue = 1
			time.sleep(1)
			continue
	if returnValue:
		print 'Unique id was not found in systemmail'
	return returnValue


if __name__ == '__main__':
		sys.exit(main())
