from waftools.plugin import plugin
from os.path import realpath

def plugin_configure(conf):
    if not conf.env["HAVE_CXX"]:
        return False
    cfg = conf.create(configurator='pkgconfig')
    cfg.name = 'libsidplay2'
    cfg.uselib = 'sidplay'
    cfg.variables = ['builders']
    if not cfg.run():
        return False

    builders = conf.env['sidplay_BUILDERS']

    resid_cfg = conf.create(configurator='library')
    resid_cfg.name = 'resid-builder'
    resid_cfg.uselib = 'resid'
    resid_cfg.path = [builders]
    if not resid_cfg.run():
        return False

    if not conf.check_header("sidplay/builders/resid.h"):
        return False

    # It looks funny that this is LIBPATH_sidplay but it is correct
    # since we explcitly set the path to builders for resid it will
    # find resid in the list even though we still need to -rpath it.
    if not realpath(builders) in [realpath(i) for i in conf.env['LIBPATH_sidplay']]:
        conf.env['LINKFLAGS_resid'] = "-Wl,-rpath=%s" % builders

    return True

def plugin_build(bld, obj):
    obj.add_objects = 'xmms_sid_cpp'

    obj = bld.create_obj('cpp', 'objects')
    obj.target = 'xmms_sid_cpp'
    obj.includes = '../../include'
    obj.source = """sidplay_wrapper.cpp md5.cpp""".split()
    obj.uselib = 'sidplay resid glib2'

configure, build = plugin('sid', configure=plugin_configure,
                          build=plugin_build, extra_libs=['sidplay resid'])
