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

import os.path
import re # subst_func

from waflib import Logs, Options

def 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 >= 1.0.0', args='--cflags --libs', mandatory=False):
        print(Logs.colors.RED + 'ERROR !! 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 + 'ERROR !! 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')

    if not conf.check_cfg(package='expat', args='--cflags --libs', mandatory=False):
        print(Logs.colors.RED + 'ERROR !! jackdbus will not be built because of expat is missing' + Logs.colors.NORMAL)
        return

    conf.env['BUILD_JACKDBUS'] = True

def build(bld):
    obj = bld(features = ['c', 'cprogram'], idx=17)
    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',
        ]
    obj.use = ['serverlib']
    if bld.env['IS_LINUX']:
        obj.use += ['PTHREAD', 'DL', 'RT', 'DBUS-1', 'EXPAT', 'STDC++']
    if bld.env['IS_MACOSX']:
        obj.use += ['PTHREAD', 'DL', 'DBUS-1', 'EXPAT']
    obj.target = 'jackdbus'

    # process org.jackaudio.service.in -> org.jackaudio.service
    obj = bld(
            features = 'subst',
            source = 'org.jackaudio.service.in',
            target = 'org.jackaudio.service',
            install_path = '${DBUS_SERVICES_DIR}/',
            BINDIR = bld.env['PREFIX'] + '/bin')
