#------------------------------------------------------------------------------
# ConsoleSetLibPath.py
#   Initialization script for cx_Freeze which manipulates the path so that the
# directory in which the executable is found is searched for extensions but
# no other directory is searched. The environment variable LD_LIBRARY_PATH is
# manipulated first, however, to ensure that shared libraries found in the
# target directory are found. This requires a restart of the executable because
# the environment variable LD_LIBRARY_PATH is only checked at startup.
#------------------------------------------------------------------------------

import os
import sys
import warnings
import zipimport
import ConfigParser
import urllib,urlparse

fileName = sys.path[0]
while os.path.islink(fileName): fileName = os.path.realpath(fileName)
dirName = os.path.abspath( os.path.dirname(fileName) )
# reading oopath. Remark = sys.argv[0] does not work because we are not a python script
cp=ConfigParser.ConfigParser()
cp.read( os.path.join(dirName,'bibus.cfg') )
oopath = cp.get('PATH','oopath')
oobasis = cp.get('PATH','oobasis')
ooure = cp.get('PATH','ooure')
if not os.path.isabs(oopath):
	# the path is relative to bibus install directory (needed by portable version)
	oopath = os.path.abspath( os.path.join(dirName,oopath) )
	oobasis = os.path.abspath( os.path.join(dirName,oobasis) )
	ooure = os.path.abspath( os.path.join(dirName,ooure) )
	
if sys.platform.startswith('win'):
	LIBPATH = 'PATH'	# Windows
else:
	LIBPATH = 'LD_LIBRARY_PATH'	# linux (unix)
	
paths = os.environ.get(LIBPATH, "").split(os.pathsep)

if not ooure:   # OOo2.x
	if dirName not in paths:
		if oopath not in paths:
			paths.insert(0, oopath)
		paths.insert(0, dirName)
		os.environ[LIBPATH] = os.pathsep.join(paths)
		os.execv(sys.executable, sys.argv)
else:
	if dirName not in paths:
		if oobasis not in paths:
			paths.insert(0, oobasis)
		if ooure not in paths:
			paths.insert(0, ooure)
		paths.insert(0, dirName)
		os.environ[LIBPATH] = os.pathsep.join(paths)
		os.environ["URE_BOOTSTRAP"] = urlparse.urlunparse( ('file','',urllib.pathname2url( os.path.join(oopath,"fundamental.ini") ),'','','') )
		os.execv(sys.executable, sys.argv)	  

sys.frozen = True
sys.path = [fileName, dirName]

m = __import__("__main__")
importer = zipimport.zipimporter(fileName)
code = importer.get_code(m.__name__)
exec code in m.__dict__

