#! /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 traceback
import sys
import logging
import zlib

from random import randrange
from optparse import OptionParser
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

if __name__ == '__main__':

	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)

	parser = OptionParser()
	parser.add_option('-m', '--modify', dest='modify', action='store_true', help='Modify users, default: dry-run')
	parser.add_option('-o', '--onlyone', dest='oneuser', help='option: uid; Only look at and modify one user (for testing purposes)')
	parser.add_option('-n', '--new-password', dest='newpassword', action='store_true', help='Set a new random password for the Azure AD user')
	parser.add_option('-i', '--invalidate-tokens', dest='invalidatetokens', action='store_true', help='Invalidate login tokens, forcing reauthentication')
	parser.add_option('--max-modifications', dest='max_modifications', default=1000, help='Invalidate tokens for a maximum of X users (default: 1000, overwrite default with UCR office365/tokens/max_modifications)')
	options, args = parser.parse_args()

	if not options.newpassword and not options.invalidatetokens:
		logger.error("At least one option of --new-password or --invalidate-tokens is required")
		exit(1)

	options.max_modifications = UCRHelper.get("office365/tokens/max_modifications", 1000)
	modified_users = 0

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

	# 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:
		reset_period_modifier = int(UCRHelper.get("office365/tokens/reset_period_modifier", 15))
	except ValueError as e:
		logger.error("UCRv office365/tokens/reset_period_modifier must contain an integer")
		exit(1)

	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)
		config = univention.admin.config.config()
	except Exception as exc:
		logger.exception("Failed to initilize Microsoft 365 token reset script: %s", exc)
		sys.exit(1)

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

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

	for ldap_user in lookup_result:
		try:
			if options.modify:
				if modified_users >= options.max_modifications:
					logger.info("Modified %s users, exiting", modified_users)
					exit(0)

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

				for alias, values in adconnection_objects.items():
					core = MSGraphApiCore(AzureAccount(alias))
					if options.newpassword:
						raise DeprecationWarning
						# core.reset_user_password(user_id=values['objectId'])
					if options.invalidatetokens:
						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
				next_mod_date = today + timedelta(days=base_reset_period + randrange(reset_period_modifier + 1))

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

				lo.modify(ldap_user[0], [('univentionOffice365TokenResetDate', ldap_user_old_reset_date, [next_mod_date.strftime("%Y%m%d")])])
				modified_users += 1
				logger.info("Modified user: %s, next reset will be %s", ldap_user[1]["uid"][0], next_mod_date.strftime("%Y-%m-%d"))
			else:
				logger.info("Would modify user: %s", ldap_user[1]["uid"][0])
		except Exception as ex:
			traceback.print_exc()
			exit(1)
