#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 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 sys
import ldap
import copy
from optparse import OptionParser
from univention.config_registry import ConfigRegistry
import univention.admin.modules
import univention.admin.config
import univention.admin.uldap


class ConnectionError(Exception):
	pass


class PreCheckError(Exception):
	pass


class ZarafaMigration(object):
	def debug(self, msg):
		if self.options.verbose:
			print >> sys.stderr, msg

	def message(self, msg):
		print >> sys.stderr, msg

	def error(self, msg):
		print >> sys.stderr, msg
		self.ret = 1

	def __init__(self):
		self.options = None
		self.ret = 0
		self.ucr = ConfigRegistry()

	def parse_cmdline(self):
		usage = "%prog [options]"
		parser = OptionParser(usage=usage)
		parser.add_option(
			'--dry-run', '-d',
			action='store_true', dest='dry_run', help='Do not modify objects')
		parser.add_option(
			'--dn',
			action='store', dest='dn', help='DN of zarafa contact')
		parser.add_option(
			'--verbose', '-v',
			action='store_true', dest='verbose', help='Enable verbose output')

		(self.options, _args) = parser.parse_args()

	def main(self):
		self.ucr.load()
		try:
			self.parse_cmdline()
			# self.precheck()
			self.get_ldap_connection()
			self.migrate()
		except (ldap.LDAPError), e:
			if 'info' in e:
				self.error(e.info)
			elif 'desc' in e:
				self.error(e.desc)
		except PreCheckError:
			self.error('\nError encountered during precheck, exiting')

		return self.ret

	def precheck(self):
		if not self.options.dn:
			self.error('Parameter --dn missing')
			raise PreCheckError()

	def get_ldap_connection(self):
		self.config = univention.admin.config.config()
		self.access, self.position = univention.admin.uldap.getAdminConnection()
		self.debug('ldap connection established')

	def migrate(self):
		self.debug('\nRemove ldap attributes from contacts and non-active users; move back to cn=users')
		self.debug('DN = %s' % self.options.dn)
		user_container = "cn=users,%s" % self.ucr.get('ldap/base')
		for dn, attrs in self.access.search(
			base=self.options.dn,
		):
			classes_updated = copy.deepcopy(attrs.get('objectClass', []))
			for objclass in ['zarafa-contact', 'zarafa4ucsObject']:
				if objclass in classes_updated:
					classes_updated.remove(objclass)

			objecttype_updated = copy.deepcopy(attrs.get('univentionObjectType', []))
			objecttype_updated.remove('zarafa/contact')
			objecttype_updated.append('users/user')

			changes = [
				('objectClass', attrs.get('objectClass', []), classes_updated),
				('univentionObjectType', attrs.get('univentionObjectType', []), objecttype_updated),
				('zarafa4ucsRole', attrs.get('zarafa4ucsRole', []), []),
				('zarafaAccount', attrs.get('zarafaAccount', []), []),
			]
			try:
				self.debug('Updating %s\nChanges: %s' % (dn, changes))

				part_dn = univention.admin.uldap.explodeDn(dn)[0]
				new_dn = '%s,%s' % (part_dn, user_container)
				self.debug('Moving %s to %s' % (dn, new_dn))
				if not self.options.dry_run:
					self.access.rename(dn, new_dn, ignore_license=1)
				self.debug('Modify %s' % (new_dn))
				if not self.options.dry_run:
					self.access.modify(new_dn, changes, ignore_license=1)

			except Exception as ex:
				self.error('Failed to modify %s: %s' % (dn, ex))
		self.debug('End of migrate()')


def main():
	m = ZarafaMigration()
	m.main()
	sys.exit(m.ret)

if __name__ == '__main__':
	main()
