#!/usr/bin/env python

APPNAME = 'tdb'
VERSION = '2.0.0'

blddir = 'bin'

import sys, os

# find the buildtools directory
srcdir = '.'
while not os.path.exists(srcdir+'/buildtools') and len(srcdir.split('/')) < 5:
    srcdir = '../' + srcdir
sys.path.insert(0, srcdir + '/buildtools/wafsamba')

import wafsamba, samba_dist, Options, Logs, glob

samba_dist.DIST_DIRS('lib/tdb2:. lib/replace:lib/replace lib/ccan:lib/ccan buildtools:buildtools')

def set_options(opt):
    opt.BUILTIN_DEFAULT('replace,ccan')
    opt.PRIVATE_EXTENSION_DEFAULT('tdb2', noextension='tdb2')
    opt.RECURSE('lib/replace')
    opt.add_option('--enable-tdb2',
                   help=("Use tdb2 API instead of tdb1 [True]"),
                   action="store_true", dest='BUILD_TDB2', default=True)
    opt.add_option('--disable-tdb2',
                   help=("Use old tdb1 API instead of tdb2"),
                   action="store_false", dest='BUILD_TDB2')
    opt.add_option('--valgrind',
                   help=("use valgrind on tests programs"),
                   action="store_true", dest='VALGRIND', default=False)
    opt.add_option('--valgrind-log',
                   help=("where to put the valgrind log"),
                   action="store", dest='VALGRINDLOG', default=None)
    if opt.IN_LAUNCH_DIR():
        opt.add_option('--disable-python',
                       help=("disable the pytdb module"),
                       action="store_true", dest='disable_python', default=False)

def configure(conf):
    if Options.options.BUILD_TDB2:
        conf.DEFINE('BUILD_TDB2', 1)
        conf.RECURSE('lib/replace')
        conf.RECURSE('lib/ccan')

        conf.env.standalone_tdb2 = conf.IN_LAUNCH_DIR()
        conf.env.disable_python = getattr(Options.options, 'disable_python', False)

        if not conf.env.standalone_tdb2:
            if conf.CHECK_BUNDLED_SYSTEM('tdb', minversion=VERSION,
                                         implied_deps='replace'):
                conf.define('USING_SYSTEM_TDB2', 1)
                if conf.CHECK_BUNDLED_SYSTEM_PYTHON('pytdb', 'tdb', minversion=VERSION):
                    conf.define('USING_SYSTEM_PYTDB', 1)

        if not conf.env.disable_python:
            # also disable if we don't have the python libs installed
            conf.find_program('python', var='PYTHON')
            conf.check_tool('python')
            conf.check_python_version((2,4,2))
            conf.SAMBA_CHECK_PYTHON_HEADERS(mandatory=False)
            if not conf.env.HAVE_PYTHON_H:
                Logs.warn('Disabling pytdb as python devel libs not found')
                conf.env.disable_python = True

        # This make #include <ccan/...> work.
        conf.ADD_EXTRA_INCLUDES('''#lib''')

        conf.SAMBA_CONFIG_H()

        # Seems like env can't contain sets?
        conf.env.tdb2_test = {}
        conf.env.tdb2_test['run'] = glob.glob('test/run*.c')
        conf.env.tdb2_test['api'] = glob.glob('test/api*.c')
        conf.env.tdb2_test['runhelper'] = glob.glob('test/helprun*.c')
        conf.env.tdb2_test['apihelper'] = glob.glob('test/helpapi*.c')
        conf.env.tdb2_test['helper'] = list(set(glob.glob('test/*.c'))
                                            - set(conf.env.tdb2_test['run'])
                                            - set(conf.env.tdb2_test['api'])
                                            - set(conf.env.tdb2_test['runhelper'])
                                            - set(conf.env.tdb2_test['apihelper']))

def build(bld):
    if bld.env.BUILD_TDB2:
        bld.RECURSE('lib/replace')
        bld.RECURSE('lib/ccan')

        if bld.env.standalone_tdb2:
            bld.env.PKGCONFIGDIR = '${LIBDIR}/pkgconfig'
            private_library = False
        else:
            private_library = True

        SRC = '''check.c free.c hash.c io.c lock.c open.c
                 summary.c tdb.c transaction.c traverse.c
                 tdb1_check.c tdb1_freelist.c tdb1_hash.c
                 tdb1_io.c tdb1_lock.c tdb1_open.c
                 tdb1_summary.c tdb1_tdb.c tdb1_transaction.c
                 tdb1_traverse.c'''

        if not bld.CONFIG_SET('USING_SYSTEM_TDB2'):
            bld.SAMBA_LIBRARY('tdb',
                              SRC,
                              deps='replace ccan',
                              includes='.',
                              abi_directory='ABI',
                              abi_match='tdb_* tdb1_incompatible_hash',
                              hide_symbols=True,
                              vnum=VERSION,
                              public_headers='tdb2.h',
                              public_headers_install=not private_library,
                              pc_files='tdb.pc',
                              private_library=private_library)

            bld.SAMBA_BINARY('tdbtorture',
                             'tools/tdb2torture.c',
                             deps='tdb',
                             install=False)

            bld.SAMBA_BINARY('tdbtool',
                             'tools/tdb2tool.c',
                             deps='tdb')

            bld.SAMBA_BINARY('tdbdump',
                             'tools/tdb2dump.c',
                             deps='tdb')

            bld.SAMBA_BINARY('tdbrestore',
                             'tools/tdb2restore.c',
                             deps='tdb')

            bld.SAMBA_BINARY('tdbbackup',
                             'tools/tdb2backup.c',
                             deps='tdb')

            # FIXME: We need CCAN for some API tests, but waf thinks it's
            # already available via tdb.  It is, but not publicly.
            # Workaround is to build a private, non-hiding version.
            bld.SAMBA_SUBSYSTEM('tdb-testing',
                                SRC,
                                deps='replace ccan',
                                includes='.')

            bld.SAMBA_SUBSYSTEM('tdb2-test-helpers',
                                bld.env.tdb2_test['helper'], deps='replace')
            bld.SAMBA_SUBSYSTEM('tdb2-run-helpers',
                                bld.env.tdb2_test['runhelper'], deps='replace')
            bld.SAMBA_SUBSYSTEM('tdb2-api-helpers',
                                bld.env.tdb2_test['apihelper'], deps='replace tdb-testing')

            for f in bld.env.tdb2_test['run']:
                base = os.path.splitext(os.path.basename(f))[0]
                bld.SAMBA_BINARY('tdb2-' + base, f,
                                 deps='ccan replace tdb2-test-helpers tdb2-run-helpers',
                                 install=False)

            for f in bld.env.tdb2_test['api']:
                base = os.path.splitext(os.path.basename(f))[0]
                bld.SAMBA_BINARY('tdb2-' + base, f,
                                 deps='ccan replace tdb2-test-helpers tdb2-api-helpers',
                                 install=False)

            if not bld.CONFIG_SET('USING_SYSTEM_PYTDB'):
                bld.SAMBA_PYTHON('pytdb',
                                 source='pytdb.c',
                                 deps='tdb',
                                 enabled=not bld.env.disable_python,
                                 realname='tdb.so',
                                 cflags='-DPACKAGE_VERSION=\"%s\"' % VERSION)

def testonly(ctx):
    '''run tdb2 testsuite'''
    import Utils, samba_utils, shutil
    ecode = 0;

    env = samba_utils.LOAD_ENVIRONMENT()

    if env.BUILD_TDB2 and env.standalone_tdb2:
        # FIXME: This is horrible :(
        test_prefix = "%s/st" % (Utils.g_module.blddir)
        shutil.rmtree(test_prefix, ignore_errors=True)
        os.makedirs(test_prefix)

        # Create scratch directory for tests.
        testdir = os.path.join(test_prefix, 'tdb2-tests')
        samba_utils.mkdir_p(testdir)
        # Symlink back to source dir so it can find tests in test/
        link = os.path.join(testdir, 'test')
        if not os.path.exists(link):
            os.symlink(os.path.abspath(os.path.join(env.cwd, 'test')), link)

        if Options.options.VALGRIND:
            os.environ['VALGRIND'] = 'valgrind -q --num-callers=30'
        if Options.options.VALGRINDLOG is not None:
            os.environ['VALGRIND'] += ' --log-file=%s' % Options.options.VALGRINDLOG

        for f in env.tdb2_test['run'] + env.tdb2_test['api']:
            name = "tdb2-" + os.path.splitext(os.path.basename(f))[0]
            cmd = "cd " + testdir + " && $VALGRIND " + os.path.abspath(os.path.join(Utils.g_module.blddir, name)) + " > test-output 2>&1"
            print("..." + f)
            ret = samba_utils.RUN_COMMAND(cmd)
            if ret != 0:
                print("%s (%s) failed:" % (name, f))
                samba_utils.RUN_COMMAND("cat " + os.path.join(testdir, 'test-output'))
                ecode = ret;
                break;

    sys.exit(ecode)

# WAF doesn't build the unit tests for this, maybe because they don't link with tdb?
# This forces it
def test(ctx):
    import Scripting
    Scripting.commands.append('build')
    Scripting.commands.append('testonly')

def dist():
    '''makes a tarball for distribution'''
    samba_dist.dist()

def reconfigure(ctx):
    '''reconfigure if config scripts have changed'''
    import samba_utils
    samba_utils.reconfigure(ctx)