#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: rename user
## tags: [apptest]
## exposure: dangerous
## packages:
##   - open-xchange-authentication-ucs (>= 7.8.4-0)
## bugs: [45605]

import time
import random
import datetime
import univention.testing.udm as testing_udm
import univention.testing.ucr as testing_ucr
import univention.testing.strings as uts
import univention.testing.utils as utils
from essential.common import OXTestEmptyQueue, OXTestEnv
from univention.ox.wait_for_ox_server import wait_for_ox_server
from univention.ox.api.http.http_api_client import OXHttpApi


wait_for_ox_server()
with OXTestEmptyQueue(), \
		testing_ucr.UCSTestConfigRegistry() as ucr, \
		testing_udm.UCSTestUDM() as udm, \
		OXTestEnv() as oxenv:

	mail_domain = ucr['mail/hosteddomains'].split()[0]

	context_id = uts.random_int(100, 300)
	print('*** Creating context {!r}...'.format(context_id))
	oxenv.create_context(context_id)
	oxenv.check_if_context_exists_in_ldap(context_id)
	oxenv.check_if_context_exists_in_ox(context_id)

	old_birthday = '{}-{:02}-{:02}'.format(random.randint(1900, 2016), random.randint(1, 12), random.randint(1, 27))
	print('*** Creating OX user with birthday {!r} in context {!r}...'.format(old_birthday, context_id))
	user_password = uts.random_string()
	old_dn, old_username = udm.create_user(
		mailPrimaryAddress='{}@{}'.format(uts.random_username(), mail_domain),
		password=user_password,
		isOxUser='OK',
		oxContext=context_id,
		oxBirthday=old_birthday,
	)
	print('*** Checking if user exists in context {!r}...'.format(context_id))
	oxenv.check_if_user_exists_in_context(old_username, context_id)
	print('*** Testing HTTP login...')
	oxenv.check_if_user_can_login(old_username, user_password)

	print('*** Checking OX users birthday attribute...')
	client = OXHttpApi(old_username, user_password)
	ox_user = client.get_user()
	ox_birthday = datetime.date.fromtimestamp(int(ox_user['birthday'] / 1000.0)).strftime('%Y-%m-%d')
	if old_birthday != ox_birthday:
		print('ox_user[birthday]={!r}'.format(ox_user['birthday']))
		print('time.timezone={!r}'.format(time.timezone))
		utils.fail('Expected {!r}, found {!r}.'.format(old_birthday, ox_birthday))
	print('*** OK: birthday of OX user is correct.')

	new_username = uts.random_username()
	print('*** Renaming user from {!r} to {!r}...'.format(old_username, new_username))
	new_dn = udm.modify_object(
		'users/user',
		dn=old_dn,
		username=new_username,
		check_for_drs_replication=True
	)

	print('*** Checking if user with old username exists in context {!r}...'.format(context_id))
	oxenv.check_if_user_exists_in_context(old_username, context_id, expected=False)
	print('*** Testing HTTP login with old username...')
	oxenv.check_if_user_can_login(old_username, user_password, expected=False)
	print('*** Checking if user with new username exists in context {!r}...'.format(context_id))
	oxenv.check_if_user_exists_in_context(new_username, context_id)
	print('*** Testing HTTP login with new username...')
	oxenv.check_if_user_can_login(new_username, user_password)

	new_birthday = '{}-{:02}-{:02}'.format(random.randint(1900, 2016), random.randint(1, 12), random.randint(1, 27))
	print('*** Changing users brithday to {!r} to trigger Bug #45605...'.format(new_birthday))
	udm.modify_object(
		'users/user',
		dn=new_dn,
		oxBirthday=new_birthday,
		check_for_drs_replication=True
	)

	client = OXHttpApi(new_username, user_password)
	ox_user = client.get_user()

	print('*** Checking OX users birthday attribute...')
	ox_birthday = datetime.date.fromtimestamp(int(ox_user['birthday'] / 1000.0)).strftime('%Y-%m-%d')
	if new_birthday != ox_birthday:
		utils.fail('Expected {!r}, found {!r}.{}'.format(
			old_birthday,
			ox_birthday,
			' Birthday was not changed.' if old_birthday == ox_birthday else '')
		)
	print('*** OK: birthday of OX user was changed.')

	# have to remove manually, because udm-test may remove the context before the user,
	# and the listener module will choke on that
	print('*** Removing user {!r} from OX context {!r}...'.format(new_username, context_id))
	udm.remove_object('users/user', dn=new_dn)
	oxenv.check_if_user_exists_in_context(new_username, context_id, expected=False)
