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

APPNAME='semantik'
VERSION='0.6.5'

srcdir = '.'
blddir = 'build'

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

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

Params.g_autoconfig=1

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

def dist():
	import md5
	from Scripting import DistTarball
	(f, filename) = DistTarball(APPNAME, VERSION)
	f = file(filename,'rb')
	m = md5.md5()
	readBytes = 1024 # read 1024 bytes per time
	while (readBytes):
		readString = f.read(readBytes)
		m.update(readString)
		readBytes = len(readString)
	f.close()
	print filename, m.hexdigest()
	sys.exit(0)

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 Action
	#[Action.simple_action(x, 'sleep 1&& echo \\"ehlo\\" && touch ${TGT}', color='CYAN') for x in []+Action.g_actions.keys()]
	#[Action.simple_action(x, 'touch ${TGT}', color='CYAN') for x in []+Action.g_actions.keys()]
	# FIXME: why the hell is this needed?
	os.environ['LD_LIBRARY_PATH'] = env['LIBPATH_KDECORE']+':'+os.environ.get('LD_LIBRARY_PATH', '')

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

	#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.includes = '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
	ibj.install_var = 'KDE4_LIB_INSTALL_DIR'

	import time
	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 KDECORE KIO KDEUI KHTML'
	obj.uselib_local = 'nablah'
	obj.target = 'src/semantik'
	obj.install_var = 'KDE4_BIN_INSTALL_DIR'
	#obj.defines = ['''TT1=\'"%s"\'''' % time.ctime(), '''TT2='"%s"' ''' % time.ctime(), 'foo=2']

	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+'/*')

	obj = bld.create_obj('msgfmt', 'semantik')
	obj.langs=['src/po/'+x for x in 'fr es'.split()]

	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('KDE4_XDG_APPS_INSTALL_DIR', '', 'src/data/semantik.desktop')
	install_as('KDE4_ICON_INSTALL_DIR', 'hicolor/64x64/apps/semantik.png', 'src/data/hi64-app-semantik.png')
	install_as('KDE4_ICON_INSTALL_DIR', 'hicolor/48x48/apps/semantik.png', 'src/data/hi48-app-semantik.png')
	install_as('KDE4_ICON_INSTALL_DIR', 'hicolor/22x22/apps/semantik.png', 'src/data/hi22-app-semantik.png')
	install_files('KDE4_DATA_INSTALL_DIR', 'semantik', 'src/data/semantikui.rc src/data/tips')

	if Params.g_commands['install'] or Params.g_commands['uninstall']:
		lst = os.listdir('src/images')
		lst = [x for x in lst if (x.rfind('hi')>-1)]
		for x in lst:
			els = x.split('-')
			size = els[0][2:]

			uh = els[2].replace('.png', '')
			uh = 'oxygen/%sx%s/actions/%s.png' % (size, size, uh)
			install_as('KDE4_ICON_INSTALL_DIR', uh, 'src/images/%s' % x)

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.define("turlututu", '"chapeau_pointu"')

        conf.check_tool('g++ qt4')
	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']))

	try:
		conf.check_tool('kde4', tooldir='.')
		Params.pprint('GREEN', "And you even have kde4! we will use it")
	except Configure.ConfigurationError:
		#Params.pprint('YELLOW', "kde4 is disabled (missing)")
		Params.fatal('Semantik requires kde4')

	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.define('ICONS', icons)
	conf.define('VERSION', VERSION)

	conf.define('SEMANTIK_DIR', conf.env['KDE4_DATA_INSTALL_DIR']+'/semantik')
	conf.define('TEMPLATE_DIR', conf.env['KDE4_DATA_INSTALL_DIR']+'/semantik/templates/')
	conf.define('FILTER_DIR', conf.env['KDE4_DATA_INSTALL_DIR']+'/semantik/filters/')
	conf.env['PICDIR'] = conf.env['KDE4_ICON_INSTALL_DIR'] #j('share/pixmaps/')

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

	conf.env['CXXFLAGS_PYEMBED'] = [x for x in conf.env['CXXFLAGS_PYEMBED'] if x != '-g']

	conf.env['CXXFLAGS']='-O2 -pipe -Wall'# -DDEBUG=1 -g'
	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 2> /dev/null')
		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')

