#! /usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2007 (ita)
# Tots els suggeriments són benvinguts

APPNAME='semantik'
VERSION='0.5.8'

srcdir = '.'
blddir = 'build'

import os, sys, re
import Params, Action, Task, Utils, Common, Object
from qt4 import create_rcc_task

trans = "ca fr es de it".split()

Params.g_autoconfig=0 # broken in the current version
Params.g_preprocess=0

Utils.waf_version(mini="1.1.1", maxi="1.5.9")

def compile_py(task):
	outfile = task.m_outputs[0].abspath(task.m_env)
	f = open(outfile, 'w')
	w = f.write
	w('<!DOCTYPE RCC><RCC version="1.0">\n<qresource>\n')
	for k in task.m_inputs:
		w(' <file>')
		w(k.m_name)
		w('</file>\n')
		w('</qresource>\n</RCC>')
	f.close()

def build(bld):
	env = bld.env_of_name('default')

	import ocaml
	ocaml.open_re = re.compile('open ([a-zA-Z]+)', re.M)

	import Action
	Action.simple_action('ts2qm', '${QT_LRELEASE} ${SRC} -qm ${TGT} 2> /dev/null', color='RED')
	Action.Action('py2rcc', vars=[], func=compile_py, color='BLUE')

	ibj = bld.create_obj('ocaml', 'native')
	ibj.include = 'util'
	ibj.find_sources_in_dirs('util')
	ibj.target = 'util/ocaml+twt'
	ibj.are_deps_set=1
	ibj.uselib='PP'

	bld.add_group()

	abj = bld.create_obj('ocaml', 'c_object')
	abj.env = env.copy()
	abj.source = ['src/armtlkto.c']
	abj.find_sources_in_dirs('src')
	abj.includes='. src'
	abj.target='camlprog'
	abj.are_deps_set = 1
	abj.uselib = 'TWT'
	abj.add_objects=[]
	Object.g_name_to_obj['camlprog']=abj

	ibj = bld.create_obj('qt4', 'shlib')
	ibj.find_sources_in_dirs('src/wp')
	ibj.target = 'nablah'
	ibj.uselib = 'QTCORE QTGUI'
	ibj.includes='. src src/wp'
	Object.g_name_to_obj['nablah']=ibj

	obj = bld.create_obj('qt4', 'program', 'pyembed')
	obj.find_sources_in_dirs('src src/fig', excludes=['src/armtlkto.c'])
	obj.uselib = 'QTCORE QTGUI QTXML QTSVG CAML NABLAH'
	obj.uselib_local = 'nablah'
	obj.target = 'src/semantik'

	lst = []
	for x in trans: lst.append("src/semantik_%s" % x)
	obj.lang = " ".join(lst)
	obj.langname = "tsts"
	obj.includes = 'src src/fig'
	obj.add_objects='camlprog'
	obj.post()

	obj.m_linktask.set_run_after(abj.m_tasks[-1])

	rt = 'src/templates/'

	install_files('SEMANTIK_DIR', 'flags', 'src/flags/*.svg')
	install_files('TEMPLATE_DIR', '', rt+'*.py')

	tgt = bld.env_of_name('default')['TEMPLATE_DIR']+'waf'
        if env.get_destdir(): tgt = os.path.join(env.get_destdir(), tgt.lstrip(os.sep))
	Common.do_install(os.path.abspath('waf'), tgt)

	install_files('TEMPLATE_DIR', 'pdflatex', rt+'pdflatex/*')
	for x in 'html odt odp java'.split():
		install_files('TEMPLATE_DIR', x, rt+'%s/*' % x)

	for x in "color font inner outer theme".split():
		k = 'beamer/beamermindist/themes/'
		install_files('TEMPLATE_DIR', k+x, rt+k+x+'/*')

	install_files('TEMPLATE_DIR', 'beamer/beamermindist/art/', rt+'beamer/beamermindist/art/*')
	install_files('TEMPLATE_DIR', 'beamer/beamermindist/', rt+'beamer/beamermindist/*.???')
	install_files('TEMPLATE_DIR', 'beamer/', rt+'beamer/main.tex')
	install_files('TEMPLATE_DIR', 'beamer/', rt+'beamer/wscript')

	install_files('TEMPLATE_DIR', 's5', rt+'s5/index.html')
	install_files('TEMPLATE_DIR', 's5/ui/default/', rt+'s5/ui/default/*')
	install_files('SEMANTIK_DIR', 'images', 'src/images/*.svg')
	install_files('FILTER_DIR', '', 'src/filters/*')

	install_files('DESKTOPFILES', '', 'src/data/semantik.desktop')
	install_as('PICDIR', 'semantik.png', 'src/data/hi64-app-semantik.png')

def configure(conf):
	def test(system):
		return (sys.platform.lower().rfind(system) > -1)

	err = "Semantik cannot work on %s, please install a Linux system from http://www.opensuse.org"
	if (test('linux')):
		Params.pprint('GREEN', "You are using Linux, that's good (tm)")
	elif (test('bsd')):
		Params.pprint('GREEN', "You are using a BSD system, that's good (tm)")
	elif (test('win32') or test('cygwin')):
		Params.fatal(err % "win32")
	elif (test('darwin')):
		Params.fatal(err % "osx")
	elif (test('solaris') or test('sunos')):
		Params.fatal(err % "Sun systems")


	kde_config = os.popen("which kde-config").read().strip()
	if kde_config:
		icons = os.popen('%s --path icon' % kde_config).read().strip()
	else:
		icons = '/usr/share/icons:/usr:/etc/opt/kde3/share/icons/:/opt/kde3/share/icons/:/var/lib/mandriva/kde-profiles/powerpackplus/share/icons/:/usr/share/icons/'
		if not Params.g_options.icons:
			Params.warning("For now Semantik uses a few kde icons - if you have problems seeing the icons install kde")

	if Params.g_options.icons:
		icons = Params.g_options.icons

        conf.check_tool('g++ qt4 python')
	conf.check_tool('python')
	conf.check_tool('ocaml')
	if not conf.env['CXX']: Params.fatal('Semantik requires g++ (compilation only)')
	if not conf.env['OCAMLOPT']: Params.fatal('Semantik requires ocamlopt (compilation only)')
	if not conf.env['QT_LRELEASE']: Params.fatal('Semantik requires the program lrelease (from the Qt linguist package? - compilation only)')
	if not conf.env['HAVE_QTXML']: Params.fatal('Semantik requires Qt 4')
	if not conf.env['PYTHON']: Params.fatal('Semantik requires Python >= 2.5 (development package for the compilation)')
	conf.check_python_version((2,4,2))
	conf.check_python_headers()
	if not conf.env['PYTHON_VERSION'] in "2.4 2.5 2.6 2.7".split(): Params.warning('Bad Python version %s ' % str(conf.env['PYTHON_VERSION']))


	conf.env['OCALINKFLAGS_OPT_PP']= ' str.cmxa '
	conf.env['LINKFLAGS_CAML'] = '-lasmrun -lstr -lnums'.split()
	conf.env['LIBPATH_CAML'] = conf.env['OCAMLLIB']
	conf.env['LIB_CAML'] = "m".split()
	conf.env['OCAMLFLAGS_TWT'] = '-pp default/util/ocaml+twt ' #-unsafe -noassert -inline 10'
	conf.env['CXXDEFINES']='WAF'
	conf.add_define('ICONS', icons)
	conf.add_define('VERSION', VERSION)

	def j(x):
		return os.path.join(Params.g_options.prefix, x)

	conf.add_define('SEMANTIK_DIR', j('share/semantik/'))
	conf.add_define('TEMPLATE_DIR', j('share/semantik/templates/'))
	conf.add_define('FILTER_DIR', j('share/semantik/filters/'))

	conf.env['DESKTOPFILES'] = j('share/applications/')
	conf.env['PICDIR'] = j('share/pixmaps/')

	'''e = conf.create_header_configurator()
	e.mandatory = 0
	e.name = 'aspell.h'
	#e.define = 'HAS_ASPELL'
	ret = e.run()

	if ret:
		libconf = conf.create_library_configurator()
		libconf.name   = 'aspell'
		libconf.paths = ['/usr/lib','/usr/local/lib']
		ret = libconf.run()

	if ret:
		conf.add_define('HAS_ASPELL', 1)
	else:
		Params.pprint('YELLOW', '-> Maybe you should install aspell-devel (spell checking)')
	'''

	if Params.g_options.use64:
		conf.env['shlib_INST_DIR'] = 'lib64'

	#conf.env['CXXFLAGS']='-Wall -DDEBUG=1 -g3'
	conf.write_config_header('aux.h')

	# the Debian packagers compile with --prefix=/usr and set /etc/ld.so.conf accordingly
	# the rpath is for end users installing into /usr/local/lib only
	sur = '/usr/local'
	if Params.g_options.prefix[:len(sur)] == sur:
		conf.env['RPATH_NABLAH'] = '-Wl,--rpath=/usr/local/lib'

def set_options(opt):
	opt.tool_options('qt4')
	opt.tool_options('python')
	opt.add_option('--exe', action='store_true', default=False, help='execute after the compilation (developers)')
	opt.add_option('--icons', action='store', default='', help='icon dirs where to look for kde icons (configuration)')
	opt.add_option('--use64', action='store_true', default=False, help='set the installation into lib+64 (configuration)')

def shutdown():
	if Params.g_commands['install']:
		try: os.popen('/sbin/ldconfig')
		except: pass
	if Params.g_options.exe:
		#os.popen('export LD_LIBRARY_PATH=build/default/:$LD_LIBRARY_PATH; PATH=plugins:$PATH build/default/src/semantik')
		os.popen('LD_LIBRARY_PATH=build/default/:$LD_LIBRARY_PATH build/default/src/semantik')

