""""
help       -> scons -h
compile    -> scons
clean      -> scons -c
install    -> scons install
uninstall  -> scons -c install
configure  -> scons configure prefix=/tmp/ita debug=full extraincludes=/usr/local/include:/tmp/include prefix=/usr/local

Run from a subdirectory -> scons -u
The variables are saved automatically after the first run (look at cache/kde.cache.py, ..)
"""

import os
import sys

EnsureSConsVersion(0, 96)

if os.path.isfile("/etc/debian_version"):
    os.environ['QTDIR'] = "/usr/share/qt3"

if os.path.isfile("/etc/fedora-release"):
    os.environ['QTDIR'] = "/usr/lib/qt-3.3"

if os.path.isfile("/etc/SuSE-release"):
    os.environ['QTDIR'] = "/usr/lib/qt3"

env = Environment(tools=['default', 'generic', 'qt'], toolpath=['admin'])
env['QT_LIB'] = 'qt-mt'
env.Append(ENV = {'HOME': os.environ['HOME']})

# set the CC flags. This has been changed from 'AppendUnique' to 'Append'
# because it generated compiler commands that had the CCFLAGS all summed up
# between dbl-quotes. This was not taken correctly by the g++ 4.2.1 compiler on openSuse.
#env.AppendUnique(CCFLAGS='-Dlinux -pipe -DQT_THREAD_SUPPORT -D_REENTRANT')
env.Append(CCFLAGS=' -Dlinux -pipe -DQT_THREAD_SUPPORT -D_REENTRANT' )
env.AppendUnique(CPPPATH=['/usr/include/PCSC']) # here needed for config step (for debian)

# FIXME not for for 32 bit mandriva !
if os.path.isfile("/etc/mandriva-release"):
    # FIXME should remove /usr/lib/qt3/lib from path (now warning ...)
    env.Append(LIBPATH=['/usr/lib/qt3/lib64'])

if os.path.isfile("/etc/fedora-release"):
    env.Append(LIBPATH=['/usr/lib/qt-3.3/lib'])
    env.Append(CPPPATH = ['/usr/include/wx-2.6'])

if os.path.isfile("/etc/SuSE-release"):
    env.Append(LIBPATH=['/usr/lib/qt3/lib'])

env['PREFIX'] = ARGUMENTS.get('prefix', '/usr/local')
# FIXME: the confdir is hardcoded to /usr/local/etc, as is done in the sources
#env['CONFDIR'] = ARGUMENTS.get('confdir', '/usr/local/etc')
env['CONFDIR'] = '/usr/local/etc'
env['LIBDIR'] = ARGUMENTS.get('libdir', '/usr/local/lib')

def CheckPKGConfig(context, version):
     context.Message( 'Checking for pkg-config... ' )
     ret = context.TryAction('pkg-config --atleast-pkgconfig-version=%s' % 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

if not env['HELP']:
    optionsfile=env['CACHEDIR'] + 'custom.cache.py'
    opts = Options(optionsfile)
    opts.AddOptions(('CUSTOMISCONFIGURED', 'configuration succeeded'))
    opts.AddOptions(('WITHEIDGUI', 'with eidgui'))
    opts.AddOptions(('WITHJNI', 'with eidlib JNI'))
    opts.AddOptions(('JAVA', 'JAVA_HOME'))
    opts.Update(env)

if not env['HELP'] and (env['_CONFIGURE'] or not env.has_key('CUSTOMISCONFIGURED')):
    conf = Configure(env, custom_tests = { 'CheckPKGConfig' : CheckPKGConfig,
                                           'CheckPKG' : CheckPKG })
    # pkg-config
    if not conf.CheckPKGConfig('0.15.0'):
        print 'pkg-config >= 0.15.0 not found.'
        Exit(1)

    # QT
    # FIXME what if QT 4.x installed !?
    if not conf.CheckPKG('qt-mt >= 3.3.3'):
        print 'qt-mt >= 3.3.3 not found.'
        Exit(1)

    # pcsclite
    if not conf.CheckPKG('libpcsclite >= 1.2.9'):
        print 'pcsclite >= 1.2.9 not found.'
        Exit(1)

    # openssl
    if not conf.CheckPKG('openssl >= 0.9.7'):
        print 'openssl >= 0.9.7 not found.'
        Exit(1)

    # can we build QT apps ?
    if not conf.CheckLibWithHeader('qt-mt', 'qapplication.h', 'c++', 'QApplication qapp(0,0);' ):
        Exit(1)

    # openssl
    if not (conf.CheckLibWithHeader('crypto', 'openssl/crypto.h', 'C', 'SSLeay();') and
            conf.CheckLibWithHeader('ssl', 'openssl/ssl.h', 'C', 'SSL_library_init();')):
        print 'OpenSSL not found, exiting'
        Exit(1)

    if os.path.isfile("/etc/fedora-release"):
    	env.Append(LIBPATH="/usr/lib")

    # check for wx libs
    # must be version wx 2.4 or 2.6
    if conf.CheckLib('wx_gtk-2.4') or conf.CheckLib('wx_gtk2u_core-2.6') or conf.CheckLib('wx_gtk2-2.4') or conf.CheckLib('wx_gtk2_core-2.6'):
        env['WITHEIDGUI']=1

    # check for headers
    headers = Split('''openssl/bio.h openssl/conf.h openssl/ocsp.h openssl/ssl.h 
                       pcsclite.h assert.h ctype.h float.h stdarg.h stdio.h stdlib.h string.h''')
    for header in headers:
        if not conf.CheckHeader(header):
            print 'Did not find %s header file, exiting' % (header)
            Exit(1)

    # check for STL headers
    headers = Split('algorithm map string vector')
    for header in headers:
        if not conf.CheckCXXHeader(header):
            print 'Did not find %s header file, exiting' % (header)
            Exit(1)

    # check for JNI headers (require presence of Java SDK)
    if os.environ.has_key('JAVA_HOME'):
        saveEnv = env['CPPPATH']
        javaHome = os.environ['JAVA_HOME']
        env['JAVA'] = javaHome
        env.Append(CPPPATH = [javaHome + '/include', javaHome + '/include/linux'])
        if conf.CheckHeader('jni.h'):
            env['WITHJNI']=1
        env.Replace(CPPPATH = saveEnv)

    print
    if not env.has_key('WITHEIDGUI'):
        print "Not building eidviewer: no wx_gtk 2.4 or 2.6 found"
    if not env.has_key('WITHJNI'):
        print "Not building eidlibjni: JAVA_HOME needs to point to the Java2 SDK"
    print

    env['CUSTOMISCONFIGURED']=1
    opts.Save(optionsfile, env)

    print "NOTE: to start the privacy filter and crl download services automatically at boot-time,"
    print "extra steps need to be taken (chkconfig, update-rc.d, install_initd) using the two "
    print "/etc/init.d/belgium.be-beid* files."
    print 
    env = conf.Finish()

Export('env')
#env.SConscript('src/SConscript', build_dir='build', duplicate=0)
env.SConscript('src/SConscript')

prefix = env['PREFIX']
env.Alias('install', env.Install(prefix + '/share/beid', 'doc/eID-toolkit_licensingtermsconditions Deutch.rtf'))
env.Alias('install', env.Install(prefix + '/share/beid', 'doc/eID-toolkit_licensingtermsconditions English.rtf'))
env.Alias('install', env.Install(prefix + '/share/beid', 'doc/eID-toolkit_licensingtermsconditions Francais.rtf'))
env.Alias('install', env.Install(prefix + '/share/beid', 'doc/eID-toolkit_licensingtermsconditions Nederlands.rtf'))
env.Alias('install', env.Install(prefix + '/share/beid', 'doc/DeveloperGuide.doc'))

# if you forget to add a version number, the one in the file VERSION will be used instead
#env.dist('beid', '2.52')
env.dist('beid_linux')
