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

import Build
import re
import os

def configure(conf):
    conf.check_cc(header_name='samplerate.h', define_name="HAVE_SAMPLERATE")
   
    if conf.is_defined('HAVE_SAMPLERATE'):
        conf.env['LIB_SAMPLERATE'] = ['samplerate']

    conf.env['BUILD_NETLIB'] = conf.is_defined('HAVE_SAMPLERATE')
    conf.env['BUILD_ADAPTER'] = conf.is_defined('HAVE_SAMPLERATE')

def create_jack_process_obj(bld, target, sources, uselib = None):
    process = bld.new_task_gen('cxx', 'shlib')
    process.env['shlib_PATTERN'] = '%s.so'
    process.defines  = ['HAVE_CONFIG_H','SERVER_SIDE']
    if bld.env['IS_MACOSX']:
        env_includes = ['../macosx', '../posix', '../macosx/coreaudio']
    if bld.env['IS_LINUX']:
	env_includes = ['../linux', '../posix', '../linux/alsa']
    if bld.env['IS_SUN']:
        env_includes = ['../solaris', '../posix', '../solaris/oss']
    process.includes = ['.'] + env_includes + ['jack', '..']
    process.name     = target
    process.target   = target
    process.source   = sources
    if bld.env['IS_LINUX']:
        process.env.append_value("CPPFLAGS", "-fvisibility=hidden")
    if bld.env['IS_MACOSX']:
        process.env.append_value("CPPFLAGS", "-mmacosx-version-min=10.4 -arch i386 -arch ppc -arch x86_64")
        #process.env.append_value("LINKFLAGS", "-arch i386 -arch ppc -arch x86_64")
        process.env.append_value("CPPFLAGS", "-fvisibility=hidden")
    process.install_path = '${ADDON_DIR}/'
    process.uselib_local = uselib.name
    return process

def build(bld):
    common_libsources = [
        'JackActivationCount.cpp',
        'JackAPI.cpp',
        'JackClient.cpp',
        'JackConnectionManager.cpp',
        'ringbuffer.c',
        'JackError.cpp',
        'JackFrameTimer.cpp',
        'JackGraphManager.cpp',
        'JackPort.cpp',
        'JackPortType.cpp',
        'JackAudioPort.cpp',
        'JackMidiPort.cpp',
        'JackMidiAPI.cpp',
        'JackEngineControl.cpp',
        'JackShmMem.cpp',
        'shm.c',
        'JackGlobals.cpp',
        'JackDebugClient.cpp',
        'JackTransportEngine.cpp',
        'timestamps.c',
        'JackTools.cpp',
        'JackMessageBuffer.cpp',
        'JackEngineProfiling.cpp',
        ]

    includes = ['.', './jack', '..']
    uselib = ["PTHREAD", "CELT"]

    if bld.env['IS_LINUX']:
        common_libsources += [
            '../posix/JackPosixThread.cpp',
            '../posix/JackPosixSemaphore.cpp',
            '../posix/JackFifo.cpp',
            '../posix/JackProcessSync.cpp',
            '../posix/JackSocket.cpp',
            '../linux/JackLinuxTime.c',
            ]
        includes = ['../linux', '../posix'] + includes
        uselib.append('RT')
        uselib.append('DL')

    if bld.env['IS_SUN']:
        common_libsources += [
           '../posix/JackPosixThread.cpp',
           '../posix/JackFifo.cpp',
           '../posix/JackProcessSync.cpp',
           '../posix/JackSocket.cpp',
           '../solaris/JackSolarisTime.c',
           ]
        includes = ['../solaris', '../posix'] + includes
        uselib.append('RT')

    if bld.env['IS_MACOSX']:
        common_libsources += [
            '../posix/JackProcessSync.cpp',
            '../posix/JackPosixThread.cpp',
            '../macosx/JackMachThread.cpp',
            '../macosx/JackMachSemaphore.cpp',
            '../posix/JackSocket.cpp',
            '../macosx/JackMachTime.c',
            ]
        includes = ['../macosx', '../macosx/RPC', '../posix'] + includes

    serverlib = bld.new_task_gen('cxx', 'shlib')
    serverlib.features.append('cc')
    serverlib.defines = ['HAVE_CONFIG_H','SERVER_SIDE']
    serverlib.includes = includes
    serverlib.name         = 'serverlib'
    serverlib.target       = 'jackserver'
    serverlib.uselib = uselib
    serverlib.install_path = '${LIBDIR}'
    serverlib.source = [] + common_libsources
    serverlib.source += [
        'JackAudioDriver.cpp',
	'JackTimedDriver.cpp',
        'JackMidiDriver.cpp',
        'JackDriver.cpp',
        'JackEngine.cpp',
        'JackExternalClient.cpp',
        'JackFreewheelDriver.cpp',
        'JackInternalClient.cpp',
        'JackServer.cpp',
        'JackThreadedDriver.cpp',
        'JackRestartThreadedDriver.cpp',
        'JackWaitThreadedDriver.cpp',
        'JackServerAPI.cpp',
        'JackDriverLoader.cpp',
        'JackServerGlobals.cpp',
        'JackControlAPI.cpp',
        'JackNetTool.cpp',
        'JackNetInterface.cpp',
        'JackArgParser.cpp',
        'JackMidiAsyncQueue.cpp',
        'JackMidiAsyncWaitQueue.cpp',
        'JackMidiBufferReadQueue.cpp',
        'JackMidiBufferWriteQueue.cpp',
        'JackMidiRawInputWriteQueue.cpp',
        'JackMidiRawOutputWriteQueue.cpp',
        'JackMidiReadQueue.cpp',
        'JackMidiReceiveQueue.cpp',
        'JackMidiSendQueue.cpp',
        'JackMidiUtil.cpp',
        'JackMidiWriteQueue.cpp'
        ]

    if bld.env['IS_LINUX']:
        serverlib.source += [
            '../posix/JackSocketServerChannel.cpp',
            '../posix/JackSocketNotifyChannel.cpp',
            '../posix/JackSocketServerNotifyChannel.cpp',
            '../posix/JackNetUnixSocket.cpp',
            ]

    if bld.env['IS_SUN']:
        serverlib.source += [
            '../posix/JackSocketServerChannel.cpp',
            '../posix/JackSocketNotifyChannel.cpp',
            '../posix/JackSocketServerNotifyChannel.cpp',
            '../posix/JackNetUnixSocket.cpp',
            ]

    if bld.env['IS_MACOSX']:
        serverlib.source += [
            '../posix/JackSocketServerChannel.cpp',
            '../posix/JackSocketNotifyChannel.cpp',
            '../posix/JackSocketServerNotifyChannel.cpp',
            '../posix/JackNetUnixSocket.cpp',
            ]

    serverlib.vnum = bld.env['JACK_API_VERSION']

    if bld.env['IS_LINUX']:
        serverlib.env.append_value("CPPFLAGS", "-fvisibility=hidden")

    if bld.env['IS_MACOSX']:
        serverlib.env.append_value("CPPFLAGS", "-fvisibility=hidden")
        serverlib.env.append_value("CPPFLAGS", "-mmacosx-version-min=10.4 -arch i386 -arch ppc -arch x86_64")
        #serverlib.env.append_value("LINKFLAGS", "-framework CoreAudio -framework vecLib -single_module -arch i386 -arch ppc -arch x86_64")
        serverlib.env.append_value("LINKFLAGS", "-framework CoreAudio -framework CoreFoundation -framework vecLib -single_module")
        serverlib.env.append_value("LINKFLAGS", "-compatibility_version 1 -current_version 1")

    if bld.env['IS_SUN']:
        serverlib.env.append_value("LINKFLAGS", "-lnsl -lsocket")

    if bld.env['BUILD_NETLIB'] == True:
        netlib = bld.new_task_gen('cxx', 'shlib')
        netlib.features.append('cc')
        netlib.defines = ['HAVE_CONFIG_H','SERVER_SIDE']
        netlib.includes = includes
        netlib.name         = 'netlib'
        netlib.target       = 'jacknet'
        netlib.uselib = ['SAMPLERATE', 'CELT', 'PTHREAD' , 'RT']
        netlib.install_path = '${LIBDIR}'
        netlib.source = [
            'JackNetAPI.cpp',
            'JackNetInterface.cpp',
            'JackNetTool.cpp',
            'JackAudioAdapterInterface.cpp',
            'JackLibSampleRateResampler.cpp',
            'JackResampler.cpp',
            'JackGlobals.cpp',
            'ringbuffer.c']

        if bld.env['IS_LINUX']:
            netlib.source += ['../posix/JackNetUnixSocket.cpp','../posix/JackPosixThread.cpp', '../linux/JackLinuxTime.c']
            netlib.env.append_value("CPPFLAGS", "-fvisibility=hidden")

        if bld.env['IS_SUN']:
            netlib.source += ['../posix/JackNetUnixSocket.cpp','../posix/JackPosixThread.cpp', '../solaris/JackSolarisTime.c']
            netlib.env.append_value("CPPFLAGS", "-fvisibility=hidden")
       

        if bld.env['IS_MACOSX']:
            netlib.source += ['../posix/JackNetUnixSocket.cpp','../posix/JackPosixThread.cpp', '../macosx/JackMachThread.cpp', '../macosx/JackMachTime.c']
            netlib.env.append_value("LINKFLAGS", "-framework CoreAudio -single_module")

        netlib.vnum = bld.env['JACK_API_VERSION']

    clientlib = bld.new_task_gen('cxx', 'shlib')
    clientlib.features.append('cc')
    clientlib.defines = 'HAVE_CONFIG_H'
    clientlib.uselib = uselib
    clientlib.install_path = '${LIBDIR}'
    if bld.env['BUILD_JACKDBUS'] == True and bld.env['BUILD_JACKD'] == False:
        clientlib.uselib.append('DBUS-1')
    clientlib.includes = includes
    clientlib.name         = 'clientlib'
    clientlib.target       = 'jack'
    clientlib.source = [] + common_libsources
    clientlib.source += [
        'JackLibClient.cpp',
        'JackLibAPI.cpp',
        ]

    if bld.env['IS_LINUX']:
        clientlib.source += [
            '../posix/JackSocketClientChannel.cpp',
            '../posix/JackPosixServerLaunch.cpp',
            ]

    if bld.env['IS_SUN']:
        clientlib.source += [
            '../posix/JackSocketClientChannel.cpp',
            '../posix/JackPosixServerLaunch.cpp',
            ]

    if bld.env['IS_MACOSX']:
        clientlib.source += [
            '../posix/JackSocketClientChannel.cpp',
            '../posix/JackPosixServerLaunch.cpp',
            ]

    clientlib.vnum = bld.env['JACK_API_VERSION']

    if bld.env['IS_LINUX']:
        clientlib.env.append_value("CPPFLAGS", "-fvisibility=hidden")
    
    if bld.env['IS_MACOSX']:
        clientlib.env.append_value("CPPFLAGS", "-fvisibility=hidden")
        clientlib.env.append_value("CPPFLAGS", "-mmacosx-version-min=10.4 -arch i386 -arch ppc -arch x86_64")
        #clientlib.env.append_value("LINKFLAGS", "-framework CoreAudio -framework vecLib -single_module -arch i386 -arch ppc -arch x86_64"
        clientlib.env.append_value("LINKFLAGS", "-framework CoreAudio -framework vecLib -single_module")
        clientlib.env.append_value("LINKFLAGS", "-compatibility_version 1 -current_version 1")

    if bld.env['IS_SUN']:
        clientlib.env.append_value("LINKFLAGS", "-lnsl -lsocket")

    if bld.env['BUILD_WITH_32_64']:
        print "create 32bit lib..."
        clientlib32bit = clientlib.clone('lib32')
  
    create_jack_process_obj(bld, 'netmanager', 'JackNetManager.cpp', serverlib)

    create_jack_process_obj(bld, 'profiler', 'JackProfiler.cpp', serverlib)

    net_adapter_sources = [
        'JackResampler.cpp',
        'JackLibSampleRateResampler.cpp',
        'JackAudioAdapter.cpp',
        'JackAudioAdapterInterface.cpp',
        'JackNetAdapter.cpp',
        ]

    if bld.env['BUILD_ADAPTER'] == True:
        process = create_jack_process_obj(bld, 'netadapter', net_adapter_sources, serverlib)
        process.uselib = 'SAMPLERATE'

    audio_adapter_sources = [
        'JackResampler.cpp',
        'JackLibSampleRateResampler.cpp',
        'JackAudioAdapter.cpp',
        'JackAudioAdapterInterface.cpp',
        'JackAudioAdapterFactory.cpp',
         ]

    if bld.env['BUILD_ADAPTER'] and bld.env['IS_MACOSX']:
         audio_adapter_sources += ['../macosx/coreaudio/JackCoreAudioAdapter.cpp']
         process = create_jack_process_obj(bld, 'audioadapter', audio_adapter_sources, serverlib)
         process.env.append_value("LINKFLAGS", "-framework CoreAudio -framework AudioUnit -framework AudioToolbox -framework CoreServices")
         process.uselib = 'SAMPLERATE'

    if bld.env['BUILD_ADAPTER'] and bld.env['IS_LINUX'] and bld.env['BUILD_DRIVER_ALSA']:
         audio_adapter_sources += ['../linux/alsa/JackAlsaAdapter.cpp']
         process = create_jack_process_obj(bld, 'audioadapter', audio_adapter_sources, serverlib)
         process.uselib = ['ALSA', 'SAMPLERATE']

    if bld.env['BUILD_ADAPTER'] and bld.env['IS_SUN']:
         audio_adapter_sources += ['../solaris/oss/JackOSSAdapter.cpp', 'memops.c']
         process = create_jack_process_obj(bld, 'audioadapter', audio_adapter_sources, serverlib)
         process.uselib = 'SAMPLERATE'

    #audio_adapter_sources += ['../windows/JackPortAudioAdapter.cpp']
    #process = create_jack_process_obj(bld, 'audioadapter', audio_adapter_sources, serverlib)

    bld.install_files('${PREFIX}/include/jack', 'jack/*.h')

    # process jack.pc.in -> jack.pc
    import misc
    obj = bld.new_task_gen('subst')
    obj.source = '../jack.pc.in'
    obj.target = 'jack.pc'
    obj.dict = {'PREFIX': bld.env['PREFIX'],
                'LIBDIR': bld.env['LIBDIR'],
                'INCLUDEDIR': os.path.normpath(bld.env['PREFIX'] + '/include'),
                'SERVERLIB': serverlib.target,
                'JACK_VERSION': bld.env['JACK_VERSION'],
                }
    obj.install_path = '${LIBDIR}/pkgconfig/'
    obj.fun = misc.subst_func
