#!/usr/bin/python
import sys,os,shutil

# setting environnement
if sys.platform.startswith('win'):
	quote = '"'
	#oopath = "C:\Program Files\OpenOffice.org 2.3\program"                     # OOo2.x
	oopath = "C:\Program Files\OpenOffice.org 3\Basis\program"                  # OOo3.x
	wxpython = "C:\Python23\Lib\site-packages\wx-2.6-msw-unicode" # this is needed to force the use of the last version since wxversion does not work with freese 
	FreezePython = "C:\Program Files\cx_Freeze\FreezePython.exe"                # path to cx_Freeze executable
	encodings = "C:\Python23\Lib\encodings"	# path to the python directory containings the encodings
	name = "bibus.exe"
	base = '"'+ os.path.abspath("bibusGUI.exe") +'"'        # WinGUI.exe with bibus icon changed using a resource editor
	init = '"'+ os.path.abspath("InitBibus.py") +'"'
	shell = ""
	extra = ("C:\Python23\Lib\site-packages\pysqlite2\_sqlite.pyd",)
                # "C:\Program Files\Python2.3\Lib\site-packages\wx-2.8-msw-unicode\wx\MSVCP60.dll")									# extra files/shared lib to copy
else:
	quote = ''
	#oopath = '/usr/lib/openoffice/program'                             # OOo2.x
	oopath = '/usr/lib/openoffice/basis-link/program'                   # OOo3.x
	wxpython = '/usr/lib/python2.3/site-packages/wx-2.6-gtk2-unicode' # this is needed to force the use of the last version since wxversion does not work with freese 
	FreezePython = '/opt/cx_Freeze/FreezePython' # path to cx_Freeze executable
	encodings = "/usr/lib/python2.3/encodings"	# path to the python directory containings the encodings
	name = "bibus"
	base = "Console"
	init = os.path.abspath("InitBibus.py")
	shell = "/bin/sh"
	# you may have to adjust the files below depending on your distribution
	extra = "/usr/lib/libmysqlclient_r.so.14",\
			"/usr/lib/libsqlite3.so.0", \
			"/usr/lib/openoffice/program/libpyuno.so", \
			"/usr/lib/libpython2.3.so.1.0"

try:
	os.environ['PYTHONPATH'] = os.pathsep.join( (os.environ['PYTHONPATH'],oopath,wxpython,os.pardir) )
except:
	os.environ['PYTHONPATH'] = os.pathsep.join( (oopath,wxpython,os.pardir) )

# Utilities

def getModules():
	"""Return a list of the modules dynamically loaded from Import/Export/Format directories"""
	modulesList = []
	# getting modules in Format
	for (dirpath, dirnames, filenames) in os.walk( os.path.join('..','Format') ):
		for filename in filenames:
			if filename.endswith('.py') and not filename.startswith('__'):
				tmp = os.path.join( dirpath,filename[:-3] )
				modulesList.append( '.'.join( tmp.split(os.sep)[1:] ) )

	# getting modules in Import
	for filename in os.listdir( os.path.join('..','Import') ):
		if filename.endswith('.py') and not filename.startswith('__'):
			modulesList.append( '.'.join( ('Import',filename[:-3]) ))

	# getting modules in Export
	for filename in os.listdir( os.path.join('..','Export') ):
		if filename.endswith('.py') and not filename.startswith('__'):
			modulesList.append( '.'.join( ('Export',filename[:-3]) ))

	# python encodings. Does not work when imported with --include-modules. bug in FreezePython??
	#encodings = "/usr/lib/python2.3/encodings/"
	#for filename in os.listdir( encodings ):
		#if filename.endswith('.py') and not filename.startswith('__'):
			#modulesList.append( '.'.join( ('encodings',filename[:-3]) ))

	return modulesList

def generate_bibus_freeze():
	"""
	This function generates the file ../bibus_freeze.py
	the list of encodings to import
	followed by import bibus.py
	this file can then be freezed by cx_freeze
	this is needed because adding 
	--include-modules encoding.utf_8 ... does not work
	"""
	output = []
#	output.append('import bibus')
	# python encodings
	for filename in os.listdir( encodings ):
		if filename.endswith('.py') and not filename.startswith('__'):
				if filename == 'mbcs.py' and not sys.platform.startswith('win'): # mbcs is only available under Windows
					pass
				else:
					output.append( 'import ' + '.'.join( ('encodings',filename[:-3]) ) )
	output.append('import bibus')
	# other modules to import
	for mod in getModules():
		output.append( 'import %s'%mod )
	# strptime and MySQL, etc...
	for mod in ('_strptime','dbBibMySQL'):
		output.append( 'import %s'%mod )
	#
	return '\n'.join( output )

def cleanCVS(directory):
	"""Remove recursively all the CVS directories in 'directory'"""
	if not os.path.isdir(directory): return
	for root,dirs,files in os.walk(directory):
		if os.path.split(root)[-1] == "CVS":
			shutil.rmtree(root,True)

# end of procedures


# remove the old Freezed_Bibus
shutil.rmtree("Freezed_Bibus",True)
# we need to import all the encodings
# for this we generate the list in ../bibus_freeze.py
# see above,  --include-modules not working with encodings ?
tmpf = file( os.path.join(os.pardir,"tmp_bibus_freeze.py"), 'w')
tmpf.write( generate_bibus_freeze() )
tmpf.close()

# " --include-modules=_strptime,dbBibMySQL,%s"%getModules() + \
# cannot be used with Windows because the line is too long
# for the Shell
# we thus put in ../bibus_freeze.py all the needed
# import statements
#
f=file('tmp.bat','w')   # we use a file since the line is too long for the MSDOS Shell
f.write(quote+FreezePython+quote + \
	" -OO" + \
	" --init-script=%s"%init + \
	" --base-name=%s"%base + \
	" --target-dir=Freezed_Bibus" + \
	" --target-name=%s "%name + \
	os.path.join(os.pardir,"tmp_bibus_freeze.py") \
	)
f.close()
os.system(shell +' tmp.bat')
# copying other required files
shutil.copy( os.path.join(os.pardir,"bibus.cfg") ,"Freezed_Bibus")
shutil.copy( os.path.join(os.pardir,"bibus.config") ,"Freezed_Bibus")
shutil.copy( os.path.join(os.pardir,"MySQL_Bibus.ini") ,"Freezed_Bibus")
shutil.copy( "bibus.exe.manifest" ,"Freezed_Bibus")

os.mkdir( os.path.join("Freezed_Bibus","StyleEditor") )
shutil.copy( os.path.join(os.pardir,"StyleEditor","default_style") ,os.path.join("Freezed_Bibus","StyleEditor") )

# we need to copy the modules for the style editor even if we included them
shutil.copytree( os.path.join(os.pardir,"Format"), os.path.join("Freezed_Bibus","Format") )

# we need pixmap for the icon in the executable
shutil.copytree( os.path.join(os.pardir,"Pixmaps"), os.path.join("Freezed_Bibus","Pixmaps") )

shutil.copytree( os.path.join(os.pardir,"locale"), os.path.join("Freezed_Bibus","locale") )

os.mkdir( os.path.join("Freezed_Bibus","Setup") )
shutil.copy( os.path.join(os.pardir,"Setup","UnoConnectionListener.odg"), os.path.join("Freezed_Bibus","Setup") )

shutil.copytree( os.path.join(os.pardir,"db_models"), os.path.join("Freezed_Bibus","db_models") )

shutil.copytree( os.path.join(os.pardir,"Docs"), os.path.join("Freezed_Bibus","Docs") )

os.mkdir( os.path.join("Freezed_Bibus","Data") )
shutil.copy( os.path.join(os.pardir,"Data","journals"), os.path.join("Freezed_Bibus","Data") )

# we copy the files in extra
for f in extra:
	shutil.copy(f,"Freezed_Bibus")

# we remove the CVS directory that may have been copied
cleanCVS( "Freezed_Bibus" )
# we remove the generate ../tmp_bibus_freeze.py and tmp.bat
os.remove( os.path.join(os.pardir,"tmp_bibus_freeze.py") )
os.remove( 'tmp.bat' )
