###########################################################################
# 
#	This is the ldcpp construction file. To use it type scons
#	Specify arguments with scons arg=value. Argumens:
#
#      debug=1:                Compile the program with debug information
#      release=1:              Compile the program with optimizations
#      profile=1:              Compile the program with profiling information
#                              (Don't use unless you know what it does).
#      PREFIX="path":          Compile the program with PREFIX as the root
#                              for installation.
#                              eg. PREFIX=/usr/local -> ldcpp goes into
#                              PREFIX/bin/ and other files into PREFIX/share/
#      BINDIR="path":          Place the program (ldcpp executable) in BINDIR
#                              defaluts to PREFIX/bin/
#      DATADIR="path":          Place the glade and pixmap files under DATADIR
#                              defaults to PREFIX/share/
#      DOCDIR="path":          Place the program docs into DOCDIR
#                              defaults to PREFIX/share/doc/
#      FAKE_ROOT="path":       Make scons install ldcpp under a fake root
#                              (for gentoo ebuilds)
#
###########################################################################

import os, commands, string

def CheckPKGConfig(context): 
     context.Message('Checking for pkg-config... ') 
     ret = context.TryAction('pkg-config --version')[0] 
     context.Result(ret)
     return ret 
 
def CheckPKG(context, name): 
     context.Message('Checking for %s... ' % name) 
     ret = context.TryAction('pkg-config --exists \'%s\'' % name)[0] 
     context.Result(ret) 
     return ret 

def CheckDefine(context, symbol, header, library):
	testProg = """
		#include<%s>
		#ifndef %s
			#error
		#endif
		int main() {
			return 0;
		}
		""" % (header, symbol)
	context.Message('Checking for %s in %s... ' % (symbol, header))
	result = context.TryCompile(testProg, '.cc')
	context.Result(result)
	return result

def CheckCXXVersion(context, name, major, minor):
	context.Message('Checking for %s >= %d.%d...' % (name, major, minor))
	ret = commands.getoutput('%s -dumpversion' % name)

	retval = 0
	try:
		if ((string.atoi(ret[0]) == major and string.atoi(ret[2]) >= minor) 
		or (string.atoi(ret[0]) > major)):
			retval = 1
	except ValueError:
		print "Oops! No C++ compiler found!"
                
	context.Result(retval)
	return retval

# import enviroment variables from os
# this is to find headers and librarys and such
env = Environment(ENV=os.environ)

conf = Configure(env, custom_tests = {'CheckPKGConfig' : CheckPKGConfig, 
	'CheckDefine' : CheckDefine,
	'CheckPKG' : CheckPKG,
	'CheckCXXVersion' : CheckCXXVersion}) 

# This looks up the CXX enviroment variable so that people can specify
# what g++ to use on the command line (eg. prompt:> CXX=foo scons)
cxx = conf.env.Dictionary()['CXX']
if not conf.CheckCXXVersion(cxx, 3, 4):
	if WhereIs('g++-3.4') != None:
		print 'Found g++-3.4'
		cxx = 'g++-3.4'
	else:
	     print 'Compiler version check failed. g++ 3.4 or later is needed'
	     Exit(1)

# Add support for compiler caches to speed-up compilation.
if os.popen('distcc 2> /dev/null').read():
	cxx = 'distcc ' + cxx
	print 'Enabling distcc...'
if os.popen('ccache 2> /dev/null').read():
	cxx = 'ccache ' + cxx
	print 'Enabling ccache...'
conf.env.Replace(CXX = cxx)

if not conf.CheckPKGConfig(): 
     print 'pkg-config not found.' 
     Exit(1) 
 
if not conf.CheckPKG('gtk+-2.0 >= 2.6'): 
     print 'gtk+ >= 2.6 not found.' 
     Exit(1) 

if not conf.CheckPKG('gthread-2.0 >= 2.4'): 
     print 'gthread >= 2.4 not found.' 
     Exit(1) 

if not conf.CheckPKG('libglade-2.0 >= 2.4'): 
     print 'libglade >= 2.4 not found.' 
     Exit(1) 

if not conf.CheckHeader('time.h'):
	print 'Did not find the header time.h'
	print 'Can\'t live without it, sorry'
	Exit(1)

if not conf.CheckHeader('signal.h'):
	print 'Did not find the header signal.h'
	print 'Can\'t live without it, sorry'
	Exit(1)

if not conf.CheckHeader('unistd.h'):
	print 'Did not find the header unistd.h'
	print 'Can\'t live without it, sorry'
	Exit(1)
	
if not conf.CheckHeader('sys/poll.h'):
	print 'Did not find the header sys/poll.h'
	print 'Can\'t live without it, sorry'
	Exit(1)

if not conf.CheckLibWithHeader('pthread', 'pthread.h', 'c'):
	print 'Did not find the pthread library, exiting!'
	print 'Note: You might have the lib but not the headers'
	Exit(1)

if not conf.CheckLibWithHeader('z', 'zlib.h', 'c'):
	print 'Did not find the z library (gzip/z compression)'
	print 'Can\'t live without it, exiting'
	print 'Note: You might have the lib but not the headers'
	Exit(1)

if not conf.CheckLibWithHeader('bz2', 'bzlib.h', 'c'):
	print 'Did not find the bz2 library (bz2 compression)'
	print 'Can\'t live without it, exiting'
	print 'Note: You might have the lib but not the headers'
	Exit(1)

conf.env.Append(CXXFLAGS = '-D_GNU_SOURCE')

env = conf.Finish()
env.ParseConfig('pkg-config --cflags --libs libglade-2.0') 
env.ParseConfig('pkg-config --cflags --libs gthread-2.0') 
env.Append(CXXFLAGS = ['-I.', '-DENABLE_BINRELOC', '-D_FILE_OFFSET_BITS=64'])

debug = ARGUMENTS.get('debug', 0)
if int(debug):
	env.Append(CXXFLAGS = '-g -ggdb -D_DEBUG')
	env.Append(LDFLAGS = '-g -ggdb')

release = ARGUMENTS.get('release', 0)
if int(release):
	env.Append(CXXFLAGS = '-O3')

profile = ARGUMENTS.get('profile', 0)
if int(profile):
	env.Append(CXXFLAGS = '-pg')
	env.Append(LDFLAGS= '-pg')

prefix = ARGUMENTS.get('PREFIX','')
root = ARGUMENTS.get('FAKE_ROOT','')
_dir = ''
bindir = ARGUMENTS.get('BINDIR', prefix + '/bin')
datadir = ARGUMENTS.get('DATADIR', prefix + '/share')
docdir = ARGUMENTS.get('DOCDIR', prefix + '/share/doc')
if str(prefix):
	env.Append(CXXFLAGS = '-D_PREFIX=\'\"' + prefix + '\"\'')
	env.Append(CXXFLAGS = '-D_DATADIR=\'\"' + datadir + '\"\'')
_dir = root

objs = []
objs.append(SConscript('client/SConstruct', exports='env', build_dir='build/client', duplicate=0))
objs.append(SConscript('linux/SConstruct', exports='env', build_dir='build/gui', duplicate=0))
Default(env.Program('ldcpp', objs))

glade_files=['glade/favoritehubs.glade','glade/hash.glade',
	'glade/mainwindow.glade','glade/publichubs.glade',
	'glade/settingsdialog.glade','glade/downloadqueue.glade',
	'glade/finishedtransfers.glade','glade/hub.glade',
	'glade/privatemessage.glade','glade/search.glade',
	'glade/sharebrowser.glade']
pixmap_files=['pixmaps/dc++-fw.png','pixmaps/dc++.png',
	'pixmaps/favhubs.png','pixmaps/FinishedUL.png',
	'pixmaps/normal-fw.png','pixmaps/normal.png',
	'pixmaps/queue.png','pixmaps/settings.png',
	'pixmaps/dc++-fw-op.png','pixmaps/dc++-op.png',
	'pixmaps/download.png','pixmaps/FinishedDL.png',
	'pixmaps/normal-fw-op.png','pixmaps/normal-op.png',
	'pixmaps/publichubs.png','pixmaps/search.png',
	'pixmaps/upload.png','pixmaps/linuxdcpp.svg']

text_files=['Changelog.txt','Credits.txt','License.txt','Readme.txt']

env.Install(dir = _dir + datadir + '/ldcpp/glade', source = glade_files)
env.Install(dir = _dir + datadir + '/ldcpp/pixmaps', source = pixmap_files)
env.Install(dir = _dir + docdir + '/ldcpp', source = text_files)
env.Install(dir = _dir + bindir, source = 'ldcpp')

env.Alias('install',[_dir + datadir + '/ldcpp/glade',
	_dir + datadir + '/ldcpp/pixmaps',
	_dir + docdir + '/ldcpp',
	_dir + bindir])
