#!/usr/bin/env python3
# coding:utf-8

import uuid

msg0102 = 'uuid present in object: \'{0}\''
msg0103 = 'uuid not found, generating one for object: \'{0}\''
msg0104 = 'failed to inserted uuid in object: \'{0}\''
msg0105 = 'uuid successfully inserted in object: \'{0}\''
msg0106 = 'uuid not present in object: \'{0}\''
msg0107 = 'removing uuid from object: \'{0}\''
msg0108 = 'failed to remove uuid from object: \'{0}\''
msg0109 = 'uuid successfully removed from object: \'{0}\''
msg0110 = 'object \'{0}\' is neither group nor user'
msg0111 = 'no ldap data for \'{0}\', object already removed?'
msg0020 = "fetching configuration for: '{0}'"


class AfpUUID():

	def __init__(self, postcmd):

		self.auuid_config = self.__getAfpUUIDConfig()
		self.auuid = self.auuid_config['handleuuid']
		if not self.auuid: return


	def __getAfpUUIDConfig(self):

		cfg_def = {
			'handleuuid' : True,
			}
		cfg_ver = {
			'handleuuid' : ('bool', ),
			}

		# get AfpUUID configuration
		self.logger.debug(msg0020.format('AfpUUID'))
		self.config.updateDefaults('AfpUUID', cfg_def)
		self.config.updateVerify(cfg_ver)

		return self.config.getSection('AfpUUID')


	def addUUID(self):

		mod_name = self.class_name+'.addUUID'
		if not self.auuid: return

		if 'apple-generateduid' in self.ldap_data.keys():
			self.logger.info(msg0102.format(self.cn))
			return True

		# group or user or neither
		g_list = (b'posixGroup', b'groupOfNames')
		u_list = (b'person', b'organizationalPerson', b'inetOrgPerson', b'posixAccount')
		if [i for i in g_list if i in self.ldap_data['objectClass']]:
			o_item = 'apple-group'
		elif [i for i in u_list if i in self.ldap_data['objectClass']]:
			o_item = 'apple-user'
		else:
			self.logger.warn(msg0110.format(self.cn))
			return

		self.logger.debug(msg0103.format(self.cn))
		mod_list = (
			((self.dn, 'base', '(objectClass=*)', ('objectClass', 'apple-generateduid', ) ), (
				('attrib', 'add',
					(o_item, ),
					('objectClass', ), ),
				('attrib', 'add',
					(str(uuid.uuid4()).upper(), ),
					('apple-generateduid', ), ),
			)),
			)

		if not self.ldapmod.modify(mod_list):
			self.exit(1, msg0104.format(self.cn))

		self.logger.info(msg0105.format(self.cn))
		return True


	def delUUID(self):

		mod_name = self.class_name+'.delUUID'
		if not self.auuid: return

		if self.ldap_data == None:
			self.logger.info(msg0111.format(self.cn))
			return True

		if not 'apple-generateduid' in self.ldap_data.keys():
			self.logger.info(msg0106.format(self.cn))
			return True

		self.logger.debug(msg0107.format(self.cn))
		mod_list = (
			((self.dn, 'base', '(objectClass=*)', ('apple-generateduid', ) ), (
				('attrib', 'delete',
					(),
					('apple-generateduid', ), ),
			)),
			)

		if not self.ldapmod.modify(mod_list):
			self.exit(1, msg0108.format(self.cn))

		self.logger.info(msg0109.format(self.cn))
		return True

