#
# Copyright (C) 2007 Arnold Krille
# Copyright (C) 2007 Pieter Palmers
# Copyright (C) 2008 Marc-Olivier Barre
#
# This file originates from FFADO (www.ffado.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import os
import glob
from string import Template

def pkg_config_get_value(module, args):
    return env.backtick('pkg-config ' + args + ' ' + module).strip()

def merge_pkg_config_append_string(env, envvar, module, args):
    value = pkg_config_get_value(module, args)
    #print value
    if env._dict.has_key(envvar):
        env._dict[envvar] += value
    else:
        env._dict[envvar] = value

def merge_pkg_config_libs(env, module):
    for lib in pkg_config_get_value(module, "--libs").split(' '):
        if lib[:2] == '-l':
            env._dict['LIBS'].append(lib[2:])
        elif lib[:2] == '-L':
            env._dict['LIBPATH'].append(lib[2:])

def merge_pkg_config_variable(env, envvar, module, pkgvar):
    merge_pkg_config_append_string(env, envvar, module, '--variable=' + pkgvar)

def merge_pkg_config_std(env, module):
    merge_pkg_config_append_string(env, 'CCFLAGS', module, '--cflags')
    merge_pkg_config_libs(env, module)

Import('env')


# Paths where include files can be found
env.AppendUnique(CPPPATH=['#/', '#/common', '#/common/jack'])

# Needed libraries
env.AppendUnique(LIBS=['rt', 'pthread'])

# HACK: this should not be here ideally
env.AppendUnique(CPPPATH=['#/linux','#/macosx'])

# A symlinking command for our libraries' names
symlinkcmd = 'rm -f $TARGET;ln -nsf $SOURCE.name $TARGET'

#
# Source files section
#

srcfiles_common_serverlib = [
    'JackActivationCount.cpp',
    'JackAPI.cpp',
    'JackAudioDriver.cpp',
    'JackClient.cpp',
    'JackConnectionManager.cpp',
    'JackDriver.cpp',
    'JackEngine.cpp',
    'JackEngineControl.cpp',
    'JackError.cpp',
    'JackExternalClient.cpp',
    'JackFrameTimer.cpp',
    'JackFreewheelDriver.cpp',
    'JackGraphManager.cpp',
    'JackInternalClient.cpp',
    'JackPort.cpp',
    'JackPosixSemaphore.cpp',
    'JackPosixThread.cpp',
    'JackFifo.cpp',
    'JackLoopbackDriver.cpp',
    'JackPortType.cpp',
    'JackAudioPort.cpp',
    'JackMidiPort.cpp',
    'JackMidiAPI.cpp',
    'JackServer.cpp',
    'JackShmMem.cpp',
    'JackThreadedDriver.cpp',
    'shm.c',
    'JackSocket.cpp',
    'JackSocketServerChannel.cpp',
    'JackSocketNotifyChannel.cpp',
    'JackSocketServerNotifyChannel.cpp',
    'JackTime.c',
    'JackServerAPI.cpp',
    'JackGlobals.cpp',
    'JackDriverLoader.cpp',
    'JackDebugClient.cpp',
    'JackTransportEngine.cpp',
    'JackServerGlobals.cpp',
    'timestamps.c',
    'JackTools.cpp',
    'ringbuffer.c',
    'JackControl.cpp',
    'JackMessageBuffer.cpp',
    'JackProcessSync.cpp'
    ]

srcfiles_common_clientlib = [
    'JackActivationCount.cpp',
    'JackAPI.cpp',
    'JackClient.cpp',
    'JackConnectionManager.cpp',
    'ringbuffer.c',
    'JackServerLaunch.cpp',
    'JackError.cpp',
    'JackFrameTimer.cpp',
    'JackGraphManager.cpp',
    'JackLibClient.cpp',
    'JackLibAPI.cpp',
    'JackPort.cpp',
    'JackPosixSemaphore.cpp',
    'JackFifo.cpp',
    'JackPortType.cpp',
    'JackAudioPort.cpp',
    'JackMidiPort.cpp',
    'JackMidiAPI.cpp',
    'JackEngineControl.cpp',
    'JackPosixThread.cpp',
    'JackShmMem.cpp',
    'shm.c',
    'JackSocket.cpp',
    'JackSocketClientChannel.cpp',
    'JackTime.c',
    'JackGlobals.cpp',
    'JackDebugClient.cpp',
    'JackTransportEngine.cpp',
    'timestamps.c',
    'JackTools.cpp',
    'JackMessageBuffer.cpp',
    'JackProcessSync.cpp'
    ]

jack_headers = [
    'intclient.h',
    'jack.h',
    'midiport.h',
    'ringbuffer.h',
    'statistics.h',
    'thread.h',
    'transport.h',
    'types.h',
    'control.h',
    'jslist.h'
    ]

#
# Build/install section
#

# Libraries

if env['ENABLE_DBUS']:
    merge_pkg_config_std(env, 'dbus-1') # actually we need this only for client lib

# Each platform should get it's own environment
libenv = env.Copy()
if env['PLATFORM'] == 'posix':
    libenv.Append(SHLIBSUFFIX='.' + env['JACKAPI_VERSION'])
    libenv.Append(SHLINKFLAGS='-Wl,-soname,${str(TARGET.file).split(".")[0]}.so.' + str(env['JACKAPI_MAJOR_VERSION']))

clientlib = libenv.SharedLibrary(env['CLIENTLIB'], srcfiles_common_clientlib)
serverlib = libenv.SharedLibrary(env['SERVERLIB'], srcfiles_common_serverlib)
env.Install( env['INSTALL_LIBDIR'], [clientlib, serverlib])
env.Alias('install', env['INSTALL_LIBDIR'])

# Handle the way we name libraries on a POSIX system
if env['PLATFORM'] == 'posix':
    libs = [(env['CLIENTLIB'], clientlib), (env['SERVERLIB'], serverlib)]
    for lib_name, lib in libs:
        env.Command('#/common/lib' + lib_name + '.so.' + str(env['JACKAPI_MAJOR_VERSION']), lib, symlinkcmd)
        env.Command('#/common/lib' + lib_name + '.so', '#/common/lib' + lib_name + '.so.' + str(env['JACKAPI_MAJOR_VERSION']), symlinkcmd)
        env.Command(env['INSTALL_LIBDIR']  + '/lib' + lib_name + '.so.' + str(env['JACKAPI_MAJOR_VERSION']), env['INSTALL_LIBDIR'] + '/lib' + lib_name + '.so.' + env['JACKAPI_VERSION'], symlinkcmd)
        env.Command(env['INSTALL_LIBDIR']  + '/lib' + lib_name + '.so', env['INSTALL_LIBDIR'] + '/lib' + lib_name + '.so.' + str(env['JACKAPI_MAJOR_VERSION']), symlinkcmd)
        env.Alias('install', env['INSTALL_LIBDIR']  + '/lib' + lib_name + '.so.' + str(env['JACKAPI_MAJOR_VERSION']))

# Headers
for header in jack_headers:
    env.Install(env['INSTALL_INCLUDEDIR'], 'jack/' + header)
