#!/usr/share/ucs-test/runner python
## desc: Tests the Univention Self Service
## tags: [apptest]
## roles: [domaincontroller_master]
## exposure: dangerous
## packages:
##   - univention-self-service
##   - univention-self-service-passwordreset-umc

from __future__ import print_function
import subprocess
import time

from test_self_service import self_service_user, capture_mails
import univention.testing.strings as uts
import univention.testing.ucr as ucr_test
from univention.config_registry import handler_set


def main():
	with ucr_test.UCSTestConfigRegistry():
		handler_set(["umc/self-service/passwordreset/limit/per_user/minute=120"])
		try:
			mail = '%s@%s' % (uts.random_username(), uts.random_username())
			with self_service_user(mailPrimaryAddress=mail) as user:
				print('test with login per username')
				test_contact(user)
				test_reset_method_email(user)
				time.sleep(2)
				print('test with login per mail address')
				user.username = mail
				test_contact(user)
				test_reset_method_email(user)
		finally:
			# force all module processes to close
			subprocess.call(['systemctl', 'restart', 'univention-management-console-server'], close_fds=True)
			time.sleep(3)


def test_contact(user):
	email = 'foo@example.com'
	mobile = '+0176123456'
	user.set_contact(email=email, mobile=mobile)
	assert user.get_contact().get('email') == email, 'Setting mail address failed'


def test_reset_method_email(user):
	email = 'testuser@example.com'
	user.set_contact(email=email)
	assert 'email' in user.get_reset_methods()

	timeout = 5
	with capture_mails(timeout=timeout) as mails:
		user.send_token('email')

	mail = mails.data and mails.data[0]

	assert mail, 'No email has been received in %s seconds' % (timeout,)
	token = mail.split('and enter the following token manually:')[-1].split('Greetings from your password self service system.')[0].strip()
	assert token, 'Could not parse token from mail. Is there a token in it? %r' % (mail,)

	user.password = uts.random_string()
	user.set_password(token, user.password)

	assert user.get_contact() == {'email': email}, 'Login with the new password seems to have failed'


if __name__ == '__main__':
	main()
