#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# Univention Office 365 - migration script
#
# Copyright 2017-2021 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

import argparse
import json
import logging
import os
import subprocess
import sys
import univention.admin.uldap
from univention.config_registry import ConfigRegistry, handler_set, handler_unset
from univention.office365.azure_auth import AzureAuth, adconnection_alias_ucrv
from univention.office365.udm_helper import UDMHelper
from univention.office365.logging2udebug import get_logger
from univention.office365.listener import Office365Listener


conf_path = '/etc/univention-office365'
ucr = ConfigRegistry()
ucr.load()

if __name__ == '__main__':
	parser = argparse.ArgumentParser(description='Migrate a single Azure AD Office 365 connector setup to a multi-connection setup.')
	parser.add_argument('adconnection_alias', help='Value to be written to user attribute.')
	parser.add_argument('--dryrun', help='Simulate the migration, but don\'t actually change anything [default off].', action='store_true')
	args = parser.parse_args()

	logger = get_logger("office365", "o365")
	_handler = logging.StreamHandler(sys.stdout)
	_handler.setLevel(logging.INFO)
	logger.addHandler(_handler)

	if args.dryrun:
		print('Dry run - no changes will be applied.')

	if args.dryrun or AzureAuth.is_initialized(args.adconnection_alias):
		print('OK: Azure AD connection {!r} is initialized.'.format(args.adconnection_alias))
	else:
		print('Error: Azure AD connection {!r} is not initialized after copying. Exiting.'.format(args.adconnection_alias))
		sys.exit(1)

	if args.dryrun:
		ids_file = os.path.join(conf_path, 'ids.json')
	else:
		target_path = os.path.join(conf_path, args.adconnection_alias)
		ids_file = os.path.join(target_path, 'ids.json')
	with open(ids_file, 'rb') as fp:
		ids = json.load(fp)
		adconnection_id = ids['adconnection_id']

	ucrv_set = '{}{}={}'.format(adconnection_alias_ucrv, args.adconnection_alias, adconnection_id)
	print('Setting UCR {}...'.format(ucrv_set))
	if not args.dryrun:
		handler_set([ucrv_set])

	handler_unset(['office365/migrate/adconnectionalias'])

	print('Restarting the univention-directory-listener...')
	if args.dryrun:
		res = 0
	else:
		res = subprocess.call('systemctl restart univention-directory-listener.service'.split())
	print('{}: Return value {!r} for "systemctl restart univention-directory-listener.service".'.format(
		'OK' if res == 0 else 'Error',
		res)
	)

	print('Searching for users to migrate in LDAP...')
	users = UDMHelper.get_lo_o365_users(
		attributes=['uid', 'univentionOffice365Enabled', 'univentionOffice365ObjectID', 'univentionOffice365userPrincipalName', 'univentionOffice365Data', ],
		enabled='',
		additional_filter='(!(univentionOffice365ADConnectionAlias=*))'
	)
	print('Found the following users:\n')
	print('       username      | enabled |  Azure object ID')
	print('-' * 82)
	for dn in sorted(users.keys()):
		attr = users[dn]
		print('{: <20} |    {}    | {}'.format(
			attr['uid'][0],
			'x' if 'univentionOffice365Enabled' in attr and attr['univentionOffice365Enabled'][0] == '1' else ' ',
			attr.get('univentionOffice365ObjectID', [''])[0])
		)
	if users:
		print('\nSetting the Azure AD connection alias of those users to {!r}...\n'.format(args.adconnection_alias))
		lo, po = univention.admin.uldap.getAdminConnection()
		for dn in sorted(users.keys()):
			attr = users[dn]
			print('Changing {} ({})...'.format(attr['uid'][0], dn))
			modlist = [('univentionOffice365ADConnectionAlias', None, args.adconnection_alias)]

			azure_data_encoded = attr.get('univentionOffice365Data', [''])[0]

			adconnection_data = {
				args.adconnection_alias: {
					'userPrincipalName': attr.get('univentionOffice365userPrincipalName', [''])[0],
					'objectId': attr.get('univentionOffice365ObjectID', [''])[0],
				}
			}
			new_univentionOffice365Data = Office365Listener.encode_o365data(adconnection_data)
			modlist.append(('univentionOffice365Data', azure_data_encoded, new_univentionOffice365Data))

			azure_object_id = attr.get('univentionOffice365ObjectID', [''])[0]
			if azure_object_id:
				modlist.append(('univentionOffice365ObjectID', azure_object_id, None))

			azure_upn = attr.get('univentionOffice365userPrincipalName', [''])[0]
			if azure_upn:
				modlist.append(('univentionOffice365userPrincipalName', azure_upn, None))

			if not args.dryrun:
				lo.modify(dn, modlist)
	else:
		print('No users found.')
	print('Finished migrating users.\n')

	groups = UDMHelper.get_lo_o365_groups(
		attributes=['cn', 'univentionOffice365ObjectID'],
		additional_filter='(!(univentionOffice365ADConnectionAlias=*))'
	)
	print('Found the following groups:\n')
	print('           group name          | Azure object ID')
	print('-' * 69)
	for dn in sorted(groups.keys()):
		attr = groups[dn]
		print('{: <30} | {}'.format(
			attr['cn'][0],
			attr.get('univentionOffice365ObjectID', [''])[0])
		)
	if groups:
		print('\nSetting the Azure AD connection alias of those groups to {!r}...\n'.format(args.adconnection_alias))
		lo, po = univention.admin.uldap.getAdminConnection()
		for dn in sorted(groups.keys()):
			attr = groups[dn]
			print('Changing {} ({})...'.format(attr['cn'][0], dn))
			modlist = [('univentionOffice365ADConnectionAlias', None, args.adconnection_alias)]
			azure_object_id = attr.get('univentionOffice365ObjectID', [''])[0]
			if azure_object_id:
				adconnection_data = {
					args.adconnection_alias: {
						'objectId': azure_object_id,
					}
				}
				new_univentionOffice365Data = Office365Listener.encode_o365data(adconnection_data)
				modlist.append(('univentionOffice365Data', None, new_univentionOffice365Data))
				modlist.append(('univentionOffice365ObjectID', azure_object_id, None))
			if not args.dryrun:
				lo.modify(dn, modlist)
	else:
		print('No groups found.')
	print('Finished migrating groups.\n')

	print('\nEnd of migration.\n')
