# vi:filetype=python:expandtab:tabstop=4:shiftwidth=4
#
# file SConstruct
#
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
#
# \author Bo Peng
# Full author contact details are available in file CREDITS.
#
# This is a scons based building system for lyx, please refer
# to INSTALL.scons for detailed instructions.
#

import os, sys, copy, cPickle, glob, time

# determine where I am ...
#
from SCons.Node.FS import default_fs
# default_fs.SConstruct_dir is where SConstruct file is located.
scons_dir = default_fs.SConstruct_dir.path
scons_absdir = default_fs.SConstruct_dir.abspath

# if SConstruct is copied to the top source directory
if os.path.exists(os.path.join(scons_dir, 'development', 'scons', 'scons_manifest.py')):
    scons_dir = os.path.join(scons_dir, 'development', 'scons')
    scons_absdir = os.path.join(scons_absdir, 'development', 'scons')
# get the ../.. of scons_dir
top_src_dir = os.path.split(os.path.split(scons_absdir)[0])[0]

sys.path.extend([scons_absdir, os.path.join(top_src_dir, 'lib', 'doc')])

# scons_utils.py defines a few utility function
import scons_utils as utils
# import all file lists
from scons_manifest import *

# scons asks for 1.5.2, lyx requires 2.3
EnsurePythonVersion(2, 3)
# Please use at least version 0.97
EnsureSConsVersion(0, 97)

#----------------------------------------------------------
# Global definitions
#----------------------------------------------------------

# some global settings
#
# get version number from configure.ac so that JMarc does
# not have to change SConstruct during lyx release
package_version, majmin_ver, lyx_date = utils.getVerFromConfigure(top_src_dir)
package_cygwin_version = '%s-1' % package_version
boost_version = ['1_34']

if 'svn' in package_version:
    devel_version = True
    default_build_mode = 'debug'
else:
    devel_version = False
    default_build_mode = 'release'

package = 'lyx'
package_bugreport = 'lyx-devel@lists.lyx.org'
package_name = 'LyX'
package_tarname = 'lyx'
package_string = '%s %s' % (package_name, package_version)

# various cache/log files
default_log_file = 'scons_lyx.log'
opt_cache_file = 'opt.cache'


#----------------------------------------------------------
# platform dependent settings
#----------------------------------------------------------

if os.name == 'nt':
    platform_name = 'win32'
    default_prefix = 'c:/program files/lyx'
    default_with_x = False
    default_packaging_method = 'windows'
elif os.name == 'posix' and sys.platform != 'cygwin':
    platform_name = sys.platform
    default_prefix = '/usr/local'
    default_with_x = True
    default_packaging_method = 'posix'
elif os.name == 'posix' and sys.platform == 'cygwin':
    platform_name = 'cygwin'
    default_prefix = '/usr'
    default_with_x = True
    default_packaging_method = 'posix'
elif os.name == 'darwin':
    platform_name = 'macosx'
    # FIXME: macOSX default prefix?
    default_prefix = '.'
    default_with_x = False
    default_packaging_method = 'macosx'
else:  # unsupported system, assume posix behavior
    platform_name = 'others'
    default_prefix = '.'
    default_with_x = True
    default_packaging_method = 'posix'

#---------------------------------------------------------
# Handling options
#----------------------------------------------------------
#
# You can set perminant default values in config.py
if os.path.isfile('config.py'):
    print "Getting options from config.py..."
    print open('config.py').read()

opts = Options(['config.py'])
opts.AddOptions(
    # frontend
    EnumOption('frontend', 'Main GUI', 'qt4',
        allowed_values = ('qt4',) ),
    # debug or release build
    EnumOption('mode', 'Building method', default_build_mode,
        allowed_values = ('debug', 'release') ),
    # boost libraries
    EnumOption('boost',
        'Use included, system boost library, or try sytem boost first.',
        'auto', allowed_values = (
            'auto',       # detect boost, if not found, use included
            'included',   # always use included boost
            'system',     # always use system boost, fail if can not find
            ) ),
    #
    EnumOption('gettext',
        'Use included, system gettext library, or try sytem gettext first',
        'auto', allowed_values = (
            'auto',       # detect gettext, if not found, use included
            'included',   # always use included gettext
            'system',     # always use system gettext, fail if can not find
            ) ),
    #
    EnumOption('spell', 'Choose spell checker to use.', 'auto',
        allowed_values = ('aspell', 'enchant', 'pspell', 'ispell', 'auto', 'no') ),
    # packaging method
    EnumOption('packaging', 'Packaging method to use.', default_packaging_method,
        allowed_values = ('windows', 'posix', 'macosx')),
    #
    BoolOption('fast_start', 'This option is obsolete.', False),
    # No precompiled header support (too troublesome to make it work for msvc)
    # BoolOption('pch', 'Whether or not use pch', False),
    # enable assertion, (config.h has ENABLE_ASSERTIOS
    BoolOption('assertions', 'Use assertions', True),
    # config.h define _GLIBCXX_CONCEPT_CHECKS
    # Note: for earlier version of gcc (3.3) define _GLIBCPP_CONCEPT_CHECKS
    BoolOption('concept_checks', 'Enable concept checks', True),
    #
    BoolOption('nls', 'Whether or not use native language support', True),
    #
    BoolOption('profiling', 'Whether or not enable profiling', False),
    # config.h define _GLIBCXX_DEBUG and _GLIBCXX_DEBUG_PEDANTIC
    BoolOption('stdlib_debug', 'Whether or not turn on stdlib debug', False),
    # using x11?
    BoolOption('X11', 'Use x11 windows system', default_with_x),
    # use MS VC++ to build lyx
    BoolOption('use_vc', 'Use MS VC++ to build lyx (cl.exe will be probed)', None),
    #
    PathOption('qt_dir', 'Path to qt directory', None),
    #
    PathOption('qt_inc_path', 'Path to qt include directory', None),
    #
    PathOption('qt_lib_path', 'Path to qt library directory', None),
    # extra include and libpath
    PathOption('extra_inc_path', 'Extra include path', None),
    #
    PathOption('extra_lib_path', 'Extra library path', None),
    #
    PathOption('extra_bin_path', 'A convenient way to add a path to $PATH', None),
    #
    PathOption('extra_inc_path1', 'Extra include path', None),
    #
    PathOption('extra_lib_path1', 'Extra library path', None),
    #
    ('rebuild', 'Obsolete option', None),
    # can be set to a non-existing directory
    ('prefix', 'install architecture-independent files in PREFIX', default_prefix),
    # replace the default name and location of the windows installer
    ('win_installer', 'name or full path to the windows installer', None),
    # the deps package used to create minimal installer (qt and other libraries)
    ('deps_dir', 'path to the development depedency packages with zlib, iconv, zlib and qt libraries', None),
    # whether or not build bundle installer
    BoolOption('bundle', 'Whether or not build bundle installer', False),
    # the bundle directory, containing bundled applications
    PathOption('bundle_dir', 'path to the bundle dependency package with miktex setup.exe etc', None),
    # build directory, will use $mode if not set
    ('build_dir', 'Build directory', None),
    # version suffix
    ('version_suffix', 'install lyx as lyx-suffix', None),
    # how to load options
    ('load_option', '''load option from previous scons run. option can be
        yes (default): load all options
        no: do not load any option
        opt1,opt2: load specified options
        -opt1,opt2: load all options other than specified ones''', 'yes'),
    #
    ('optimization', 'optimization CCFLAGS option.', None),
    #
    PathOption('exec_prefix', 'install architecture-independent executable files in PREFIX', None),
    # log file
    ('logfile', 'save commands (not outputs) to logfile', default_log_file),
    # provided for backward compatibility
    ('dest_dir', 'install to DESTDIR. (Provided for backward compatibility only)', None),
    # environment variable can be set as options.
    ('DESTDIR', 'install to DESTDIR', None),
    ('CC', 'replace default $CC', None),
    ('LINK', 'replace default $LINK', None),
    ('CPP', 'replace default $CPP', None),
    ('CXX', 'replace default $CXX', None),
    ('CXXCPP', 'replace default $CXXCPP', None),
    ('CCFLAGS', 'replace default $CCFLAGS', None),
    ('CPPFLAGS', 'replace default $CPPFLAGS', None),
    ('LINKFLAGS', 'replace default $LINKFLAGS', None),
)

# allowed options
all_options = [x.key for x in opts.options]

# copied from SCons/Options/BoolOption.py
# We need to use them before a boolean ARGUMENTS option is available
# in env as bool.
true_strings  = ('y', 'yes', 'true', 't', '1', 'on' , 'all' )
false_strings = ('n', 'no', 'false', 'f', '0', 'off', 'none')

if ARGUMENTS.has_key('fast_start'):
    print 'fast_start option is obsolete'

# if load_option=yes (default), load saved comand line options
#
# This option can take value yes/no/opt1,opt2/-opt1,opt2
# and tries to be clever in choosing options to load
if (not ARGUMENTS.has_key('load_option') or \
    ARGUMENTS['load_option'] not in false_strings) \
    and os.path.isfile(opt_cache_file):
    cache_file = open(opt_cache_file)
    opt_cache = cPickle.load(cache_file)
    cache_file.close()
    # import cached options, but we should ignore qt_dir when frontend changes
    if ARGUMENTS.has_key('frontend') and opt_cache.has_key('frontend') \
        and ARGUMENTS['frontend'] != opt_cache['frontend'] \
        and opt_cache.has_key('qt_dir'):
        opt_cache.pop('qt_dir')
    # and we do not cache some options (dest_dir is obsolete)
    for arg in ['load_option', 'dest_dir', 'bundle']:
        if opt_cache.has_key(arg):
            opt_cache.pop(arg)
    # remove obsolete cached keys (well, SConstruct is evolving. :-)
    for arg in opt_cache.keys():
        if arg not in all_options:
            print 'Option %s is obsolete, do not load it' % arg
            opt_cache.pop(arg)
    # now, if load_option=opt1,opt2 or -opt1,opt2
    if ARGUMENTS.has_key('load_option') and \
        ARGUMENTS['load_option'] not in true_strings + false_strings:
        # if -opt1,opt2 is specified, do not load these options
        if ARGUMENTS['load_option'][0] == '-':
            for arg in ARGUMENTS['load_option'][1:].split(','):
                if opt_cache.has_key(arg):
                    opt_cache.pop(arg)
        # if opt1,opt2 is specified, only load specified options
        else:
            args = ARGUMENTS['load_option'].split(',')
            for arg in opt_cache.keys():
                if arg not in args:
                    opt_cache.pop(arg)
    # now restore options as if entered from command line
    for key in opt_cache.keys():
        if not ARGUMENTS.has_key(key):
            ARGUMENTS[key] = opt_cache[key]
            print "Restoring cached option  %s=%s" % (key, ARGUMENTS[key])
    print

# check if there is unused (or misspelled) argument
for arg in ARGUMENTS.keys():
    if arg not in all_options:
        import textwrap
        print "Unknown option '%s'... exiting." % arg
        print
        print "Available options are (check 'scons -help' for details):"
        print '    ' + '\n    '.join(textwrap.wrap(',  '.join(all_options)))
        Exit(1)

# save options used
cache_file = open(opt_cache_file, 'w')
cPickle.dump(ARGUMENTS, cache_file)
cache_file.close()

#---------------------------------------------------------
# Setting up environment
#---------------------------------------------------------

# I do not really like ENV=os.environ, but you may add it
# here if you experience some environment related problem
env = Environment(options = opts)

# set individual variables since I do not really like ENV = os.environ
env['ENV']['PATH'] = os.environ.get('PATH')
env['ENV']['HOME'] = os.environ.get('HOME')
# these are defined for MSVC
env['ENV']['LIB'] = os.environ.get('LIB')
env['ENV']['INCLUDE'] = os.environ.get('INCLUDE')

# for simplicity, use var instead of env[var]
frontend = env['frontend']
prefix = env['prefix']
mode = env['mode']

if platform_name == 'win32':
    if env.has_key('use_vc'):
        use_vc = env['use_vc']
        if WhereIs('cl.exe') is None:
            print "cl.exe is not found. Are you using the MSVC environment?"
            Exit(2)
    elif WhereIs('cl.exe') is not None:
        use_vc = True
    else:
        use_vc = False
else:
    use_vc = False

if env.has_key('build_dir') and env['build_dir'] is not None:
    env['BUILDDIR'] = env['build_dir']
else:
    # Determine the name of the build $mode
    env['BUILDDIR'] = '#' + mode

# all built libraries will go to build_dir/libs
# (This is different from the make file approach)
env['LOCALLIBPATH'] = '$BUILDDIR/libs'
env.AppendUnique(LIBPATH = ['$LOCALLIBPATH'])


# Here is a summary of variables defined in env
# 1. defined options
# 2. undefined options with a non-None default value
# 3. compiler commands and flags like CCFLAGS.
#     MSGFMT used to process po files
# 4. Variables that will be used to replace variables in some_file.in
#     lib/lyx2lyx/lyx2lyx_version.py.in
#       PACKAGE_VERSION

# full path name is used to build msvs project files
# and to replace TOP_SRCDIR in package.C
env['TOP_SRCDIR'] = Dir(top_src_dir).abspath

# determine share_dir etc
packaging_method = env.get('packaging')
if packaging_method == 'windows':
    share_dir = 'Resources'
    man_dir = 'Resources/man/man1'
    locale_dir = 'Resources/locale'
else:
    share_dir = 'share/lyx'
    locale_dir = 'share/locale'
    if platform_name == 'cygwin':
        man_dir = 'share/man/man1'
    else:
        man_dir = 'man/man1'

# program suffix: can be yes, or a string
if env.has_key('version_suffix'):
    if env['version_suffix'] in true_strings:
        program_suffix = package_version
    elif env['version_suffix'] in false_strings:
        program_suffix = ''
    else:
        program_suffix = env['version_suffix']
else:
    program_suffix = ''


# whether or not add suffix to file and directory names
add_suffix = packaging_method != 'windows'
# Absolute data directory
if mode == 'release':
    if add_suffix:
        env['LYX_DATA_DIR'] = Dir(os.path.join(prefix, share_dir + program_suffix)).abspath
    else:
        env['LYX_DATA_DIR'] = Dir(os.path.join(prefix, share_dir)).abspath
else:
    # in the debug mode, use $TOP_SRCDIR/lib to make sure lyx can be started from anyway
    # by using this directory as data directory
    env['LYX_DATA_DIR'] = os.path.join(env.subst('$TOP_SRCDIR'), 'lib')
# we need absolute path for package.C
env['LOCALEDIR'] = Dir(os.path.join(prefix, locale_dir)).abspath


#---------------------------------------------------------
# Setting building environment (Tools, compiler flags etc)
#---------------------------------------------------------

# Since Tool('mingw') will reset CCFLAGS etc, this should be
# done before getEnvVariable
if platform_name == 'win32':
    if use_vc:
        env.Tool('msvc')
        env.Tool('mslink')
    else:
        env.Tool('mingw')
        env.AppendUnique(CPPPATH = ['#c:/MinGW/include'])
        # fix a scons winres bug (there is a missing space between ${RCINCPREFIX} and ${SOURCE.dir}
        # in version 0.96.93
        env['RCCOM'] = '$RC $_CPPDEFFLAGS $RCINCFLAGS ${RCINCPREFIX} ${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET'
    

# we differentiate between hard-coded options and default options
# hard-coded options are required and will always be there
# default options can be replaced by enviromental variables or command line options
CCFLAGS_required = []
CXXFLAGS_required = []
LINKFLAGS_required = []
CCFLAGS_default = []

# if we use ms vc, the commands are fine (cl.exe and link.exe)
if use_vc:
    # C4819: The file contains a character that cannot be represented
    #   in the current code page (number)
    # C4996: foo was decleared deprecated
    CCFLAGS_required.append('/EHsc')
    CXXFLAGS_required.append('/Zc:wchar_t-')
    if mode == 'debug':
        CCFLAGS_default.extend(['/wd4819', '/wd4996', '/nologo', '/MDd'])
    else:
        CCFLAGS_default.extend(['/wd4819', '/wd4996', '/nologo', '/MD'])

# for debug/release mode
if env.has_key('optimization') and env['optimization'] is not None:
    # if user supplies optimization flags, use it anyway
    CCFLAGS_required.extend(env['optimization'].split())
    # and do not use default
    set_default_optimization_flags = False
else:
    set_default_optimization_flags = True

if mode == 'debug':
    if use_vc:
        CCFLAGS_required.append('/Zi')
        LINKFLAGS_required.extend(['/debug', '/map'])
    else:
        CCFLAGS_required.append('-g')
        CCFLAGS_default.append('-O')
elif mode == 'release' and set_default_optimization_flags:
    if use_vc:
        CCFLAGS_default.append('/O2')
    else:
        CCFLAGS_default.append('-O2')

# msvc uses separate tools for profiling
if env.has_key('profiling') and env['profiling']:
    if use_vc:
        print 'Visual C++ does not use profiling options'
    else:
        CCFLAGS_required.append('-pg')
        LINKFLAGS_required.append('-pg')

if env.has_key('warnings') and env['warnings']:
    if use_vc:
        CCFLAGS_default.append('/W2')
    else:
        # Note: autotools detect gxx version and pass -W for 3.x
        # and -Wextra for other versions of gcc
        CCFLAGS_default.append('-Wall')

# Now, set the variables as follows:
# 1. if command line option exists: replace default
# 2. then if s envronment variable exists: replace default
# 3. set variable to required + default
def setEnvVariable(env, name, required = None, default = None, split = True):
    ''' env: environment to set variable
            name: variable
            required: hardcoded options
            default: default options that can be replaced by command line or
                environment variables
            split: whether or not split obtained variable like '-02 -g'
    '''
    # 1. ARGUMENTS is already set to env[name], override default.
    if ARGUMENTS.has_key(name):
        # env[name] may be rewritten when building tools are reloaded
        # if that is the case, commandline option will override it.
        env[name] = ARGUMENTS[name]
        default = None
    # then use environment default
    elif os.environ.has_key(name):
        print "Acquiring variable %s from system environment: %s" % (name, os.environ[name])
        default = os.environ[name]
        if split:
            default = default.split()
    # the real value should be env[name] + default + required
    if split:
        value = []
        if env.has_key(name):
            value = str(env[name]).split()
        if required is not None:
            value += required
        if default is not None:
            value += default
    else:
        value = ""
        if env.has_key(name):
            value = str(env[name])
        if required is not None:
            value += " " + required
        if default is not None:
            value += " " + default
    env[name] = value
    # print name, env[name]

setEnvVariable(env, 'DESTDIR', split=False)
setEnvVariable(env, 'CC')
setEnvVariable(env, 'LINK')
setEnvVariable(env, 'CPP')
setEnvVariable(env, 'CXX')
setEnvVariable(env, 'CXXCPP')
setEnvVariable(env, 'CCFLAGS', CCFLAGS_required, CCFLAGS_default)
setEnvVariable(env, 'CXXFLAGS', CXXFLAGS_required)
setEnvVariable(env, 'CPPFLAGS')
setEnvVariable(env, 'LINKFLAGS', LINKFLAGS_required)

# if DESTDIR is not set...
if env.has_key('dest_dir'):
    print "This option is obsolete. Please use DESTDIR instead."
    env['DESTDIR'] = env['dest_dir']

#
# extra_inc_path and extra_lib_path
#
extra_inc_paths = []
if env.has_key('extra_inc_path') and env['extra_inc_path']:
    extra_inc_paths.append(env['extra_inc_path'])
if env.has_key('extra_lib_path') and env['extra_lib_path']:
    env.AppendUnique(LIBPATH = [env['extra_lib_path']])
if env.has_key('extra_inc_path1') and env['extra_inc_path1']:
    extra_inc_paths.append(env['extra_inc_path1'])
if env.has_key('extra_lib_path1') and env['extra_lib_path1']:
    env.AppendUnique(LIBPATH = [env['extra_lib_path1']])
if env.has_key('extra_bin_path') and env['extra_bin_path']:
    # only the first one is needed (a scons bug?)
    os.environ['PATH'] += os.pathsep + env['extra_bin_path']
    env.PrependENVPath('PATH', env['extra_bin_path'])
# extra_inc_paths will be used later by intlenv etc
env.AppendUnique(CPPPATH = extra_inc_paths)


#----------------------------------------------------------
# Autoconf business
#----------------------------------------------------------

conf = Configure(env,
    custom_tests = {
        'CheckPkgConfig' : utils.checkPkgConfig,
        'CheckPackage' : utils.checkPackage,
        'CheckMkdirOneArg' : utils.checkMkdirOneArg,
        'CheckSelectArgType' : utils.checkSelectArgType,
        'CheckBoostLibraries' : utils.checkBoostLibraries,
        'CheckCommand' : utils.checkCommand,
        'CheckNSIS' : utils.checkNSIS,
        'CheckCXXGlobalCstd' : utils.checkCXXGlobalCstd,
        'CheckLC_MESSAGES' : utils.checkLC_MESSAGES,
        'CheckIconvConst' : utils.checkIconvConst,
        'CheckSizeOfWChar' : utils.checkSizeOfWChar,
        'CheckDeclaration' : utils.checkDeclaration,
    }
)

# When using msvc, windows.h is required
if use_vc and not conf.CheckCHeader('windows.h'):
    print 'Windows.h is not found. Please install Windows Platform SDK.'
    print 'Please check config.log for more information.'
    Exit(1)

# pkg-config? (if not, we use hard-coded options)
if conf.CheckPkgConfig('0.15.0'):
    env['HAS_PKG_CONFIG'] = True
else:
    print 'pkg-config >= 0.1.50 is not found'
    env['HAS_PKG_CONFIG'] = False

# zlib? This is required.
if (not use_vc and not conf.CheckLibWithHeader('z', 'zlib.h', 'C')) \
    or (use_vc and not conf.CheckLibWithHeader('zdll', 'zlib.h', 'C')):
    print 'Did not find zdll.lib or zlib.h, exiting!'
    print 'Please check config.log for more information.'
    Exit(1)
if conf.CheckLib('iconv'):
    env['ICONV_LIB'] = 'iconv'
elif conf.CheckLib('libiconv'):
    env['ICONV_LIB'] = 'libiconv'
elif conf.CheckFunc('iconv_open'):
    env['ICONV_LIB'] = None
else:
    print 'Did not find iconv or libiconv, exiting!'
    print 'Please check config.log for more information.'
    Exit(1)

# check socket libs
socket_libs = []
if conf.CheckLib('socket'):
    socket_libs.append('socket')
# nsl is the network services library and provides a
# transport-level interface to networking services.
if conf.CheckLib('nsl'):
    socket_libs.append('nsl')

# check available boost libs (since lyx1.4 does not use iostream)
boost_libs = []
for lib in ['signals', 'regex']:
    if os.path.isdir(os.path.join(top_src_dir, 'boost', 'libs', lib)):
        boost_libs.append(lib)

# check boost libraries
boost_opt = ARGUMENTS.get('boost', 'auto')
# check for system boost
lib_paths = env['LIBPATH'] + ['/usr/lib', '/usr/local/lib']
inc_paths = env['CPPPATH'] + ['/usr/include', '/usr/local/include']
# default to $BUILDDIR/libs (use None since this path will be added anyway)
boost_libpath = None
# here I assume that all libraries are in the same directory
if boost_opt == 'included':
    boost_libraries = ['included_boost_%s' % x for x in boost_libs]
    included_boost = True
    env['BOOST_INC_PATH'] = '$TOP_SRCDIR/boost'
elif boost_opt == 'auto':
    res = conf.CheckBoostLibraries(boost_libs, lib_paths, inc_paths, boost_version, mode == 'debug')
    # if not found, use local boost
    if res[0] is None:
        boost_libraries = ['included_boost_%s' % x for x in boost_libs]
        included_boost = True
        env['BOOST_INC_PATH'] = '$TOP_SRCDIR/boost'
    else:
        included_boost = False
        (boost_libraries, boost_libpath, env['BOOST_INC_PATH']) = res
elif boost_opt == 'system':
    res = conf.CheckBoostLibraries(boost_libs, lib_paths, inc_paths, boost_version, mode == 'debug')
    if res[0] is None:
        print "Can not find system boost libraries with version %s " % boost_version
        print "Please supply a path through extra_lib_path and try again."
        print "Or use boost=included to use included boost libraries."
        Exit(2)
    else:
        included_boost = False
        (boost_libraries, boost_libpath, env['BOOST_INC_PATH']) = res


if boost_libpath is not None:
    env.AppendUnique(LIBPATH = [boost_libpath])


env['ENABLE_NLS'] = env['nls']

if not env['ENABLE_NLS']:
    intl_libs = []
    included_gettext = False
else:
    # check gettext libraries
    gettext_opt = ARGUMENTS.get('gettext', 'auto')
    # check for system gettext
    succ = False
    if gettext_opt in ['auto', 'system']:
        if conf.CheckFunc('gettext'):
            included_gettext = False
            intl_libs = []
            succ = True
        elif conf.CheckLib('intl'):
            included_gettext = False
            intl_libs = ['intl']
            succ = True
        else: # no found
            if gettext_opt == 'system':
                print "Can not find system gettext library"
                print "Please supply a path through extra_lib_path and try again."
                print "Or use gettext=included to use included gettext libraries."
                Exit(2)
    # now, auto and succ = false, or gettext=included
    if not succ:
        # we do not need to set LIBPATH now.
        included_gettext = True
        intl_libs = ['included_intl']


#
# check for msgfmt command
env['MSGFMT'] = conf.CheckCommand('msgfmt')
env['MSGMERGE'] = conf.CheckCommand('msgmerge')
env['XGETTEXT'] = conf.CheckCommand('xgettext')
env['MSGUNIQ'] = conf.CheckCommand('msguniq')

# if under windows, check the nsis compiler
if platform_name == 'win32':
    env['NSIS'] = conf.CheckNSIS()

# cygwin packaging requires the binaries to be stripped
if platform_name == 'cygwin':
    env['STRIP'] = conf.CheckCommand('strip')

#
# Customized builders
#
# install customized builders
env['BUILDERS']['substFile'] = Builder(action = utils.env_subst)
#env['BUILDERS']['installTOC'] = Builder(action = utils.env_toc)
env['BUILDERS']['potfiles'] = Builder(action = utils.env_potfiles)


#----------------------------------------------------------
# Generating config.h
#----------------------------------------------------------
aspell_lib = 'aspell'
# assume that we use aspell, aspelld compiled for msvc
if platform_name == 'win32' and mode == 'debug' and use_vc:
    aspell_lib = 'aspelld'

# check the existence of config.h
config_h = os.path.join(env.Dir('$BUILDDIR/src').path, 'config.h')
boost_config_h = os.path.join(env.Dir('$BUILDDIR/boost').path, 'config.h')
#
print "Creating %s..." % boost_config_h
#
utils.createConfigFile(conf,
    config_file = boost_config_h,
    config_pre = r'''/* boost/config.h.  Generated by SCons.  */

/* -*- C++ -*- */
/*
* \file config.h
* This file is part of LyX, the document processor.
* Licence details can be found in the file COPYING.
*
* This is the compilation configuration file for LyX.
* It was generated by scon.
* You might want to change some of the defaults if something goes wrong
* during the compilation.
*/

#ifndef _BOOST_CONFIG_H
#define _BOOST_CONFIG_H
''',
    headers = [
        ('ostream', 'HAVE_OSTREAM', 'cxx'),
        ('locale', 'HAVE_LOCALE', 'cxx'),
        ('sstream', 'HAVE_SSTREAM', 'cxx'),
    ],
    custom_tests = [
        (env.has_key('assertions') and env['assertions'] and mode == 'debug',
            'ENABLE_ASSERTIONS',
            'Define if you want assertions to be enabled in the code'
        ),
    ],
    types = [
        ('wchar_t', 'HAVE_WCHAR_T', None),
    ],
    config_post = '''

#if defined(HAVE_OSTREAM) && defined(HAVE_LOCALE) && defined(HAVE_SSTREAM)
#  define USE_BOOST_FORMAT 1
#else
#  define USE_BOOST_FORMAT 0
#endif

#if !defined(ENABLE_ASSERTIONS)
#  define BOOST_DISABLE_ASSERTS 1
#endif
#define BOOST_ENABLE_ASSERT_HANDLER 1

#define BOOST_DISABLE_THREADS 1
#define BOOST_NO_WSTRING 1

#ifdef __CYGWIN__
#  define BOOST_POSIX 1
#  define BOOST_POSIX_API 1
#  define BOOST_POSIX_PATH 1
#endif

#define BOOST_ALL_NO_LIB 1

/*
 * the FreeBSD libc uses UCS4, but libstdc++ has no proper wchar_t
 * support compiled in:
 * http://gcc.gnu.org/onlinedocs/libstdc++/faq/index.html#3_9
 * And we are not interested at all what libc
 * does: What we need is a 32bit wide wchar_t, and a libstdc++ that
 * has the needed wchar_t support and uses UCS4. Whether it
 * implements this with the help of libc, or whether it has own code
 * does not matter for us, because we don't use libc directly (Georg)
*/
#if defined(HAVE_WCHAR_T) && SIZEOF_WCHAR_T == 4 && !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__)
#  define USE_WCHAR_T
#endif

#endif
'''
)
#
print "\nGenerating %s..." % config_h

# AIKSAURUS_H_LOCATION
if (conf.CheckCXXHeader("Aiksaurus.h")):
    aik_location = '<Aiksaurus.h>'
elif (conf.CheckCXXHeader("Aiksaurus/Aiksaurus.h")):
    aik_location = '<Aiksaurus/Aiksaurus.h>'
else:
    aik_location = ''

# determine headers to use
spell_opt = ARGUMENTS.get('spell', 'auto')
env['USE_ASPELL'] = False
env['USE_ENCHANT'] = False
env['USE_PSPELL'] = False
env['USE_ISPELL'] = False
if spell_opt in ['auto', 'aspell'] and conf.CheckLib(aspell_lib):
    spell_engine = 'USE_ASPELL'
elif spell_opt in ['auto', 'enchant'] and conf.CheckLib('enchant'):
    spell_engine = 'USE_ENCHANT'
elif spell_opt in ['auto', 'pspell'] and conf.CheckLib('pspell'):
    spell_engine = 'USE_PSPELL'
elif spell_opt in ['auto', 'ispell'] and conf.CheckLib('ispell'):
    spell_engine = 'USE_ISPELL'
else:
    spell_engine = None

if spell_engine is not None:
    env[spell_engine] = True
else:
    if spell_opt == 'auto':
        print "Warning: Can not locate any spell checker"
    elif spell_opt != 'no':
        print "Warning: Can not locate specified spell checker:", spell_opt
        print 'Please check config.log for more information.'
        Exit(1)

# check arg types of select function
(select_arg1, select_arg234, select_arg5) = conf.CheckSelectArgType()

# check the size of wchar_t
sizeof_wchar_t = conf.CheckSizeOfWChar()
# something wrong
if sizeof_wchar_t == 0:
    print 'Error: Can not determine the size of wchar_t.'
    print 'Please check config.log for more information.'
    Exit(1)


# fill in the version info
env['VERSION_INFO'] = '''Configuration
  Host type:                      %s
  Special build flags:            %s
  C   Compiler:                   %s
  C   Compiler flags:             %s %s
  C++ Compiler:                   %s
  C++ Compiler LyX flags:         %s
  C++ Compiler flags:             %s %s
  Linker flags:                   %s
  Linker user flags:              %s
Build info:
  Builing directory:              %s
  Libraries paths:                %s
  Boost libraries:                %s
  include search path:            %s
Frontend:
  Frontend:                       %s
  Packaging:                      %s
  LyX dir:                        %s
  LyX files dir:                  %s
''' % (platform_name,
    env.subst('$CCFLAGS'), env.subst('$CC'),
    env.subst('$CPPFLAGS'), env.subst('$CFLAGS'),
    env.subst('$CXX'), env.subst('$CXXFLAGS'),
    env.subst('$CPPFLAGS'), env.subst('$CXXFLAGS'),
    env.subst('$LINKFLAGS'), env.subst('$LINKFLAGS'),
    env.subst('$LOCALLIBPATH'),
    env.subst('$LIBPATH'), str(boost_libraries),
    env.subst('$CPPPATH'),
    frontend, packaging_method,
    prefix, env['LYX_DATA_DIR'])

#
# create config.h
result = utils.createConfigFile(conf,
    config_file = config_h,
    config_pre = r'''/* config.h.  Generated by SCons.  */

/* -*- C++ -*- */
/*
* \file config.h
* This file is part of LyX, the document processor.
* Licence details can be found in the file COPYING.
*
* This is the compilation configuration file for LyX.
* It was generated by scon.
* You might want to change some of the defaults if something goes wrong
* during the compilation.
*/

#ifndef _CONFIG_H
#define _CONFIG_H
''',
    headers = [
        ('io.h', 'HAVE_IO_H', 'c'),
        ('limits.h', 'HAVE_LIMITS_H', 'c'),
        ('locale.h', 'HAVE_LOCALE_H', 'c'),
        ('process.h', 'HAVE_PROCESS_H', 'c'),
        ('stdlib.h', 'HAVE_STDLIB_H', 'c'),
        ('string.h', 'HAVE_STRING_H', 'c'),
        ('sys/stat.h', 'HAVE_SYS_STAT_H', 'c'),
        ('sys/time.h', 'HAVE_SYS_TIME_H', 'c'),
        ('sys/types.h', 'HAVE_SYS_TYPES_H', 'c'),
        ('sys/utime.h', 'HAVE_SYS_UTIME_H', 'c'),
        ('sys/socket.h', 'HAVE_SYS_SOCKET_H', 'c'),
        ('unistd.h', 'HAVE_UNISTD_H', 'c'),
        ('utime.h', 'HAVE_UTIME_H', 'c'),
        ('direct.h', 'HAVE_DIRECT_H', 'c'),
        ('istream', 'HAVE_ISTREAM', 'cxx'),
        ('ios', 'HAVE_IOS', 'cxx'),
    ],
    functions = [
        ('open', 'HAVE_OPEN', None),
        ('chmod', 'HAVE_CHMOD', None),
        ('close', 'HAVE_CLOSE', None),
        ('popen', 'HAVE_POPEN', None),
        ('pclose', 'HAVE_PCLOSE', None),
        ('_open', 'HAVE__OPEN', None),
        ('_close', 'HAVE__CLOSE', None),
        ('_popen', 'HAVE__POPEN', None),
        ('_pclose', 'HAVE__PCLOSE', None),
        ('getpid', 'HAVE_GETPID', None),
        ('_getpid', 'HAVE__GETPID', None),
        ('mkdir', 'HAVE_MKDIR', None),
        ('_mkdir', 'HAVE__MKDIR', None),
        ('mktemp', 'HAVE_MKTEMP', None),
        ('mkstemp', 'HAVE_MKSTEMP', None),
        ('strerror', 'HAVE_STRERROR', None),
        ('getcwd', 'HAVE_GETCWD', None),
        ('setenv', 'HAVE_SETENV', None),
        ('putenv', 'HAVE_PUTENV', None),
        ('fcntl', 'HAVE_FCNTL', None),
        ('mkfifo', 'HAVE_MKFIFO', None),
    ],
    declarations = [
        ('mkstemp', 'HAVE_DECL_MKSTEMP', ['unistd.h', 'stdlib.h']),
    ],
    types = [
        ('std::istreambuf_iterator<std::istream>', 'HAVE_DECL_ISTREAMBUF_ITERATOR',
            '#include <streambuf>\n#include <istream>'),
        ('wchar_t', 'HAVE_WCHAR_T', None),
        ('mode_t', 'HAVE_MODE_T', "#include <sys/types.h>"),
    ],
    libs = [
        ('gdi32', 'HAVE_LIBGDI32'),
        (('Aiksaurus', 'libAiksaurus'), 'HAVE_LIBAIKSAURUS', 'AIKSAURUS_LIB'),
    ],
    custom_tests = [
        (conf.CheckType('pid_t', includes='#include <sys/types.h>'),
            'HAVE_PID_T',
            'Define is sys/types.h does not have pid_t',
            '',
            '#define pid_t int',
        ),
        (conf.CheckCXXGlobalCstd(),
            'CXX_GLOBAL_CSTD',
            'Define if your C++ compiler puts C library functions in the global namespace'
        ),
        (conf.CheckMkdirOneArg(),
            'MKDIR_TAKES_ONE_ARG',
            'Define if mkdir takes only one argument.'
        ),
        (conf.CheckIconvConst(),
            'ICONV_CONST',
            'Define as const if the declaration of iconv() needs const.',
            '#define ICONV_CONST const',
            '#define ICONV_CONST',
        ),
        (conf.CheckLC_MESSAGES(),
            'HAVE_LC_MESSAGES',
            'Define if your <locale.h> file defines LC_MESSAGES.'
        ),
        (devel_version, 'DEVEL_VERSION', 'Whether or not a development version'),
        (env['nls'],
            'ENABLE_NLS',
            "Define to 1 if translation of program messages to the user's native anguage is requested.",
        ),
        (env['nls'] and not included_gettext,
            'HAVE_GETTEXT',
            'Define to 1 if using system gettext library'
        ),
        (env.has_key('concept_checks') and env['concept_checks'],
            '_GLIBCXX_CONCEPT_CHECKS',
            'libstdc++ concept checking'
        ),
        (env.has_key('stdlib_debug') and env['stdlib_debug'],
            '_GLIBCXX_DEBUG',
            'libstdc++ debug mode'
        ),
        (env.has_key('stdlib_debug') and env['stdlib_debug'],
            '_GLIBCXX_DEBUG_PEDANTIC',
            'libstdc++ pedantic debug mode'
        ),
        (os.name != 'nt', 'BOOST_POSIX',
            'Indicates to boost < 1.34 which API to use (posix or windows).'
        ),
        (os.name != 'nt', 'BOOST_POSIX_API',
            'Indicates to boost 1.34 which API to use (posix or windows).'
        ),
        (os.name != 'nt', 'BOOST_POSIX_PATH',
            'Indicates to boost 1.34 which path style to use (posix or windows).'
        ),
        (spell_engine is not None, spell_engine,
            'Spell engine to use'
        ),
        # we need to know the byte order for unicode conversions
        (sys.byteorder == 'big', 'WORDS_BIGENDIAN',
            'Define to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel and VAX).'
        ),
    ],
    extra_items = [
        ('#define PACKAGE "%s%s"' % (package, program_suffix),
            'Name of package'),
        ('#define PACKAGE_BUGREPORT "%s"' % package_bugreport,
            'Define to the address where bug reports for this package should be sent.'),
        ('#define PACKAGE_NAME "%s"' % package_name,
            'Define to the full name of this package.'),
        ('#define PACKAGE_STRING "%s"' % package_string,
            'Define to the full name and version of this package.'),
        ('#define PACKAGE_TARNAME "%s"' % package_tarname,
            'Define to the one symbol short name of this package.'),
        ('#define PACKAGE_VERSION "%s"' % package_version,
            'Define to the version of this package.'),
        ('#define VERSION_INFO "%s"' % env['VERSION_INFO'].replace('\n', '\\n'),
            'Full version info'),
        ('#define LYX_DIR_VER "LYX_DIR_%sx"' % majmin_ver,
            'Versioned env var for system dir'),
        ('#define LYX_USERDIR_VER "LYX_USERDIR_%sx"' % majmin_ver,
            'Versioned env var for user dir'),
        ('#define LYX_DATE "%s"' % lyx_date,
            'Date of release'),
        ('#define PROGRAM_SUFFIX "%s"' % program_suffix,
            'Program version suffix'),
        ('#define LYX_ABS_INSTALLED_DATADIR "%s"' % env.subst('$LYX_DATA_DIR').replace('\\', '/'),
            'Hard coded system support directory'),
        ('#define LYX_ABS_INSTALLED_LOCALEDIR "%s"' % env.subst('$LOCALEDIR').replace('\\', '/'),
            'Hard coded locale directory'),
        ('#define LYX_ABS_TOP_SRCDIR "%s"' % env.subst('$TOP_SRCDIR').replace('\\', '/'),
            'Top source directory'),
        ('#define BOOST_ALL_NO_LIB 1',
            'disable automatic linking of boost libraries.'),
        ('#define USE_%s_PACKAGING 1' % packaging_method.upper(),
            'Packaging method'),
        ('#define AIKSAURUS_H_LOCATION ' + aik_location,
            'Aiksaurus include file'),
        ('#define SELECT_TYPE_ARG1 %s' % select_arg1,
            "Define to the type of arg 1 for `select'."),
        ('#define SELECT_TYPE_ARG234 %s' % select_arg234,
            "Define to the type of arg 2, 3, 4 for `select'."),
        ('#define SELECT_TYPE_ARG5 %s' % select_arg5,
            "Define to the type of arg 5 for `select'."),
        ('#define SIZEOF_WCHAR_T %d' % sizeof_wchar_t,
            'Define to be the size of type wchar_t'),
    ],
    config_post = '''/************************************************************
** You should not need to change anything beyond this point */

#ifndef HAVE_STRERROR
#if defined(__cplusplus)
extern "C"
#endif
char * strerror(int n);
#endif

#include <../boost/config.h>

#endif
'''
)

# these keys are needed in env
for key in ['USE_ASPELL', 'USE_ENCHANT', 'USE_PSPELL', 'USE_ISPELL',\
    'HAVE_FCNTL', 'HAVE_LIBGDI32', 'HAVE_LIBAIKSAURUS', 'AIKSAURUS_LIB']:
    # USE_ASPELL etc does not go through result
    if result.has_key(key):
        env[key] = result[key]

#
# if nls=yes and gettext=included, create intl/config.h
# intl/libintl.h etc
#
intl_config_h = os.path.join(env.Dir('$BUILDDIR/intl').path, 'config.h')
if env['nls'] and included_gettext:
    #
    print "Creating %s..." % intl_config_h
    #
    # create intl/config.h
    result = utils.createConfigFile(conf,
        config_file = intl_config_h,
        config_pre = r'''/* intl/config.h.  Generated by SCons.  */

/* -*- C++ -*- */
/*
* \file config.h
* This file is part of LyX, the document processor.
* Licence details can be found in the file COPYING.
*
* This is the compilation configuration file for LyX.
* It was generated by scon.
* You might want to change some of the defaults if something goes wrong
* during the compilation.
*/

#ifndef _INTL_CONFIG_H
#define _INTL_CONFIG_H
''',
        headers = [
            ('unistd.h', 'HAVE_UNISTD_H', 'c'),
            ('inttypes.h', 'HAVE_INTTYPES_H', 'c'),
            ('string.h', 'HAVE_STRING_H', 'c'),
            ('strings.h', 'HAVE_STRINGS_H', 'c'),
            ('argz.h', 'HAVE_ARGZ_H', 'c'),
            ('limits.h', 'HAVE_LIMITS_H', 'c'),
            ('alloca.h', 'HAVE_ALLOCA_H', 'c'),
            ('stddef.h', 'HAVE_STDDEF_H', 'c'),
            ('stdint.h', 'HAVE_STDINT_H', 'c'),
            ('sys/param.h', 'HAVE_SYS_PARAM_H', 'c'),
        ],
        functions = [
            ('getcwd', 'HAVE_GETCWD', None),
            ('stpcpy', 'HAVE_STPCPY', None),
            ('strcasecmp', 'HAVE_STRCASECMP', None),
            ('strdup', 'HAVE_STRDUP', None),
            ('strtoul', 'HAVE_STRTOUL', None),
            ('alloca', 'HAVE_ALLOCA', None),
            ('__fsetlocking', 'HAVE___FSETLOCKING', None),
            ('mempcpy', 'HAVE_MEMPCPY', None),
            ('__argz_count', 'HAVE___ARGZ_COUNT', None),
            ('__argz_next', 'HAVE___ARGZ_NEXT', None),
            ('__argz_stringify', 'HAVE___ARGZ_STRINGIFY', None),
            ('setlocale', 'HAVE_SETLOCALE', None),
            ('tsearch', 'HAVE_TSEARCH', None),
            ('getegid', 'HAVE_GETEGID', None),
            ('getgid', 'HAVE_GETGID', None),
            ('getuid', 'HAVE_GETUID', None),
            ('wcslen', 'HAVE_WCSLEN', None),
            ('asprintf', 'HAVE_ASPRINTF', None),
            ('wprintf', 'HAVE_WPRINTF', None),
            ('snprintf', 'HAVE_SNPRINTF', None),
            ('printf', 'HAVE_POSIX_PRINTF', None),
            ('fcntl', 'HAVE_FCNTL', None),
        ],
        types = [
            ('intmax_t', 'HAVE_INTMAX_T', None),
            ('long double', 'HAVE_LONG_DOUBLE', None),
            ('long long', 'HAVE_LONG_LONG', None),
            ('wchar_t', 'HAVE_WCHAR_T', None),
            ('wint_t', 'HAVE_WINT_T', None),
            ('uintmax_t', 'HAVE_INTTYPES_H_WITH_UINTMAX', '#include <inttypes.h>'),
            ('uintmax_t', 'HAVE_STDINT_H_WITH_UINTMAX', '#include <stdint.h>'),
        ],
        libs = [
            ('c', 'HAVE_LIBC'),
        ],
        custom_tests = [
            (conf.CheckLC_MESSAGES(),
                'HAVE_LC_MESSAGES',
                'Define if your <locale.h> file defines LC_MESSAGES.'
            ),
            (conf.CheckIconvConst(),
                'ICONV_CONST',
                'Define as const if the declaration of iconv() needs const.',
                '#define ICONV_CONST const',
                '#define ICONV_CONST',
            ),
            (conf.CheckType('intmax_t', includes='#include <stdint.h>') or \
            conf.CheckType('intmax_t', includes='#include <inttypes.h>'),
                'HAVE_INTMAX_T',
                "Define to 1 if you have the `intmax_t' type."
            ),
            (env.has_key('nls') and env['nls'],
                'ENABLE_NLS',
                "Define to 1 if translation of program messages to the user's native anguage is requested.",
            ),
        ],
        extra_items = [
            ('#define HAVE_ICONV 1', 'Define if iconv or libiconv is found'),
            ('#define SIZEOF_WCHAR_T %d' % sizeof_wchar_t,
                'Define to be the size of type wchar_t'),
        ],
        config_post = '#endif'
    )

    # these keys are needed in env
    for key in ['HAVE_ASPRINTF', 'HAVE_WPRINTF', 'HAVE_SNPRINTF', \
        'HAVE_POSIX_PRINTF', 'HAVE_LIBC']:
        # USE_ASPELL etc does not go through result
        if result.has_key(key):
            env[key] = result[key]


# this looks misplaced, but intl/libintl.h is needed by src/message.C
if env['nls'] and included_gettext:
    # libgnuintl.h.in => libintl.h
    env.Depends('$TOP_SRCDIR/intl/libintl.h', '$BUILDDIR/intl/config.h')
    env.substFile('$BUILDDIR/intl/libintl.h', '$TOP_SRCDIR/intl/libgnuintl.h.in')
    env.Command('$BUILDDIR/intl/libgnuintl.h', '$BUILDDIR/intl/libintl.h',
        [Copy('$TARGET', '$SOURCE')])

#
# Finish auto-configuration
env = conf.Finish()

#----------------------------------------------------------
# Now set up our build process accordingly
#----------------------------------------------------------

if env['ICONV_LIB'] is None:
    system_libs = []
else:
    system_libs = [env['ICONV_LIB']]
if platform_name in ['win32', 'cygwin']:
    # the final link step needs stdc++ to succeed under mingw
    # FIXME: shouldn't g++ automatically link to stdc++?
    if use_vc:
        system_libs += ['ole32', 'shlwapi', 'psapi', 'shell32', 'advapi32', 'zdll']
    else:
        system_libs += ['shlwapi', 'psapi', 'stdc++', 'z']
elif platform_name == 'cygwin' and env['X11']:
    system_libs += ['GL',  'Xmu', 'Xi', 'Xrender', 'Xrandr',
        'Xcursor', 'Xft', 'freetype', 'fontconfig', 'Xext', 'X11', 'SM', 'ICE', 
        'resolv', 'pthread', 'z']
else:
    system_libs += ['z']

libs = [
    ('HAVE_LIBGDI32', 'gdi32'),
    ('HAVE_LIBAIKSAURUS', env['AIKSAURUS_LIB']),
    ('USE_ASPELL', aspell_lib),
    ('USE_ENCHANT', 'enchant'),
    ('USE_ISPELL', 'ispell'),
    ('USE_PSPELL', 'pspell'),
]

for lib in libs:
    if env[lib[0]]:
        system_libs.append(lib[1])

#
# Build parameters CPPPATH etc
#
if env['X11']:
    env.AppendUnique(LIBPATH = ['/usr/X11R6/lib'])

#
# boost: for boost header files
# BUILDDIR/src: for config.h
# TOP_SRCDIR/src: for support/* etc
#
env['CPPPATH'] += ['$BUILDDIR/src', '$TOP_SRCDIR/src']
#
# Separating boost directories from CPPPATH stops scons from building
# the dependency tree for boost header files, and effectively reduce
# the null build time of lyx from 29s to 16s. Since lyx may tweak local
# boost headers, the following is not 100% safe.
#    env.AppendUnique(CPPPATH = ['$BOOST_INC_PATH'])
env.PrependUnique(CCFLAGS = ['$INCPREFIX$BOOST_INC_PATH'])

# for intl/config.h, intl/libintl.h and intl/libgnuintl.h
if env['nls'] and included_gettext:
    env['CPPPATH'].append('$BUILDDIR/intl')
#

#
# A Link script for cygwin see
# http://www.cygwin.com/ml/cygwin/2004-09/msg01101.html
# http://www.cygwin.com/ml/cygwin-apps/2004-09/msg00309.html
# for details
#
if platform_name == 'cygwin':
    ld_script_path = '/tmp'
    ld_script = utils.installCygwinLDScript(ld_script_path)
    env.AppendUnique(LINKFLAGS = ['-Wl,--enable-runtime-pseudo-reloc',
        '-Wl,--script,%s' % ld_script, '-Wl,-s'])


#---------------------------------------------------------
# Frontend related variables (QTDIR etc)
#---------------------------------------------------------

#
# create a separate environment so that other files do not have
# to be built with all the include directories etc
#
if frontend == 'qt4':
    env['BUILDERS']['qtResource'] = Builder(action = utils.env_qtResource)

    # handle qt related user specified paths
    # set environment so that moc etc can be found even if its path is not set properly
    if env.has_key('qt_dir') and env['qt_dir']:
        env['QTDIR'] = env['qt_dir']
        if os.path.isdir(os.path.join(env['qt_dir'], 'bin')):
            os.environ['PATH'] += os.pathsep + os.path.join(env['qt_dir'], 'bin')
            env.PrependENVPath('PATH', os.path.join(env['qt_dir'], 'bin'))
        if os.path.isdir(os.path.join(env['qt_dir'], 'lib')):
            env.PrependENVPath('PKG_CONFIG_PATH', os.path.join(env['qt_dir'], 'lib'))

    # if separate qt_lib_path is given
    if env.has_key('qt_lib_path') and env['qt_lib_path']:
        qt_lib_path = env.subst('$qt_lib_path')
        env.AppendUnique(LIBPATH = [qt_lib_path])
        env.PrependENVPath('PKG_CONFIG_PATH', qt_lib_path)
    else:
        qt_lib_path = None

    # if separate qt_inc_path is given
    if env.has_key('qt_inc_path') and env['qt_inc_path']:
        qt_inc_path = env['qt_inc_path']
    else:
        qt_inc_path = None

    # local qt4 toolset from
    # http://www.iua.upf.es/~dgarcia/Codders/sconstools.html
    #
    # NOTE: I have to patch qt4.py since it does not automatically
    # process .C file!!! (add to cxx_suffixes )
    #
    env.Tool('qt4', [scons_dir])
    env['QT_AUTOSCAN'] = 0
    env['QT4_AUTOSCAN'] = 0
    env['QT4_UICDECLFLAGS'] = '-tr lyx::qt_'
    if platform_name == 'win32':
        env['QT4_MOCFROMHFLAGS'] = '-D_WIN32'

    if qt_lib_path is None:
        qt_lib_path = os.path.join(env.subst('$QTDIR'), 'lib')
    if qt_inc_path is None:
        qt_inc_path = os.path.join(env.subst('$QTDIR'), 'include')


    conf = Configure(env,
        custom_tests = { 
            'CheckPackage' : utils.checkPackage,
            'CheckCommand' : utils.checkCommand,
        }
    )

    succ = False
    # first: try pkg_config
    if env['HAS_PKG_CONFIG']:
        succ = conf.CheckPackage('QtCore') or conf.CheckPackage('QtCore4')
        # FIXME: use pkg_config information?
        #env['QT4_PKG_CONFIG'] = succ
    # second: try to link to it
    if not succ:
        # Under linux, I can test the following perfectly
        # Under windows, lib names need to passed as libXXX4.a ...
        if platform_name == 'win32':
            succ = conf.CheckLibWithHeader('QtCore4', 'QtGui/QApplication', 'c++', 'QApplication qapp();')
        else:
            succ = conf.CheckLibWithHeader('QtCore', 'QtGui/QApplication', 'c++', 'QApplication qapp();')
    # still can not find it
    if not succ:
        print 'Did not find qt libraries, exiting!'
        print 'Please check config.log for more information.'
        Exit(1)
    #
    # Now, determine the correct suffix:
    qt_libs = ['QtCore', 'QtGui']
    if platform_name == 'win32':
        if mode == 'debug' and use_vc and \
            conf.CheckLibWithHeader('QtCored4', 'QtGui/QApplication', 'c++', 'QApplication qapp();'):
            qt_lib_suffix = 'd4'
            use_qt_debug_libs = True
        else:
            qt_lib_suffix = '4'
            use_qt_debug_libs = False
    else:
        if mode == 'debug' and conf.CheckLibWithHeader('QtCore_debug', 'QtGui/QApplication', 'c++', 'QApplication qapp();'):
            qt_lib_suffix = '_debug'
            use_qt_debug_libs = True
        else:
            qt_lib_suffix = ''
            use_qt_debug_libs = False
    env.EnableQt4Modules(qt_libs, debug = (mode == 'debug' and use_qt_debug_libs))
    frontend_libs = [x + qt_lib_suffix for x in qt_libs]
    qtcore_lib = ['QtCore' + qt_lib_suffix]

    # check uic and moc commands for qt frontends
    if conf.CheckCommand('uic') == None or conf.CheckCommand('moc') == None:
        print 'uic or moc command is not found for frontend', frontend
        Exit(1)
    
    # now, if msvc2005 is used, we will need to embed lyx.exe.manifest to lyx.exe
    # NOTE: previously, lyx.exe had to be linked to some qt manifest to work.
    # For some unknown changes in msvc or qt, this is no longer needed.
    if use_vc:
        env['LINKCOM'] = [env['LINKCOM'], \
            'mt.exe /MANIFEST %s /outputresource:$TARGET;1' % \
            env.File('$BUILDDIR/lyx.exe.manifest').path]

    env = conf.Finish()

#
# Report results
#
print env['VERSION_INFO']

#
# Mingw command line may be too short for our link usage,
# Here we use a trick from scons wiki
# http://www.scons.org/cgi-sys/cgiwrap/scons/moin.cgi/LongCmdLinesOnWin32
#
# I also would like to add logging (commands only) capacity to the
# spawn system.
logfile = env.get('logfile', default_log_file)
if logfile != '' or platform_name == 'win32':
    import time
    utils.setLoggedSpawn(env, logfile, longarg = (platform_name == 'win32'),
        info = '''# This is a log of commands used by scons to build lyx
# Time: %s
# Command: %s
# Info: %s
''' % (time.asctime(), ' '.join(sys.argv),
    env['VERSION_INFO'].replace('\n','\n# ')) )


# Cleanup stuff
#
# -h will print out help info
Help(opts.GenerateHelpText(env))


#----------------------------------------------------------
# Start building
#----------------------------------------------------------
# this has been the source of problems on some platforms...
# I find that I need to supply it with full path name
env.SConsignFile(os.path.join(Dir(env['BUILDDIR']).abspath, '.sconsign'))
# this usage needs further investigation.
#env.CacheDir('%s/Cache/%s' % (env['BUILDDIR'], frontend))
env.BuildDir('$BUILDDIR/boost', '$TOP_SRCDIR/boost/libs', duplicate = 0)
env.BuildDir('$BUILDDIR/intl', '$TOP_SRCDIR/intl', duplicate = 0)
env.BuildDir('$BUILDDIR/src', '$TOP_SRCDIR/src', duplicate = 0)
env.BuildDir('$BUILDDIR/src', '$TOP_SRCDIR/src', duplicate = 0)

print "Building all targets recursively"

def libExists(libname):
    ''' Check whether or not lib $LOCALLIBNAME/libname already exists'''
    return os.path.isfile(File(env.subst('$LOCALLIBPATH/${LIBPREFIX}%s$LIBSUFFIX'%libname)).abspath)


if (included_boost and not libExists('included_boost_regex')) or 'boost' in BUILD_TARGETS:
    #
    # boost/libs
    #
    for lib in boost_libs:
        boostlib = env.StaticLibrary(
            target = '$LOCALLIBPATH/included_boost_%s' % lib,
            source = ['$BUILDDIR/boost/%s/src/%s' % (lib, x) for x in eval('boost_libs_%s_src_files' % lib)],
            # do not use global CPPPATH because src/config.h will mess up with boost/config.h
            CPPPATH = ['$BUILDDIR/boost'] + extra_inc_paths,
            CCFLAGS = ['$CCFLAGS', '$INCPREFIX$TOP_SRCDIR/boost', '-DBOOST_USER_CONFIG="<config.h>"']
        )
        Alias('boost', boostlib)


if (included_gettext and not libExists('included_intl')) or 'intl' in BUILD_TARGETS:
    #
    # intl
    #
    INTL_CCFLAGS =  [
        r'-DLOCALEDIR=\"' + env['LOCALEDIR'].replace('\\', '\\\\') + r'\"',
        r'-DLOCALE_ALIAS_PATH=\"' + env['LOCALEDIR'].replace('\\', '\\\\') + r'\"',
        r'-DLIBDIR=\"' + env['TOP_SRCDIR'].replace('\\', '\\\\') + r'/lib\"',
        '-DIN_LIBINTL',
        '-DENABLE_RELOCATABLE=1',
        '-DIN_LIBRARY',
        r'-DINSTALLDIR=\"' + prefix.replace('\\', '\\\\') + r'/lib\"',
        '-DNO_XMALLOC',
        '-Dset_relocation_prefix=libintl_set_relocation_prefix',
        '-Drelocate=libintl_relocate',
        '-DDEPENDS_ON_LIBICONV=1',
        '-DHAVE_CONFIG_H'
        ]
    if use_vc:
        INTL_CCFLAGS.extend(['/Dinline#', '/D__attribute__(x)#', '/Duintmax_t=UINT_MAX'])

    intl = env.StaticLibrary(
        target = '$LOCALLIBPATH/included_intl',
        LIBS = ['c'],
        CCFLAGS = INTL_CCFLAGS,
        # do not use global CPPPATH because src/config.h will mess up with intl/config.h
        CPPPATH =  ['$BUILDDIR/intl'] + extra_inc_paths,
        source = ['$BUILDDIR/intl/%s' % x for x in intl_files]
    )
    Alias('intl', intl)

#
# src/support
#
env['QT4_MOCHPREFIX'] = ''
env['QT4_MOCHSUFFIX'] = '_moc.cpp'

support_moced_files = [env.Moc4('$BUILDDIR/src/support/%s' % x)
    for x in src_support_header_files ]
support = env.StaticLibrary(
    target = '$LOCALLIBPATH/support',
    source = ['$BUILDDIR/src/support/%s' % x for x in src_support_files],
    CCFLAGS =  [
        '$CCFLAGS',
        '-DHAVE_CONFIG_H',
        '-DQT_NO_STL',
        '-DQT_NO_KEYWORDS',
    ],
    CPPPATH = ['$CPPPATH', '$BUILDDIR/src/support']
)
Alias('support', support)

#
# lyxclient
#
if env['HAVE_FCNTL']:
    client = env.Program(
        target = '$BUILDDIR/src/client/lyxclient',
        LIBS = ['support'] + intl_libs + system_libs +
            socket_libs + boost_libraries + qtcore_lib,
        source = ['$BUILDDIR/src/client/%s' % x for x in src_client_files] + \
            utils.createResFromIcon(env, 'lyx.ico', '$LOCALLIBPATH/client.rc')
    )
    Alias('client', env.Command(os.path.join('$BUILDDIR', os.path.split(str(client[0]))[1]),
        client, [Copy('$TARGET', '$SOURCE')]))
else:
    client = None
Alias('client', client)


#
# tex2lyx
#
for file in src_tex2lyx_copied_files + src_tex2lyx_copied_header_files:
    env.Command('$BUILDDIR/src/tex2lyx/'+file, '$TOP_SRCDIR/src/'+file,
        [Copy('$TARGET', '$SOURCE')])

tex2lyx = env.Program(
    target = '$BUILDDIR/src/tex2lyx/tex2lyx',
    LIBS = ['support'] + boost_libraries + intl_libs + system_libs + qtcore_lib,
    source = ['$BUILDDIR/src/tex2lyx/%s' % x for x in src_tex2lyx_files + src_tex2lyx_copied_files] + \
        utils.createResFromIcon(env, 'lyx.ico', '$LOCALLIBPATH/tex2lyx.rc'),
    CPPPATH = ['$BUILDDIR/src/tex2lyx', '$BUILDDIR/src', '$CPPPATH'],
    LIBPATH = ['#$LOCALLIBPATH', '$LIBPATH'],
    CCFLAGS = ['$CCFLAGS', '-DTEX2LYX'],
)
Alias('tex2lyx', env.Command(os.path.join('$BUILDDIR', os.path.split(str(tex2lyx[0]))[1]),
    tex2lyx, [Copy('$TARGET', '$SOURCE')]))
Alias('tex2lyx', tex2lyx)


#
# Build lyx with given frontend
#
if env.has_key('USE_ASPELL') and env['USE_ASPELL']:
    src_post_files.append('ASpell.cpp')
elif env.has_key('USE_ENCHANT') and env['USE_ENCHANT']:
    src_post_files.append('Enchant.cpp')
elif env.has_key('USE_PSPELL') and env['USE_PSPELL']:
    src_post_files.append('PSpell.cpp')
elif env.has_key('USE_ISPELL') and env['USE_ISPELL']:
    src_post_files.append('ISpell.cpp')

# tells scons how to get these moced files, although not all moced files are needed
# (or are actually generated).
qt4_moced_files = [env.Moc4('$BUILDDIR/src/frontends/qt4/%s' % x)
    for x in src_frontends_qt4_header_files ]
src_moced_files = [env.Moc4('$BUILDDIR/src/%s' % x)
    for x in src_header_files ]
ui_files = [env.Uic4('$BUILDDIR/src/frontends/qt4/ui/%s' % x.split('.')[0])
    for x in src_frontends_qt4_ui_files]
resource = env.Qrc(env.qtResource(
    '$BUILDDIR/src/frontends/qt4/Resource.qrc',
    ['$TOP_SRCDIR/lib/images/%s' % x for x in lib_images_files] +
    ['$TOP_SRCDIR/lib/images/math/%s' % x for x in lib_images_math_files] +
    ['$TOP_SRCDIR/lib/images/commands/%s' % x for x in lib_images_commands_files]))

lyx = env.Program(
    target = '$BUILDDIR/lyx',
    source = ['$BUILDDIR/src/main.cpp'] +
	['$BUILDDIR/src/frontends/qt4/%s' % x for x in src_frontends_qt4_files] +
	resource +
    	['$BUILDDIR/src/graphics/%s' % x for x in src_graphics_files] +
    	['$BUILDDIR/src/mathed/%s' % x for x in src_mathed_files] +
    	['$BUILDDIR/src/insets/%s' % x for x in src_insets_files] +
    	['$BUILDDIR/src/frontends/%s' % x for x in src_frontends_files] +
    	['$BUILDDIR/src/%s' % x for x in src_pre_files] +
    	["$BUILDDIR/src/%s" % x for x in src_post_files] +
        utils.createResFromIcon(env, 'lyx.ico', '$LOCALLIBPATH/lyx.rc'),
    CPPPATH = [
        '$CPPPATH',
        '$BUILDDIR/src',
        '$BUILDDIR/src/images',
        '$BUILDDIR/src/frontends',
        '$BUILDDIR/src/frontends/qt4',
        '$BUILDDIR/src/frontends/qt4/ui',
    ],
    CCFLAGS =  [
        '$CCFLAGS',
        '-DHAVE_CONFIG_H',
        '-DQT_NO_STL',
        '-DQT_NO_KEYWORDS',
    ],
    LIBS = [
        'support',
        ] +
        boost_libraries + 
        frontend_libs +
        intl_libs +
        socket_libs +
        system_libs
)
Alias('lyx', lyx)


if use_vc and 'msvs_projects' in BUILD_TARGETS:
    def build_project(target, full_target = None, src = [], inc = [], res = []):
        ''' build mavs project files
            target:      alias (correspond to directory name)
            full_target: full path/filename of the target
            src:         source files
            inc:         include files
            res:         resource files

        For non-debug-able targets like static libraries, target (alias) is
        enough to build the target. For executable targets, msvs need to know
        the full path to start debug them.
        '''
        # project
        proj = env.MSVSProject(
            target = target + env['MSVSPROJECTSUFFIX'],
            # this allows easy access to header files (along with source)
            srcs = [env.subst(x) for x in src + inc],
            incs = [env.subst('$TOP_SRCDIR/src/config.h')],
            localincs = [env.subst(x) for x in inc],
            resources = [env.subst(x) for x in res],
            buildtarget = full_target,
            variant = 'Debug'
        )
        Alias('msvs_projects', proj)
    #
    build_project('client', src = ['$TOP_SRCDIR/src/client/%s' % x for x in src_client_files],
        inc = ['$TOP_SRCDIR/src/client/%s' % x for x in src_client_header_files],
        full_target = File(env.subst('$BUILDDIR/src/client/lyxclient$PROGSUFFIX')).abspath)
    #
    build_project('tex2lyx', src = ['$TOP_SRCDIR/src/tex2lyx/%s' % x for x in src_tex2lyx_files],
        inc = ['$TOP_SRCDIR/src/tex2lyx/%s' % x for x in src_tex2lyx_header_files],
        full_target = File(env.subst('$BUILDDIR/src/tex2lyx/tex2lyx$PROGSUFFIX')).abspath)
    #
    build_project('lyx', 
        src = ['$TOP_SRCDIR/src/%s' % x for x in src_pre_files + src_post_files + ['version.cpp']] + \
            ['$TOP_SRCDIR/src/support/%s' % x for x in src_support_files + ['Package.cpp'] ] + \
            ['$TOP_SRCDIR/src/mathed/%s' % x for x in src_mathed_files] + \
            ['$TOP_SRCDIR/src/insets/%s' % x for x in src_insets_files] + \
            ['$TOP_SRCDIR/src/frontends/%s' % x for x in src_frontends_files] + \
            ['$TOP_SRCDIR/src/graphics/%s' % x for x in src_graphics_files] + \
            ['$TOP_SRCDIR/src/frontends/qt4/%s' % x for x in src_frontends_qt4_files],
        inc = ['$TOP_SRCDIR/src/%s' % x for x in src_header_files] + \
            ['$TOP_SRCDIR/src/support/%s' % x for x in src_support_header_files] + \
            ['$TOP_SRCDIR/src/mathed/%s' % x for x in src_mathed_header_files] + \
            ['$TOP_SRCDIR/src/insets/%s' % x for x in src_insets_header_files] + \
            ['$TOP_SRCDIR/src/frontends/%s' % x for x in src_frontends_header_files] + \
            ['$TOP_SRCDIR/src/graphics/%s' % x for x in src_graphics_header_files] + \
            ['$TOP_SRCDIR/src/frontends/qt4/%s' % x for x in src_frontends_qt4_header_files],
        res = ['$TOP_SRCDIR/src/frontends/qt4/ui/%s' % x for x in src_frontends_qt4_ui_files],
        full_target = File(env.subst('$BUILDDIR/lyx$PROGSUFFIX')).abspath)


if 'update_po' in BUILD_TARGETS:
    #
    # update po files
    #
    print 'Updating po/*.po files...'

    # whether or not update po files
    if not env['XGETTEXT'] or not env['MSGMERGE'] or not env['MSGUNIQ']:
        print 'xgettext or msgmerge does not exist. Cannot merge po files'
        Exit(1)
    # rebuild POTFILES.in
    POTFILES_in = env.potfiles('$TOP_SRCDIR/po/POTFILES.in', 
        ['$TOP_SRCDIR/src/%s' % x for x in  src_header_files + src_pre_files + src_post_files + \
            src_extra_src_files] + \
        ['$TOP_SRCDIR/src/support/%s' % x for x in src_support_header_files + src_support_files + \
            src_support_extra_header_files + src_support_extra_src_files] + \
        ['$TOP_SRCDIR/src/mathed/%s' % x for x in  src_mathed_header_files + src_mathed_files] + \
        ['$TOP_SRCDIR/src/insets/%s' % x for x in  src_insets_header_files + src_insets_files] + \
        ['$TOP_SRCDIR/src/frontends/%s' % x for x in  src_frontends_header_files + src_frontends_files] + \
        ['$TOP_SRCDIR/src/graphics/%s' % x for x in src_graphics_header_files + src_graphics_files] + \
        ['$TOP_SRCDIR/src/frontends/qt4/%s' % x for x in src_frontends_qt4_header_files + src_frontends_qt4_files] + \
        ['$TOP_SRCDIR/src/client/%s' % x for x in src_client_header_files + src_client_files ]  + \
        ['$TOP_SRCDIR/src/tex2lyx/%s' % x for x in src_tex2lyx_header_files + src_tex2lyx_files ]
    )
    Alias('update_po', POTFILES_in)
    # build language_l10n.pot, encodings_10n.pot, ui_l10n.pot, layouts_l10n.pot, qt4_l10n.pot, external_l10n, formats_l10n
    # and combine them to lyx.po
    env['LYX_POT'] = 'python $TOP_SRCDIR/po/lyx_pot.py'
    lyx_po = env.Command('$BUILDDIR/po/lyx.po',
        env.Command('$BUILDDIR/po/all.po',
            [env.Command('$BUILDDIR/po/qt4_l10n.pot', 
                ['$TOP_SRCDIR/src/frontends/qt4/ui/%s' % x for x in src_frontends_qt4_ui_files],
                '$LYX_POT -b $TOP_SRCDIR -t qt4 -o $TARGET $SOURCES'),
             env.Command('$BUILDDIR/po/layouts_l10n.pot', 
                ['$TOP_SRCDIR/lib/layouts/%s' % x for x in lib_layouts_files + lib_layouts_inc_files + lib_layouts_module_files],
                '$LYX_POT -b $TOP_SRCDIR -t layouts -o $TARGET $SOURCES'),
             env.Command('$BUILDDIR/po/languages_l10n.pot', '$TOP_SRCDIR/lib/languages',
                '$LYX_POT -b $TOP_SRCDIR -t languages -o $TARGET $SOURCES'),
             env.Command('$BUILDDIR/po/encodings_l10n.pot', '$TOP_SRCDIR/lib/encodings',
                '$LYX_POT -b $TOP_SRCDIR -t encodings -o $TARGET $SOURCES'),
             env.Command('$BUILDDIR/po/ui_l10n.pot', 
                ['$TOP_SRCDIR/lib/ui/%s' % x for x in lib_ui_files],
                '$LYX_POT -b $TOP_SRCDIR -t ui -o $TARGET $SOURCES'),
             env.Command('$BUILDDIR/po/external_l10n.pot', '$TOP_SRCDIR/lib/external_templates',
                '$LYX_POT -b $TOP_SRCDIR -t external -o $TARGET $SOURCES'),
             env.Command('$BUILDDIR/po/formats_l10n.pot', '$TOP_SRCDIR/lib/configure.py',
                '$LYX_POT -b $TOP_SRCDIR -t formats -o $TARGET $SOURCES'),
             ], utils.env_cat),
            ['$MSGUNIQ -o $TARGET $SOURCE',
             '''$XGETTEXT --default-domain=${TARGET.base} \
                --directory=$TOP_SRCDIR --add-comments=TRANSLATORS: \
                --language=C++ --join-existing \
                --keyword=_ --keyword=N_ --keyword=B_ --keyword=qt_ \
                --files-from=$TOP_SRCDIR/po/POTFILES.in \
                --copyright-holder="LyX Developers" \
                --msgid-bugs-address="lyx-devel@lists.lyx.org" ''']
        )
    env.Depends(lyx_po, POTFILES_in)
    # copy lyx.po to lyx.pot
    lyx_pot = env.Command('$BUILDDIR/po/lyx.pot', lyx_po,
        Copy('$TARGET', '$SOURCE'))
    #
    import glob
    # files to translate
    transfiles = glob.glob(os.path.join(env.Dir('$TOP_SRCDIR/po').abspath, '*.po'))
    # possibly *only* handle these languages
    languages = None
    if env.has_key('languages'):
        languages = env.make_list(env['languages'])
    # merge. if I use lan.po as $TARGET, it will be removed
    # before it is merged. In this builder,
    # $BUILDDIR/po/lang.po is merged from po/lang.po and $BUILDDIR/po/lyx.pot
    # and is copied to po/lang.po
    env['BUILDERS']['msgmerge'] = Builder(action=[
        '$MSGMERGE $TOP_SRCDIR/po/${TARGET.filebase}.po $SOURCE -o $TARGET',
        Copy('$TOP_SRCDIR/po/${TARGET.filebase}.po', '$TARGET')]
        )
    # for each po file, generate pot
    for po_file in transfiles:
        # get filename
        fname = os.path.split(po_file)[1]
        # country code
        country = fname.split('.')[0]
        #
        if not languages or country in languages:
            # merge po files, the generated lan.po_new file is copied to lan.po file.
            po = env.msgmerge('$BUILDDIR/po/%s.po' % country, lyx_pot)
            env.Depends(po, POTFILES_in)
            Alias('update_po', po)


# if 'install' is not in the target, do not process this
if 'install' in BUILD_TARGETS or 'installer' in BUILD_TARGETS:
    #
    # this part is a bit messy right now. Since scons will provide
    # --DESTDIR option soon, at least the dest_dir handling can be 
    # removed later.
    #
    #
    # po/
    #
    import glob
    # handle po files
    #
    # files to translate
    transfiles = glob.glob(os.path.join(env.subst('$TOP_SRCDIR'), 'po', '*.po'))
    # possibly *only* handle these languages
    languages = None
    if env.has_key('languages'):
        languages = env.make_list(env['lanauges'])
    # use defulat msgfmt
    gmo_files = []
    if not env['MSGFMT']:
        print 'msgfmt does not exist. Can not process po files'
    else:
        # create a builder
        env['BUILDERS']['Transfiles'] = Builder(action='$MSGFMT $SOURCE -c --statistics -o $TARGET',suffix='.gmo',src_suffix='.po')
        #
        for f in transfiles:
            # get filename
            fname = os.path.split(f)[1]
            # country code
            country = fname.split('.')[0]
            #
            if not languages or country in languages:
                gmo_files.extend(env.Transfiles(f))
    # how to join dest_dir and prefix
    def joinPaths(path1, path2):
        ''' join path1 and path2, do not use os.path.join because
            under window, c:\destdir\d:\program is invalid '''
        if path1 == '':
            return os.path.normpath(path2)
        # separate drive letter
        (drive, path) = os.path.splitdrive(os.path.normpath(path2))
        # ignore drive letter, so c:\destdir + c:\program = c:\destdir\program
        return os.path.join(os.path.normpath(path1), path[1:])
    #
    # install to dest_dir/prefix
    dest_dir = env.get('DESTDIR', '')
    dest_prefix_dir = joinPaths(dest_dir, env.Dir(prefix).abspath)
    # create the directory if needed
    if not os.path.isdir(dest_prefix_dir):
        try:
            os.makedirs(dest_prefix_dir)
        except:
            pass
        if not os.path.isdir(dest_prefix_dir):
            print 'Can not create directory', dest_prefix_dir
            Exit(3)
    #
    if env.has_key('exec_prefix'):
        bin_dest_dir = joinPaths(dest_dir, Dir(env['exec_prefix']).abspath)
    else:
        bin_dest_dir = os.path.join(dest_prefix_dir, 'bin')
    if add_suffix:
        share_dest_dir = os.path.join(dest_prefix_dir, share_dir + program_suffix)
    else:
        share_dest_dir = os.path.join(dest_prefix_dir, share_dir)
    man_dest_dir = os.path.join(dest_prefix_dir, man_dir)
    locale_dest_dir = os.path.join(dest_prefix_dir, locale_dir)
    env['LYX2LYX_DEST'] = os.path.join(share_dest_dir, 'lyx2lyx')
    #
    import glob
    #
    # install executables (lyxclient may be None)
    #
    if add_suffix:
        version_suffix = program_suffix
    else:
        version_suffix = ''
    #
    # install lyx, if in release mode, try to strip the binary
    if env.has_key('STRIP') and env['STRIP'] is not None and mode != 'debug':
        # create a builder to strip and install
        env['BUILDERS']['StripInstallAs'] = Builder(action='$STRIP $SOURCE -o $TARGET')

    # install executables
    for (name, obj) in (('lyx', lyx), ('tex2lyx', tex2lyx), ('client', client)):
        if obj is None:
            continue
        target_name = os.path.split(str(obj[0]))[1].replace(name, '%s%s' % (name, version_suffix))
        target = os.path.join(bin_dest_dir, target_name)
        if env['BUILDERS'].has_key('StripInstallAs'):
            env.StripInstallAs(target, obj)
        else:
            env.InstallAs(target, obj)
        Alias('install', target)

    # share/lyx
    dirs = []
    for (dir,files) in [
            ('.', lib_files),  
            ('bind', lib_bind_files),
            ('bind/de', lib_bind_de_files),
            ('bind/fi', lib_bind_fi_files),
            ('bind/pt', lib_bind_pt_files),
            ('bind/sv', lib_bind_sv_files),
            ('commands', lib_commands_files),
            ('doc', lib_doc_files),
            ('doc/biblio', lib_doc_biblio_files),
            ('doc/clipart', lib_doc_clipart_files),
            ('doc/ca', lib_doc_ca_files),
            ('doc/cs', lib_doc_cs_files),
            ('doc/da', lib_doc_da_files),
            ('doc/de', lib_doc_de_files),
            ('doc/de/clipart', lib_doc_de_clipart_files),
            ('doc/el', lib_doc_el_files),
            ('doc/es', lib_doc_es_files),
            ('doc/es/clipart', lib_doc_es_clipart_files),
            ('doc/eu', lib_doc_eu_files),
            ('doc/fr', lib_doc_fr_files),
            ('doc/fr/clipart', lib_doc_fr_clipart_files),
            ('doc/gl', lib_doc_gl_files),
            ('doc/he', lib_doc_he_files),
            ('doc/hu', lib_doc_hu_files),
            ('doc/id', lib_doc_id_files),
            ('doc/id/clipart', lib_doc_id_clipart_files),
            ('doc/it', lib_doc_it_files),
            ('doc/it/clipart', lib_doc_it_clipart_files),
            ('doc/ja', lib_doc_ja_files),
            ('doc/ja/clipart', lib_doc_ja_clipart_files),
            ('doc/nl', lib_doc_nl_files),
            ('doc/nb', lib_doc_nb_files),
            ('doc/pl', lib_doc_pl_files),
            ('doc/pt', lib_doc_pt_files),
            ('doc/ro', lib_doc_ro_files),
            ('doc/ru', lib_doc_ru_files),
            ('doc/sk', lib_doc_sk_files),
            ('doc/sl', lib_doc_sl_files),
            ('doc/sv', lib_doc_sv_files),
            ('doc/uk', lib_doc_uk_files),
            ('doc/uk/clipart', lib_doc_uk_clipart_files),
            ('doc/zh_CN', lib_doc_zhCN_files),
            ('examples', lib_examples_files),
            ('examples/ca', lib_examples_ca_files),
            ('examples/cs', lib_examples_cs_files),
            ('examples/da', lib_examples_da_files),
            ('examples/de', lib_examples_de_files),
            ('examples/el', lib_examples_el_files),
            ('examples/es', lib_examples_es_files),
            ('examples/eu', lib_examples_eu_files),
            ('examples/fa', lib_examples_fa_files),
            ('examples/fr', lib_examples_fr_files),
            ('examples/gl', lib_examples_gl_files),
            ('examples/he', lib_examples_he_files),
            ('examples/hu', lib_examples_hu_files),
            ('examples/id', lib_examples_id_files),
            ('examples/it', lib_examples_it_files),
            ('examples/ja', lib_examples_ja_files),
            ('examples/nl', lib_examples_nl_files),
            ('examples/pl', lib_examples_pl_files),
            ('examples/pt', lib_examples_pt_files),
            ('examples/ro', lib_examples_ro_files),
            ('examples/ru', lib_examples_ru_files),
            ('examples/sk', lib_examples_sk_files),
            ('examples/sl', lib_examples_sl_files),
            ('examples/uk', lib_examples_uk_files),
            ('fonts', lib_fonts_files),
            ('images', lib_images_files),
            ('images/math', lib_images_math_files),
            ('images/commands', lib_images_commands_files),
            ('kbd', lib_kbd_files),
            ('layouts', lib_layouts_files + lib_layouts_inc_files + lib_layouts_module_files),
            ('lyx2lyx', lib_lyx2lyx_files),
            ('scripts', lib_scripts_files),
            ('templates', lib_templates_files),
            ('tex', lib_tex_files),
            ('ui', lib_ui_files)]:
        dirs.append(env.Install(os.path.join(share_dest_dir, dir),
            [env.subst('$TOP_SRCDIR/lib/%s/%s' % (dir, file)) for file in files]))
    Alias('install', dirs)

    # subst and install lyx2lyx_version.py which is not in scons_manifest.py
    env.Depends(share_dest_dir + '/lyx2lyx/lyx2lyx_version.py', '$BUILDDIR/src/config.h')
    env.substFile(share_dest_dir + '/lyx2lyx/lyx2lyx_version.py',
        '$TOP_SRCDIR/lib/lyx2lyx/lyx2lyx_version.py.in')
    Alias('install', share_dest_dir + '/lyx2lyx/lyx2lyx_version.py')
    sys.path.append(share_dest_dir + '/lyx2lyx')
    
    if platform_name == 'cygwin':
        # cygwin packaging requires a file /usr/share/doc/Cygwin/foot-vendor-suffix.README
        Cygwin_README = os.path.join(dest_prefix_dir, 'share', 'doc', 'Cygwin', 
            '%s-%s.README' % (package, package_cygwin_version))
        env.InstallAs(Cygwin_README,
            os.path.join(env.subst('$TOP_SRCDIR'), 'README.cygwin'))
        Alias('install', Cygwin_README)
        # also a directory /usr/share/doc/lyx for README etc
        Cygwin_Doc = os.path.join(dest_prefix_dir, 'share', 'doc', package)
        env.Install(Cygwin_Doc, [os.path.join(env.subst('$TOP_SRCDIR'), x) for x in \
            ['INSTALL', 'README', 'README.Cygwin', 'RELEASE-NOTES', 'COPYING', 'ANNOUNCE']])
        Alias('install', Cygwin_Doc)
        # cygwin fonts also need to be installed
        Cygwin_fonts = os.path.join(share_dest_dir, 'fonts')
        env.Install(Cygwin_fonts, 
            [env.subst('$TOP_SRCDIR/development/Win32/packaging/bakoma/%s' % file) \
                  for file in win32_bakoma_fonts])
        Alias('install', Cygwin_fonts)
        # we also need a post installation script
        tmp_script = utils.installCygwinPostinstallScript('/tmp')
        postinstall_path = os.path.join(dest_dir, 'etc', 'postinstall')
        env.Install(postinstall_path, tmp_script)
        Alias('install', postinstall_path)
    # man
    env.InstallAs(os.path.join(man_dest_dir, 'lyx' + version_suffix + '.1'),
        env.subst('$TOP_SRCDIR/lyx.1in'))
    env.InstallAs(os.path.join(man_dest_dir, 'tex2lyx' + version_suffix + '.1'),
        env.subst('$TOP_SRCDIR/src/tex2lyx/tex2lyx.1in'))
    env.InstallAs(os.path.join(man_dest_dir, 'lyxclient' + version_suffix + '.1'),
        env.subst('$TOP_SRCDIR/src/client/lyxclient.1in'))
    Alias('install', [os.path.join(man_dest_dir, x + version_suffix + '.1') for
        x in ['lyx', 'tex2lyx', 'lyxclient']])
    # locale files?
    # ru.gmo ==> ru/LC_MESSAGES/lyxSUFFIX.mo
    for gmo in gmo_files:
        lan = os.path.split(str(gmo))[1].split('.')[0]
        dest_file = os.path.join(locale_dest_dir, lan, 'LC_MESSAGES', 'lyx' + program_suffix + '.mo')
        env.InstallAs(dest_file, gmo)
        Alias('install', dest_file)


if 'installer' in BUILD_TARGETS:
    #
    # build windows installer using NSIS
    #
    # NOTE:
    # There is a nsis builder on scons wiki but it does not work with
    # our lyx.nsi because it does not dig through all the include directives
    # and find the dependencies automatically. Also, it can not parse
    # OutFile in lyx.nsi since it is defined as SETUP_EXE which is in turn
    # something rely on date.
    # Because of this, I am doing a simple nsis builder here.
    if platform_name != 'win32':
        print 'installer target is only available for windows platform'
        Exit(1)
    if mode != 'release':
        print 'installer has to be built in release mode (use option mode=release)'
        Exit(1)
    installer_files = ['$TOP_SRCDIR/development/Win32/packaging/installer/%s' \
            % x for x in development_Win32_packaging_installer] + \
        ['$TOP_SRCDIR/development/Win32/packaging/installer/graphics/%s' \
            % x for x in development_Win32_packaging_installer_graphics] + \
        ['$TOP_SRCDIR/development/Win32/packaging/installer/gui/%s' \
            % x for x in development_Win32_packaging_installer_gui] + \
        ['$TOP_SRCDIR/development/Win32/packaging/installer/include/%s' \
            % x for x in development_Win32_packaging_installer_include] + \
        ['$TOP_SRCDIR/development/Win32/packaging/installer/lang/%s' \
            % x for x in development_Win32_packaging_installer_lang] + \
        ['$TOP_SRCDIR/development/Win32/packaging/installer/setup/%s' \
            % x for x in development_Win32_packaging_installer_setup]
    if env.has_key('NSIS') and env['NSIS'] is not None:
        # create a builder to strip and install
        env['BUILDERS']['installer'] = Builder(generator=utils.env_nsis)
    else:
        print 'No nsis compiler is found. Existing...'
        Exit(2)
    if not env.has_key('win_installer') or env['win_installer'] is None:
        if devel_version:
            env['win_installer'] = '%s-%s-%s-Installer.exe' % (package_name, package_version, time.strftime('%Y-%m-%d'))
        else:
            env['win_installer'] = '%s-%s-Installer.exe' % (package_name, package_version)
    # provide default setting            
    if not env.has_key('deps_dir') or env['deps_dir'] is None:
        env['deps_dir'] = os.path.join(env.Dir('$TOP_SRCDIR').abspath, 'lyx-windows-deps-msvc-qt4')
    if not os.path.isdir(env.Dir('$deps_dir').abspath):
        print 'Development dependency package is not found.'
        Exit(1)    
    else:
        env['deps_dir'] = env.Dir('$deps_dir').abspath
    # build bundle?
    if env.has_key('bundle_dir') and os.path.isdir(env.Dir('$bundle_dir').abspath):
        env['bundle_dir'] = env.Dir('$bundle_dir').abspath
    elif os.path.isdir(os.path.join(env.Dir('$TOP_SRCDIR').abspath, 'lyx-windows-bundle-deps')):
        env['bundle_dir'] = os.path.join(env.Dir('$TOP_SRCDIR').abspath, 'lyx-windows-bundle-deps')
    else:
        env['bundle_dir'] = None
    # if absolute path is given, use it, otherwise, write to current directory
    if not (':' in env['win_installer'] or '/' in env['win_installer'] or '\\' in env['win_installer']):
        env['win_installer'] = os.path.join(env.Dir('$BUILDDIR').abspath, env['win_installer'])
    env.Append(NSISDEFINES={
        'ExeFile':env['win_installer'],
        'BundleExeFile':env['win_installer'].replace('.exe', '-bundle.exe'),
        'FilesLyx':env.Dir(dest_prefix_dir).abspath,
        'FilesDeps':env['deps_dir'],
        'FilesBundle':env['bundle_dir'],
        })
    installer = env.installer(env['win_installer'],
        '$TOP_SRCDIR/development/Win32/packaging/installer/lyx.nsi')
    # since I can not use a scanner, explicit dependent is required
    env.Depends(installer, 'install')
    env.Depends(installer, installer_files)
    env.Alias('installer', installer)
    # also generate bundle?
    if env.has_key('bundle') and env['bundle']:
        if env['bundle_dir'] is None or not os.path.isdir(env['bundle_dir']):
            print 'Bundle directory does not exist (default to %s\lyx-windows-bundle-deps.' % env.Dir('$TOP_SRCDIR').abspath
            print 'Use bundle_dir option to specify'
            Exit(1)
        # generator of the builder will add bundle stuff depending on output name
        bundle_installer = env.installer(env['win_installer'].replace('.exe', '-bundle.exe'),
            '$TOP_SRCDIR/development/Win32/packaging/installer/lyx.nsi')
        env.Depends(bundle_installer, 'install')
        env.Depends(bundle_installer, installer_files)
        env.Alias('installer', bundle_installer)

Default('lyx')
Alias('all', ['lyx', 'client', 'tex2lyx'])
