#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# Univention Office 365 - cmdline tests
#
# Copyright 2016-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/>.

from __future__ import print_function

import argparse

from univention.config_registry import ConfigRegistry
from univention.office365.azure_handler import AzureHandler, ResourceNotFoundError
from univention.office365.azure_auth import AzureADConnectionHandler


def get_members(grp, ah):
	members = ah.get_groups_direct_members(grp['objectId'])["value"]
	member_ids = list()
	if not members:
		return list()
	else:
		member_ids = ah.directory_object_urls_to_object_ids(members)
		azure_objs = list()
		for member_id in member_ids:
			try:
				azure_objs.append(ah.list_users(objectid=member_id))
			except ResourceNotFoundError:
				# that's OK - it is probably not a user but a group
				try:
					azure_objs.append(ah.list_groups(objectid=member_id))
				except ResourceNotFoundError:
					pass
		if all(azure_obj["mailNickname"].startswith("ZZZ_deleted_") for azure_obj in azure_objs):
			return list()
	return member_ids


if __name__ == "__main__":
	parser = argparse.ArgumentParser(description="List (delete) empty groups ...")
	parser.add_argument("-d", "--delete", action="store_true", help="delete empty groups")
	parser.add_argument("connection", help="connection to use")
	args = parser.parse_args()
	if args.connection not in AzureADConnectionHandler.get_adconnection_aliases():
		parser.error("choose one of these connections: {}".format(AzureADConnectionHandler.get_adconnection_aliases()))
	ucr = ConfigRegistry()
	ucr.load()
	ah = AzureHandler(ucr, args.connection, args.connection)
	groups = ah.list_groups()
	empty_groups = list()
	if groups and groups.get('value'):
		for grp in groups['value']:
			if not grp['displayName'].startswith('ZZZ_deleted_'):
				print('Name: {displayName} Description: {description} objectId: {objectId}'.format(**grp))
				members = get_members(grp, ah)
				if members:
					for member in members:
						print('\tMember: {}'.format(member))
				else:
					empty_groups.append(grp)
	if empty_groups:
		print('')
		print('Empty groups:')
		for grp in empty_groups:
			print('Name: {displayName} Description: {description} objectId: {objectId}'.format(**grp))
			if args.delete:
				print('\tdelete empty group {displayName} ... '.format(**grp), end='')
				ah.delete_group(grp['objectId'])
				print('OK')
