#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2016-2022 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/>.

"""
Univention Microsoft 365 reset tokens
"""

import sys
import logging
import zlib

from random import randrange
from argparse import ArgumentParser
from datetime import datetime, timedelta
from logging.handlers import SysLogHandler

import univention.admin.objects

from univention.office365.microsoft.account import AzureAccount
from univention.office365.microsoft.core import MSGraphApiCore
from univention.office365.udmwrapper.udmobjects import UniventionOffice365Data
from univention.office365.logging2udebug import get_logger
from univention.office365.ucr_helper import UCRHelper


# Query local LDAP for users that are activated for O365
# invalidate all auth tokens for one or --max-modifications users


def get_customized_logger():
	logger = get_logger("office365", "o365")
	_handler = logging.StreamHandler(sys.stdout)
	_handler.setLevel(logging.INFO)
	logger.addHandler(_handler)
	_handler = SysLogHandler(address="/dev/log", facility=SysLogHandler.LOG_SYSLOG)
	_handler.setLevel(logging.INFO)
	logger.addHandler(_handler)

	return logger


logger = get_customized_logger()


def parse_arguments(args):
	parser = ArgumentParser(description="A tool to modify users and manage Azure AD passwords and authentication tokens.")

	parser.add_argument('-m', '--modify', action='store_true', help='Modify users, default: dry-run')
	parser.add_argument('-o', '--onlyone', metavar="uid", help='Only look at and modify one user (for testing purposes)')
	parser.add_argument('-i', '--invalidate-tokens', action='store_true', help='Deprecated, this option became the default and has no effect')
	parser.add_argument('--max-modifications', type=int, help='Invalidate tokens for a maximum of X users (default: 1000, permanently overwrite default with UCR office365/tokens/max_modifications)')

	options = parser.parse_args(args)

	if not options.max_modifications:
		try:
			options.max_modifications = int(UCRHelper.get("office365/tokens/max_modifications", 1000))
		except ValueError:
			logger.error("UCRv office365/tokens/max_modifications must contain an integer")
			raise

	# base period, after which user tokens get invalidated
	try:
		options.base_reset_period = int(UCRHelper.get("office365/tokens/base_reset_period", 60))
	except ValueError:
		logger.error("UCRv office365/tokens/base_reset_period must contain an integer")
		raise

	# randomize the reset period for some days, so not everyone will be reset at the same time
	# should also reduce runtime of script and azure API calls, as fewer modifications are necessary
	try:
		options.reset_period_modifier = int(UCRHelper.get("office365/tokens/reset_period_modifier", 15))
	except ValueError:
		logger.error("UCRv office365/tokens/reset_period_modifier must contain an integer")
		raise

	return options


def main(options):
	base = UCRHelper.get("ldap/base")
	try:
		lo, po = univention.admin.uldap.getAdminConnection()
		univention.admin.modules.update()
		usermod = univention.admin.modules.get('users/user')
		univention.admin.modules.init(lo, po, usermod)
	except Exception as exc:
		logger.exception(f"Failed to initilize Microsoft 365 token reset script: {exc}")
		raise

	today = datetime.today()
	today_as_string = today.strftime("%Y%m%d")
	lookup_attributes = ["univentionOffice365TokenResetDate", "univentionOffice365Data", "uid"]

	lookup_result = []
	if options.onlyone:
		ldap_filter = f"(&(univentionObjectType=users/user)(uid={options.onlyone}))"
	else:
		ldap_filter = (
			f"(&(univentionOffice365Enabled=1)(univentionObjectType=users/user)"
			f"(|(UniventionOffice365TokenResetDate<={today_as_string})"
			f"(!(UniventionOffice365TokenResetDate=*))))"
		)
	lookup_result = lo.search(filter=ldap_filter, base=base, attr=lookup_attributes)

	modified_users = 0
	for ldap_user in lookup_result:
		uid = ldap_user[1]["uid"][0].decode('utf-8')
		if not options.modify:
			logger.info(f"Would modify user: {uid}")
			continue
		if modified_users >= options.max_modifications:
			logger.info(f"Modified {modified_users} users, exiting")
			return

		try:
			adconnection_objects = UniventionOffice365Data.from_ldap(ldap_user[1]["univentionOffice365Data"][0])
		except (zlib.error, TypeError):
			logger.error("Error decoding o365data for user {uid}")
			adconnection_objects = {}
		except KeyError:
			logger.error(f"Error: user {uid} is not correctly synced to Azure (missing univentionOffice365Data attribute)")
			raise

		for alias, values in adconnection_objects.items():
			core = MSGraphApiCore(AzureAccount(alias))
			core.invalidate_all_tokens_for_user(user_id=values['objectId'])

		# modify the ldap user, set the next modification date: base_reset_period + up to period_modifier days
		modification_offset = timedelta(days=options.base_reset_period + randrange(options.reset_period_modifier + 1))
		next_modification_date = datetime.today() + modification_offset

		if "univentionOffice365TokenResetDate" in ldap_user[1]:
			ldap_user_old_reset_date = ldap_user[1]["univentionOffice365TokenResetDate"][0]
		else:
			ldap_user_old_reset_date = []

		new_token_expiry_info = [(
			'univentionOffice365TokenResetDate',
			ldap_user_old_reset_date,
			[next_modification_date.strftime("%Y%m%d").encode('utf-8')]
		)]
		lo.modify(ldap_user[0], new_token_expiry_info)
		logger.info(f"Modified user: {uid} next reset will be {next_modification_date.strftime('%Y-%m-%d')}")
		modified_users += 1


if __name__ == '__main__':
	try:
		options = parse_arguments(sys.argv[1:])
		main(options)
	except Exception:
		exit(1)
	exit(0)
