#!/usr/bin/python
#
# Unix SMB/CIFS implementation.
# Extended attribute (re)building
# Copyright (C) Matthieu Patou <mat@matws.net> 2009
#
# Based on provision a Samba4 server by
# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
# Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008
#
#   
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#   
# This program is distributed 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 General Public License for more details.
#   
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import getopt
import optparse
import os
import sys

# Find right directory when running from source tree
sys.path.insert(0, "bin/python")

import samba
from samba.credentials import DONT_USE_KERBEROS
from samba.auth import system_session
from samba import Ldb, substitute_var, valid_netbios_name, check_all_substituted
from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError, \
		        timestring, CHANGETYPE_MODIFY, CHANGETYPE_NONE
import ldb
import samba.getopt as options
from samba.samdb import SamDB
from samba import param
from samba.provision import ProvisionPaths, ProvisionNames,provision_paths_from_lp,setup_add_ldif



parser = optparse.OptionParser("provision [options]")
sambaopts = options.SambaOptions(parser)
parser.add_option_group(sambaopts)
parser.add_option_group(options.VersionOptions(parser))
credopts = options.CredentialsOptions(parser)
parser.add_option_group(credopts)
parser.add_option("--modifymodules", help="Modify @MODULES if needed", action="store_true")
parser.add_option("--targetdir", type="string", metavar="DIR", 
		          help="Set target directory")

opts = parser.parse_args()[0]

def message(text):
	"""print a message if quiet is not set."""
	if not opts.quiet:
		print text

if len(sys.argv) == 1:
	opts.interactive = True

lp = sambaopts.get_loadparm()
smbconf = lp.configfile

creds = credopts.get_credentials(lp)

creds.set_kerberos_state(DONT_USE_KERBEROS)

session = system_session()


def get_paths(targetdir=None,smbconf=None):
	if targetdir is not None:
		print >>sys.stderr, targetdir
		if (not os.path.exists(os.path.join(targetdir, "etc"))):
			os.makedirs(os.path.join(targetdir, "etc"))
		smbconf = os.path.join(targetdir, "etc", "smb.conf")
	if smbconf is None:
			smbconf = param.default_path()

	if not os.path.exists(smbconf):
		print >>sys.stderr, "Unable to find smb.conf .. "+smbconf
		parser.print_usage()
		sys.exit(1)

	lp = param.LoadParm()
	lp.load(smbconf)
	paths = provision_paths_from_lp(lp,"foo")
	return paths

def get_partitions(credentials,session_info,paths):
# Get the partitions
	sam_ldb = Ldb(paths.samdb, session_info=session_info, credentials=credentials,lp=lp)
	attrs2 = ["partition"]
	res2 = sam_ldb.search(expression="(dn=@PARTITION)",base="", scope=SCOPE_SUBTREE, attrs=attrs2)
	partitions = []
	current = ""
	rootdn = ""
	def part_sort(x,y):
		if (len(x) > len(y)):
		 return 1	
		elif (len(x) < len(y)):
		 return -1
		else: 
			return 0
	for i in range (0,len( res2[0]["partition"])):
		part = str(res2[0]["partition"][i]).split(":")[0]
		partitions.append(part)
	partitions.sort(part_sort)

	return partitions

def modify_modules(credentials,session_info,paths):
	sam_ldb = Ldb(paths.samdb, session_info=session_info, credentials=credentials,lp=lp)
	res = sam_ldb.search(expression="(dn=@MODULES)",base="", scope=SCOPE_SUBTREE, attrs=["@LIST"])
	if(len(res) > 0):
		sam_ldb.transaction_start()
		strmodulesbefore = str(res[0]["@LIST"])
		modules = strmodulesbefore .split(",")
		prevmod = ""
		for i in range (0,len(modules)):
			if(prevmod == "asq" and modules[i] != "extended_dn_store"):
				modules.insert(i,"extended_dn_store,extended_dn_in");
			if(prevmod == "linked_attributes" and modules[i] != "extended_dn_out_ldb"):
				modules.insert(i,"extended_dn_out_ldb");
			prevmod = modules[i]

		strmodules=","
		strmodules = strmodules.join(modules)	
		if( strmodulesbefore != strmodules):
				print >>sys.stderr, "Modifying @MODULES to add extended modules"
				m = ldb.Message()
				m.dn = ldb.Dn(sam_ldb, "@MODULES")
				m["@LIST"] = ldb.MessageElement([], ldb.CHANGETYPE_DELETE, "@LIST")
				sam_ldb.modify(m)
				m["@LIST"] = ldb.MessageElement([strmodules], ldb.CHANGETYPE_ADD, "@LIST")
				sam_ldb.modify(m)
				sam_ldb.transaction_commit()
		else:
			sam_ldb.transaction_cancel()

	

def rebuild_en_dn(credentials,session_info,paths):
	lp = param.LoadParm()
	lp.load(paths.smbconf)
	names = ProvisionNames()
	names.domain = lp.get("workgroup")
	names.realm = lp.get("realm")
	names.rootdn = "DC=" + names.realm.replace(".",",DC=")
	
	attrs = ["dn","dMDLocation", "hasMasterNCs",  "msDS-hasMasterNCs",  "nCName", "serverReference",
             "member",  "objectCategory", "defaultObjectCategory" ]
	dn = ""


	partitions = get_partitions(credentials,session_info,paths)

	sam_ldb = Ldb(paths.samdb, session_info=session_info, credentials=credentials,lp=lp)
	sam_ldb.transaction_start()

	for partition in partitions:
		print >>sys.stderr, partition
		res = sam_ldb.search(expression="(objectClass=*)",base=partition, scope=SCOPE_SUBTREE, attrs=attrs)
		mod = ""
		for i in range (0,len(res)):
			dn = res[i]["dn"]
			for att in res[i]:
				if (att != "dn" and not (res[i][att] is None) ):
					mod = """
dn: %s
changetype: modify
replace: %s
""" % (dn,att)
					saveatt = []
					for j in range (0,len( res[i][att])):
						mod = mod +att +": "+str(res[i][att][j])+"\n"
						saveatt.append(str(res[i][att][j]))
					#m = ldb.Message()
					#m.dn = ldb.Dn(sam_ldb, str(dn))
					#m[att] = ldb.MessageElement(saveatt, ldb.CHANGETYPE_MODIFY, att)
					#sam_ldb.modify(m)
					sam_ldb.modify_ldif(mod)
					res3 = sam_ldb.search(expression="(&(dn=%s)(%s=*))"%(dn,att),base=partition, scope=SCOPE_SUBTREE, attrs=["dn",att])
					if( len(res3) == 0):
						print >>sys.stderr, str(dn) + " has no attr " +att
						for satt in saveatt:
							print >>sys.stderr,"	"+satt
						sam_ldb.transaction_cancel()
	sam_ldb.transaction_commit()



		
paths = get_paths(targetdir=opts.targetdir,smbconf=smbconf)

if(opts.modifymodules):
	modify_modules(creds,session,paths)

rebuild_en_dn(creds,session,paths)

