#!/usr/bin/env python
# Copyright 2004,2005 Pierre Martineau <pmartino@users.sourceforge.net>
# This file is part of Bibus, a bibliographic database that can
# work together with OpenOffice.org to generate bibliographic indexes.
#
# Bibus 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 2 of the License, or
# (at your option) any later version.
#
# Bibus 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 Bibus; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
#
# Compiling everything and set environment variables in bibus.cfg
import compileall,os,sys, ConfigParser
setupdir = os.path.dirname(os.path.abspath(sys.argv[0]))
sourcedir = os.path.normpath( os.path.join(setupdir , os.pardir ) )
#
def compileBibus():
	compileall.compile_dir(sourcedir)										# compile code
	os.system( """%r -O -c "import compileall; compileall.compile_dir(%r)" """ % (sys.executable,sourcedir) )	# compile optimized code
# try to find the possible OOo path and return a list of path
def find_OOpath():
	"""Looks for OpenOffice or staroffice directories"""
	if sys.platform.startswith('win'):
		pathlist = ('C:\\','C:\\Program Files','C:\\Programme')
	else:
		pathlist = ('/usr/local/lib','/opt','/usr/lib')	# linux
	#
	OOo_dirs=[]
	for path in pathlist:
		try:
			filenames = os.listdir(path)
		except OSError:
			filenames = ()
		for filen in filenames:
			if filen.lower().startswith('openoffice') or filen.lower().startswith('staroffice') or filen.lower().startswith('ooo'):
				tmp = os.path.join(path,filen)
				if os.path.isdir(tmp):
					OOo_dirs.append(os.path.join(tmp,'program'))	# path to the pyuno directory
	return OOo_dirs
# return true if pyuno is working, False otherwise
def test():
	# set environ
	if sys.platform.startswith('win'):
		LIBPATH = 'PATH'	# Windows
	else:
		LIBPATH = 'LD_LIBRARY_PATH'	# linux (unix)
	#
	try:
		os.environ['PYTHONPATH'] = os.pathsep.join( (os.environ['PYTHONPATH'],oopath) )
	except KeyError:
		os.environ['PYTHONPATH'] = oopath
	try:
		os.environ[LIBPATH] = os.pathsep.join( (os.environ[LIBPATH],oopath) )
	except KeyError:
		os.environ[LIBPATH] = oopath
	os.chdir(os.path.dirname(python))	# needed under Windows
	fin,fout,ferr=os.popen3("%s %s"%(os.path.basename(python),'"'+os.path.join(setupdir,'testuno.py'))+'"') # quoting needed for Windows
	# reset environ before returning
	os.environ['PYTHONPATH'] = os.pathsep.join( os.environ['PYTHONPATH'].split(os.pathsep)[:-1] )
	os.environ[LIBPATH] = os.pathsep.join( os.environ[LIBPATH].split(os.pathsep)[:-1] )
	# return True/False
	if ferr.read():
		return False
	else:
		return bool(fout.read().strip())
#
# trying to import wx and check the version available
try:
	import wxversion					# new multiversion install (2.5)
	wxversion.ensureMinimal('2.4')
except ImportError:
	pass
try:
	import wx
	#
	class setupApp(wx.App):
		def OnInit(self):
			return True
	#
	app=setupApp()
	if wx.VERSION[:2] < (2,4):
		wx.MessageBox( "Your wxPython version is too old (%s), please install at least wxPython 2.4" %wx.VERSION_STRING )
	else:
		wx.MessageBox( "OK, I detected a correct wxPython %s installation" %wx.VERSION_STRING )
		# reading default values
		cp = ConfigParser.ConfigParser()
		cp.read( os.path.join(sourcedir,'bibus.cfg') )
		oopath = ''
		python = sys.executable
		#
		if sys.platform.startswith('win'):
			python = os.path.normcase(python)
			if os.path.basename(python) != 'PYTHONW.EXE':
				tmp = os.path.join(os.path.dirname(python),'PYTHONW.EXE')
				if os.path.exists(tmp) and os.path.isfile(tmp):
					python = tmp	# Windows: we pick the pythonx.exe variant to avoid getting a terminal at startup
		# asking the user for the OOo path
		OOpaths = find_OOpath()
		if OOpaths:
			oopath = wx.GetSingleChoice("I found %s OpenOffice.org installations.\nPlease select the correct one,\nOr 'Cancel' to choose another location."%len(OOpaths),\
			"OpenOffice.org/program directory",OOpaths)
		# If no user choice, ask the user
		if not oopath:
			wx.MessageBox( \
"""
You did not select a valid path for you OpenOffice.org installation.
Please click in 'OK' then select the directory 'program'
located in your 'OpenOffice.org' directory.
Something like:
	/opt/OpenOffice.org1.1.3/program under GNU/linux
	C:\Program Files\OpenOffice.org1.1.3\program under Windows
""")
			# asking the location of the OOo/program to user
			try:
				oopath = wx.DirSelector("Select the 'OpenOffice.org/program' directory",OOpaths[0])
			except IndexError:
				oopath = wx.DirSelector("Select the 'OpenOffice.org/program' directory")
		#
		# saving path to $BIBUS/bibus.cfg
		cp.set('PATH','oopath',oopath)
		cp.set('PATH','python',python)
		f=file(os.path.join(sourcedir,'bibus.cfg'),'w')
		cp.write(f)
		f.close()
		#
		compileBibus()			# Compiling everything
		wx.MessageBox( "Congratulations, Setup is finished!\nStart Bibus with 'python bibusStart.py' under linux\n or double-click bibusStart.pyw under Windows" )
		#
except ImportError:
	print """
*********
* Error *
*********
	Bibus requires wxPython.
	Please install wxPython before running setup.py.
"""
#

