import os
from waflib import Task

APPNAME = "fileseq"

top = '.'
out = 'build'

def options(opt):
    opt.load('compiler_cxx')

def configure(ctx):
    ctx.load('compiler_cxx')
    ctx.find_program('go', var="GO")


_is_test = False

def test(bld):
    from waflib import Options
    Options.commands = ['build'] + Options.commands

    global _is_test
    _is_test = True


class go(Task.Task):
    run_str = ""

    def exec_command(self, cmd, **kwargs):
        kwargs['cwd'] = self.inputs[0].parent.abspath()

        env = kwargs.pop('env', None)
        if not env:
            env = os.environ.copy()
            if self.env.GOPATH:
                env['GOPATH'] = self.env.get_flat("GOPATH")
            if self.env.GOROOT:
                env['GOROOT'] = self.env.get_flat("GOROOT")
            kwargs['env'] = env

        super(go, self).exec_command(cmd, **kwargs)


def build(bld):
    # Go lib
    #
    root = os.path.abspath(os.path.join(bld.top_dir, '../..'))
    env = bld.env.derive()
    env.GOPATH = [":".join([root] + env.GOPATH)]

    golibname = "libgofileseq"

    cmd_str = "${GO} build " \
                  "-buildmode=c-%s " \
                  "-gcflags=-shared " \
                  "-asmflags=-shared " \
                  "-installsuffix=_shared " \
                  "-a " \
                  "-o ${TGT[0].abspath()}"

    source = bld.path.ant_glob("export/*.go")

    class gofileseq_shared(go):
        run_str = cmd_str % "shared"

    shared_tsk = gofileseq_shared(env=env)
    shared_tsk.set_inputs(source)
    shared_tsk.set_outputs([bld.path.find_or_declare("%s.so" % golibname), 
                            bld.path.find_or_declare("%s.h" % golibname)])
    bld.add_to_group(shared_tsk)

    class gofileseq_static(go):
        run_str = cmd_str % "archive"

    static_tsk = gofileseq_static(env=env)
    static_tsk.set_inputs(source)
    static_tsk.set_outputs([bld.path.find_or_declare("%s.a" % golibname)])
    bld.add_to_group(static_tsk)

    bld.add_group()

    # Install Go libs
    bld.install_files(
        '${PREFIX}/lib',
        ['build/%s.so' % golibname, 'build/%s.a' % golibname],
        )

    # C++ lib
    #
    includes = ['.', 'private', bld.variant_dir]
    source = bld.path.ant_glob(['*.cpp', 'private/*.cpp'])

    bld.shlib(
        name = "fileseq_shared",
        source = source,
        target = "fileseq",
        includes = includes,
        cxxflags = ["-fPIC"],
        lib = ["gofileseq"],
        libpath = [bld.variant_dir],
        rpath = ["$ORIGIN"],
        install_path='${PREFIX}/lib',
    )

    bld.stlib(
        name = "fileseq_static",
        source = source,
        target = "fileseq",
        includes = includes,
        cxxflags = ["-fPIC"],
        stlib = ["gofileseq"],
        stlibpath = [bld.variant_dir],
        install_path='${PREFIX}/lib',
    )

    # Install headers
    bld.install_files('${PREFIX}/include/fileseq', bld.path.ant_glob("*.h"))

    # Test
    #
    if _is_test:

        tsk = bld.program(
            source = 'test/main.cpp',
            target = 'test_fileseq',
            lib = ['pthread'],
            stlib = ['gofileseq'],
            use = 'fileseq_static',
            )

        bld(
            rule="cd %s && ./${SRC}" % bld.variant_dir,
            source=tsk.target,
            use="test_fileseq",
            )


