#! /usr/bin/env python
# encoding: utf-8

import os.path
import Options
import re # subst_func
import Logs

def set_options(opt):
    opt.add_option('--enable-pkg-config-dbus-service-dir', action='store_true', default=False, help='force D-Bus service install dir to be one returned by pkg-config')

def configure(conf):
    conf.env['BUILD_JACKDBUS'] = False

    if not conf.check_cfg(package='dbus-1', atleast_version='1.0.0', args='--cflags --libs') or not conf.is_defined('HAVE_DBUS_1'):
        print Logs.colors.RED + 'WARNING !! jackdbus will not be built because libdbus-dev is missing' + Logs.colors.NORMAL
        return

    dbus_dir = conf.check_cfg(package='dbus-1', args='--variable=session_bus_services_dir')
    if not dbus_dir:
        print Logs.colors.RED + 'WARNING !! jackdbus will not be built because service dir is unknown' + Logs.colors.NORMAL
        return

    dbus_dir = dbus_dir.strip()
    conf.env['DBUS_SERVICES_DIR_REAL'] = dbus_dir

    if Options.options.enable_pkg_config_dbus_service_dir:
        conf.env['DBUS_SERVICES_DIR'] = dbus_dir
    else:
        conf.env['DBUS_SERVICES_DIR'] = os.path.normpath(conf.env['PREFIX'] + '/share/dbus-1/services')

    conf.check_tool('misc')

    conf.check(header_name='expat.h', define_name="HAVE_EXPAT")

    if conf.is_defined('HAVE_EXPAT'):
        conf.env['LIB_EXPAT'] = ['expat']
    else:
        print Logs.colors.RED + 'WARNING !! jackdbus will not be built because of expat is missing' + Logs.colors.NORMAL
        return

    conf.env['BUILD_JACKDBUS'] = True

def build(bld):
    obj = bld.new_task_gen('cc', 'program')
    if bld.env['IS_LINUX']:
        sysdeps_dbus_include = ['../linux', '../posix']
    if bld.env['IS_MACOSX']:
        sysdeps_dbus_include = ['../macosx', '../posix']

    obj.includes = sysdeps_dbus_include + ['.', '../', '../common', '../common/jack']
    obj.defines = ['HAVE_CONFIG_H','SERVER_SIDE']
    obj.source = [
        'jackdbus.c',
        'controller.c',
        'params.c',
        'controller_iface_configure.c',
        'controller_iface_control.c',
        'controller_iface_introspectable.c',
        'controller_iface_patchbay.c',
        'controller_iface_session_manager.c',
        'controller_iface_transport.c',
        'xml.c',
        'xml_expat.c',
        #'xml_nop.c',
        'xml_write_raw.c',
        'sigsegv.c',
	'reserve.c',
        ]
    if bld.env['IS_LINUX']:
        obj.uselib = 'PTHREAD DL RT DBUS-1 EXPAT'
    if bld.env['IS_MACOSX']:
        obj.uselib = 'PTHREAD DL DBUS-1 EXPAT'
    obj.uselib_local = 'serverlib'
    obj.target       = 'jackdbus'

    # process org.jackaudio.service.in -> org.jackaudio.service
    import misc
    obj = bld.new_task_gen('subst')
    obj.source = 'org.jackaudio.service.in'
    obj.target = 'org.jackaudio.service'
    obj.dict = {'BINDIR': bld.env['PREFIX'] + '/bin'}
    obj.install_path = '${DBUS_SERVICES_DIR}/'
    obj.fun = misc.subst_func
