#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 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
from optparse import OptionParser, OptionGroup
import univention.admin.modules
import univention.admin.config
import univention.admin.uldap


class UCCMigration(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.access = None
		self.position = None
		self.ret = 0

	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(
			'--verbose', '-v',
			action='store_true', dest='verbose', help='Enable verbose output')

		group = OptionGroup(parser, "LDAP bind credentials")
		group.add_option(
			'--binddn',
			action='store', dest='binddn', help='LDAP bind dn for UDM CLI operation')
		group.add_option(
			'--bindpwd',
			action='store', dest='bindpwd', help='LDAP bind password for bind dn')
		parser.add_option_group(group)

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

	def main(self):
		try:
			self.parse_cmdline()
			self.get_ldap_connection()
			self.migrate()
		except Exception, e:
			self.error(str(e))

		return self.ret

	def get_ldap_connection(self):
		if self.options.binddn and self.options.bindpwd:
			self.access = univention.admin.uldap.access(
				host=self.ucr["ldap/master"],
				port=int(self.ucr.get('ldap/master/port', '7389')),
				base=self.ucr['ldap/base'],
				binddn=self.options.binddn,
				bindpw=self.options.bindpwd,
				start_tls=1)
			self.position = univention.admin.uldap.position(self.ucr['ldap/base'])
		else:
			self.access, self.position = univention.admin.uldap.getAdminConnection()
		self.debug('ldap connection established')

	def migrate(self):
		for dn, attrs in self.access.search(filter='(objectClass=univentionCorporateClient)'):
			self.debug("Migrating %s" % dn)
			changes = [
				('univentionCorporateClientBootRepartitioning', attrs.get('univentionCorporateClientBootRepartitioning', []), []),
			]
			if attrs.get('univentionCorporateClientBootRepartitioning', [])[0] == "TRUE":
				changes.append(('univentionCorporateClientBootVariant', attrs.get('univentionCorporateClientBootVariant', []), ['repartition']))

			if not self.options.dry_run:
				self.access.modify(dn, changes, ignore_license=1)


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

if __name__ == '__main__':
	main()
