#!/usr/bin/env python
from waflib.extras import autowaf as autowaf
from waflib import Options
from waflib import TaskGen
import sys

# Version of this package (even if built as a child)
MAJOR = '4'
MINOR = '1'
MICRO = '0'
LIBPBD_VERSION = "%s.%s.%s" % (MAJOR, MINOR, MICRO)

# Library version (UNIX style major, minor, micro)
# major increment <=> incompatible changes
# minor increment <=> compatible changes (additions)
# micro increment <=> no interface changes
LIBPBD_LIB_VERSION = '4.1.0'
LIBPBD_MAJOR_VERSION = '4'

I18N_PACKAGE = 'libpbd4'

libpbd_sources = [
    'basename.cc',
    'base_ui.cc',
    'boost_debug.cc',
    'cartesian.cc',
    'command.cc',
    'configuration_variable.cc',
    'convert.cc',
    'controllable.cc',
    'crossthread.cc',
    'cpus.cc',
    'debug.cc',
    'demangle.cc',
    'downloader.cc',
    'enumwriter.cc',
    'event_loop.cc',
    'enums.cc',
    'epa.cc',
    'error.cc',
    'ffs.cc',
    'file_archive.cc',
    'file_utils.cc',
    'fpu.cc',
    'glib_event_source.cc',
    'id.cc',
    'inflater.cc',
    'locale_guard.cc',
    'localtime_r.cc',
    'malign.cc',
    'md5.cc',
    'microseconds.cc',
    'mountpoint.cc',
    'openuri.cc',
    'pathexpand.cc',
    'pbd.cc',
    'pcg_rand.cc',
    'pool.cc',
    'progress.cc',
    'property_list.cc',
    'pthread_utils.cc',
    'reallocpool.cc',
    'receiver.cc',
    'resource.cc',
    'search_path.cc',
    'semutils.cc',
    'shortpath.cc',
    'signals.cc',
    'spinlock.cc',
    'stacktrace.cc',
    'stateful_diff_command.cc',
    'stateful.cc',
    'string_convert.cc',
    'strreplace.cc',
    'strsplit.cc',
    'system_exec.cc',
    'textreceiver.cc',
    'timer.cc',
    'timing.cc',
    'tlsf.cc',
    'transmitter.cc',
    'undo.cc',
    'utf8_utils.cc',
    'uuid.cc',
    'whitespace.cc',
    'xml++.cc',
]

def options(opt):
    opt.add_option('--ppc', action='store_true', default=False, dest='ppc',
                   help='Compile with -arch ppc (OS X ONLY)')
    opt.add_option('--dist-target', type='string', default='auto', dest='dist_target',
                    help='Specify the target for cross-compiling [auto,none,x86,i386,i686,x86_64,tiger,leopard,mingw,msvc]')
    opt.add_option('--internal-shared-libs', action='store_true', default=True, dest='internal_shared_libs',
                   help='Build internal libs as shared libraries')

def configure(conf):
    autowaf.check_pkg(conf, 'libxml-2.0', uselib_store='XML')
    autowaf.check_pkg(conf, 'sigc++-2.0', uselib_store='SIGCPP', atleast_version='2.0')
    autowaf.check_pkg(conf, 'libcurl', uselib_store='CURL', atleast_version='7.0.0', mandatory=True)
    autowaf.check_pkg(conf, 'libarchive', uselib_store='ARCHIVE', atleast_version='3.0.0', mandatory=True)
    autowaf.check_pkg(conf, 'glibmm-2.4', uselib_store='GLIBMM', atleast_version='2.32.0', mandatory=True)
    autowaf.check_pkg(conf, 'giomm-2.4', uselib_store='GIOMM', atleast_version='2.2', mandatory=True)

    conf.check(header_name='execinfo.h', define_name='HAVE_EXECINFO',mandatory=False)
    conf.check(header_name='unistd.h', define_name='HAVE_UNISTD',mandatory=False)
    if not Options.options.ppc:
        conf.check_cc(
                msg="Checking for function 'posix_memalign' in stdlib.h",
                fragment = "#define _XOPEN_SOURCE 600\n #include <stdlib.h>\n int main(void) { return posix_memalign (0, 64, 1); }\n",
                define_name='HAVE_POSIX_MEMALIGN', execute = False, mandatory=False)
    conf.check_cc(
            msg="Checking for function 'getmntent' in mntent.h",
            fragment = "#include <mntent.h>\n int main(void) { return (int)getmntent(0); }\n",
            define_name='HAVE_GETMNTENT', execute = False, mandatory=False)
    conf.check_cc(
            msg="Checking for function 'localtime_r' in time.h",
            fragment = "#include <time.h>\n int main(void) { return NULL == localtime_r(NULL, NULL); }\n",
            define_name='HAVE_LOCALTIME_R', execute = False, mandatory=False)

    # Boost headers
    if Options.options.dist_target == 'mingw':
        conf.check(compiler='cxx',
                   lib='ole32',
                   mandatory=True,
                   uselib_store='OLE')

    if Options.options.internal_shared_libs:
        conf.define('INTERNAL_SHARED_LIBS', 1)

    conf.write_config_header('libpbd-config.h', remove=False)

def build(bld):
    if not autowaf.is_child():  # Building standalone, install dev stuff
        # C++ Headers
        includedir = '${INCLUDEDIR}/pbd-%s/pbd' % LIBPBD_MAJOR_VERSION
        bld.install_files(includedir, bld.path.ant_glob('pbd/*.h'))
        bld.install_files(includedir, 'build/pbd/signals_generated.h')

        # Pkgconfig file
        autowaf.build_pc(bld, 'libpbd', LIBPBD_VERSION, LIBPBD_MAJOR_VERSION, [],
                         {'LIBPBD_VERSION' : LIBPBD_VERSION,
                          'LIBPBD_MAJOR_VERSION' : LIBPBD_MAJOR_VERSION})

    # Make signals_generated.h using signals.py
    bld(rule = sys.executable + ' ${SRC} ${TGT}', source = 'pbd/signals.py', target = 'pbd/signals_generated.h', name="pbdsignals", features='use', ext_out=['.h'])

    # Library
    if bld.is_defined ('INTERNAL_SHARED_LIBS'):
        obj              = bld.shlib(features = 'cxx cxxshlib', source=libpbd_sources)
        obj.defines = [ 'LIBPBD_DLL_EXPORTS=1' ]
    else:
        obj              = bld.stlib(features = 'cxx cxxstlib', source=libpbd_sources)
        obj.cxxflags     = [ bld.env['compiler_flags_dict']['pic'] ]
        obj.cflags       = [ bld.env['compiler_flags_dict']['pic'] ]
        obj.defines      = []

    if bld.is_defined('DEBUG_RT_ALLOC'):
        obj.source += 'debug_rt_alloc.c'

    obj.export_includes = ['.']
    obj.includes     = ['.']
    obj.name         = 'libpbd'
    obj.target       = 'pbd'
    obj.use          = 'pbdsignals'
    obj.uselib       = 'GLIBMM SIGCPP XML UUID SNDFILE GIOMM ARCHIVE CURL'
    if sys.platform == 'darwin':
        TaskGen.task_gen.mappings['.mm'] = TaskGen.task_gen.mappings['.cc']
        if 'cocoa_open_uri.mm' not in obj.source:
            obj.source += [ 'cocoa_open_uri.mm' ]
        obj.uselib += ' OSX'
    obj.vnum         = LIBPBD_LIB_VERSION
    obj.install_path = bld.env['LIBDIR']
    obj.defines     += [ 'PACKAGE="' + I18N_PACKAGE + '"' ]

    if sys.platform.startswith('netbsd'):
        obj.linkflags = '-lexecinfo'

    if bld.env['build_target'] == 'x86_64':
        obj.defines += [ 'USE_X86_64_ASM' ]
    if bld.env['build_target'] == 'mingw':
        obj.defines += [ 'NO_POSIX_MEMALIGN' ]
        obj.source += [ 'windows_special_dirs.cc' ]
        obj.source += [ 'windows_timer_utils.cc' ]
        obj.source += [ 'windows_mmcss.cc' ]
        obj.uselib += ' OLE'

    if bld.env['BUILD_TESTS'] and bld.is_defined('HAVE_CPPUNIT'):
        # Unit tests
        testobj              = bld(features = 'cxx cxxprogram')
        testobj.source       = '''
                test/testrunner.cc
                test/xpath.cc
                test/mutex_test.cc
                test/scalar_properties.cc
                test/signals_test.cc
                test/string_convert_test.cc
                test/convert_test.cc
                test/filesystem_test.cc
                test/natsort_test.cc
                test/rcu_test.cc
                test/reallocpool_test.cc
                test/xml_test.cc
                test/test_common.cc
        '''.split()
        if bld.env['build_target'] == 'mingw':
            testobj.source += [ 'test/windows_timer_utils_test.cc' ]
        testobj.target       = 'run-tests'
        testobj.includes     = obj.includes + ['test', '../pbd']
        testobj.uselib       = 'GLIBMM SIGCPP XML UUID SNDFILE GIOMM ARCHIVE CURL XML OSX CPPUNIT'
        testobj.use          = 'libpbd'
        testobj.name         = 'libpbd-tests'
        testobj.defines      = [ 'PACKAGE="' + I18N_PACKAGE + '"' ]
        if sys.platform != 'darwin' and bld.env['build_target'] != 'mingw':
            testobj.lib      = ['rt', 'dl']
