#!/usr/bin/env python
from waflib.extras import autowaf as autowaf
from waflib import Options
import os
import re
import subprocess

# Version of this package (even if built as a child)
MAJOR = '3'
MINOR = '0'
MICRO = '0'
LIBARDOUR_VERSION = "%s.%s.%s" % (MAJOR, MINOR, MICRO)

# Library version (UNIX style major, minor, micro)
# major increment <=> incompatible changes
# minor increment <=> compatible changes (additions)
# micro increment <=> no interface changes
LIBARDOUR_LIB_VERSION = '3.0.0'

# default state file version for this build
CURRENT_SESSION_FILE_VERSION = 3001

# Variables for 'waf dist'
APPNAME = 'libardour3'
VERSION = LIBARDOUR_VERSION
I18N_PACKAGE = 'libardour3'

# Mandatory variables
top = '.'
out = 'build'

path_prefix = 'libs/ardour/'

libardour_sources = [
        'amp.cc',
        'analyser.cc',
        'audio_buffer.cc',
        'audio_diskstream.cc',
        'audio_library.cc',
        'audio_playlist.cc',
        'audio_playlist_importer.cc',
        'audio_playlist_source.cc',
        'audio_port.cc',
        'audio_region_importer.cc',
        'audio_track.cc',
        'audio_track_importer.cc',
        'audioanalyser.cc',
        'audioengine.cc',
        'audiofile_tagger.cc',
        'audiofilesource.cc',
        'audioregion.cc',
        'audiosource.cc',
        'auditioner.cc',
        'automatable.cc',
        'automation.cc',
        'automation_control.cc',
        'automation_list.cc',
        'automation_watch.cc',
        'beats_frames_converter.cc',
        'broadcast_info.cc',
        'buffer.cc',
        'buffer_manager.cc',
        'buffer_set.cc',
        'bundle.cc',
        'butler.cc',
        'callback.cc',
        'capturing_processor.cc',
        'chan_count.cc',
        'chan_mapping.cc',
        'configuration.cc',
        'config_text.cc',
        'control_protocol_manager.cc',
        'control_protocol_search_path.cc',
        'cycle_timer.cc',
        'data_type.cc',
        'default_click.cc',
        'debug.cc',
        'delivery.cc',
        'directory_names.cc',
        'diskstream.cc',
        'element_import_handler.cc',
        'element_importer.cc',
        'enums.cc',
        'event_type_map.cc',
        'export_channel.cc',
        'export_channel_configuration.cc',
        'export_failed.cc',
        'export_filename.cc',
        'export_format_base.cc',
        'export_format_manager.cc',
        'export_format_specification.cc',
        'export_formats.cc',
        'export_formats_search_path.cc',
        'export_graph_builder.cc',
        'export_handler.cc',
        'export_preset.cc',
        'export_profile_manager.cc',
        'export_status.cc',
        'export_timespan.cc',
        'file_source.cc',
        'filename_extensions.cc',
        'filesystem_paths.cc',
        'filter.cc',
        'find_session.cc',
        'globals.cc',
        'graph.cc',
        'graphnode.cc',
        'import.cc',
        'instrument_info.cc',
        'internal_return.cc',
        'internal_send.cc',
        'interpolation.cc',
        'io.cc',
        'io_processor.cc',
        'jack_slave.cc',
        'ladspa_plugin.cc',
        'location.cc',
        'location_importer.cc',
        'meter.cc',
        'midi_automation_list_binder.cc',
        'midi_buffer.cc',
        'midi_clock_slave.cc',
        'midi_diskstream.cc',
        'midi_model.cc',
        'midi_patch_manager.cc',
        'midi_patch_search_path.cc',
        'midi_playlist.cc',
        'midi_playlist_source.cc',
        'midi_port.cc',
        'midi_region.cc',
        'midi_ring_buffer.cc',
        'midi_source.cc',
        'midi_state_tracker.cc',
        'midi_stretch.cc',
        'midi_track.cc',
        'midi_ui.cc',
        'mix.cc',
        'monitor_processor.cc',
        'mtc_slave.cc',
        'mtdm.cc',
        'mute_master.cc',
        'onset_detector.cc',
        'operations.cc',
        'pan_controllable.cc',
        'pannable.cc',
        'panner.cc',
        'panner_manager.cc',
        'panner_search_path.cc',
        'panner_shell.cc',
        'pcm_utils.cc',
        'pi_controller.cc',
        'playlist.cc',
        'playlist_factory.cc',
        'playlist_source.cc',
        'plugin.cc',
        'plugin_insert.cc',
        'plugin_manager.cc',
        'port.cc',
        'port_insert.cc',
        'port_set.cc',
        'process_thread.cc',
        'processor.cc',
        'progress.cc',
        'quantize.cc',
        'rc_configuration.cc',
        'recent_sessions.cc',
        'region_factory.cc',
        'resampled_source.cc',
        'region.cc',
        'return.cc',
        'reverse.cc',
        'route.cc',
        'route_graph.cc',
        'route_group.cc',
        'route_group_member.cc',
        'rb_effect.cc',
        'send.cc',
        'session.cc',
        'session_butler.cc',
        'session_click.cc',
        'session_command.cc',
        'session_configuration.cc',
        'session_directory.cc',
        'session_events.cc',
        'session_export.cc',
        'session_handle.cc',
        'session_metadata.cc',
        'session_midi.cc',
        'session_object.cc',
        'session_playlists.cc',
        'session_process.cc',
        'session_rtevents.cc',
        'session_state.cc',
        'session_state_utils.cc',
        'session_time.cc',
        'session_transport.cc',
        'slave.cc',
        'smf_source.cc',
        'sndfile_helpers.cc',
        'sndfileimportable.cc',
        'sndfilesource.cc',
        'source.cc',
        'source_factory.cc',
        'speakers.cc',
        'strip_silence.cc',
        'svn_revision.cc',
        'tape_file_matcher.cc',
        'template_utils.cc',
        'tempo.cc',
        'tempo_map_importer.cc',
        'thread_buffers.cc',
        'ticker.cc',
        'track.cc',
        'transient_detector.cc',
        'unknown_processor.cc',
        'user_bundle.cc',
        'utils.cc',
        'version.cc',
        'worker.cc',
]

def flac_supported():
    cmd = subprocess.Popen ("sndfile-info testfile.flac",
                            stdout = subprocess.PIPE,
                            stderr = subprocess.STDOUT, shell = True)
    out = cmd.communicate()[0].decode('utf-8');
    return re.search ('unknown format', out) == None

def ogg_supported():
    cmd = subprocess.Popen ("sndfile-info testfile.ogg",
                            stdout = subprocess.PIPE,
                            stderr = subprocess.STDOUT, shell = True)
    out = cmd.communicate()[0].decode('utf-8');
    return re.search ('unknown format', out) == None

def options(opt):
    autowaf.set_options(opt)

def configure(conf):
    conf.load('compiler_cxx')
    conf.load('gas')
    autowaf.build_version_files(
        path_prefix + 'ardour/version.h',
        path_prefix + 'version.cc',
        'libardour3', MAJOR, MINOR, MICRO)
    autowaf.configure(conf)
    autowaf.check_pkg(conf, 'aubio', uselib_store='AUBIO',
                      atleast_version='0.3.2')
    autowaf.check_pkg(conf, 'jack', uselib_store='JACK',
                      atleast_version='0.118.2')
    autowaf.check_pkg(conf, 'libxml-2.0', uselib_store='XML')
    autowaf.check_pkg(conf, 'lrdf', uselib_store='LRDF',
                      atleast_version='0.4.0')
    autowaf.check_pkg(conf, 'samplerate', uselib_store='SAMPLERATE',
                      atleast_version='0.1.0')
    autowaf.check_pkg(conf, 'sigc++-2.0', uselib_store='SIGCPP',
                      atleast_version='2.0')
    if Options.options.lv2:
        autowaf.check_pkg(conf, 'lv2', uselib_store='LV2',
                          atleast_version='1.0.0', mandatory=True)
        autowaf.check_pkg(conf, 'lv2', uselib_store='NEW_LV2',
                          atleast_version='1.0.15', mandatory=False)
        autowaf.check_pkg(conf, 'serd-0', uselib_store='SERD',
                          atleast_version='0.14.0', mandatory=True)
        autowaf.check_pkg(conf, 'sord-0', uselib_store='SORD',
                          atleast_version='0.8.0', mandatory=True)
        autowaf.check_pkg(conf, 'sratom-0', uselib_store='SRATOM',
                          atleast_version='0.2.0', mandatory=True)
        autowaf.check_pkg(conf, 'lilv-0', uselib_store='LILV',
                          atleast_version='0.14.0', mandatory=True)
        autowaf.check_pkg(conf, 'suil-0', uselib_store='SUIL',
                          atleast_version='0.6.0', mandatory=False)
        conf.define ('LV2_SUPPORT', 1)

#    autowaf.check_pkg(conf, 'soundtouch-1.0', uselib_store='SOUNDTOUCH',
#                      mandatory=False)
    autowaf.check_pkg(conf, 'cppunit', uselib_store='CPPUNIT',
                      atleast_version='1.12.0', mandatory=False)
    autowaf.check_pkg(conf, 'ogg', uselib_store='OGG', atleast_version='1.1.2')
    autowaf.check_pkg(conf, 'flac', uselib_store='FLAC',
                      atleast_version='1.2.1')
    autowaf.check_pkg(conf, 'libcurl', uselib_store='CURL',
                      atleast_version='7.0.0')
    autowaf.check_pkg(conf, 'ltc', uselib_store='LTC',
                      atleast_version='0.3.2', mandatory=False)

    # we don't try to detect this, since its part of our source tree

    conf.define('HAVE_RUBBERBAND', 1) # controls whether we think we have it
    conf.define('USE_RUBBERBAND', 1)  # controls whether we actually use it

    conf.define('CURRENT_SESSION_FILE_VERSION', CURRENT_SESSION_FILE_VERSION)

    conf.check(header_name='sys/vfs.h', define_name='HAVE_SYS_VFS_H',mandatory=False)
    conf.check(header_name='sys/statvfs.h', define_name='HAVE_SYS_STATVFS_H',mandatory=False)

    conf.check(header_name='jack/session.h', uselib = [ 'JACK' ],
               define_name='HAVE_JACK_SESSION')

    conf.check(header_name='unistd.h', define_name='HAVE_UNISTD',mandatory=False)

    conf.check_cc(fragment = '''
#include <jack/jack.h>
void callback(jack_status_t code, const char* reason, void* arg) { return; }
int main(int argc, char **argv) {
    jack_client_t* c;
    jack_on_info_shutdown(c, callback, (void*) 0);
    return 0;
}''',
                  uselib= [ 'JACK' ],
                  msg = 'Checking for jack_on_info_shutdown',
                  define_name = 'HAVE_JACK_ON_INFO_SHUTDOWN',
                  okmsg = 'present')

    missing_jack_message = 'missing - a version of JACK that supports jack_port_set_latency_range() is required to compile Ardour3.'

    conf.check_cc(fragment = '''
#include <jack/jack.h>
int main(int argc, char **argv) {
    jack_port_t* p;
    jack_latency_range_t r;
    jack_port_set_latency_range(p, JackCaptureLatency, &r);
    return 0;
}''',
                  uselib = [ 'JACK' ],
                  msg = 'Checking for new JACK latency API',
                  okmsg = 'present',
                  mandatory = True,
                  errmsg = missing_jack_message)

    conf.check_cc(fragment = '''
#include <jack/jack.h>
int main(int argc, char **argv) {
   jack_port_type_get_buffer_size((jack_client_t*)0, "");
   return 0;
}''',
                  uselib = [ 'JACK' ],
                  msg = 'Checking for new jack_port_type_get_buffer_size',
                  okmsg = 'present',
                  mandatory = True,
                  errmsg = missing_jack_message)

    if flac_supported():
        conf.define ('HAVE_FLAC', 1)
    if ogg_supported():
        conf.define ('HAVE_OGG', 1)

    conf.write_config_header('libardour-config.h', remove=False)

    # Boost headers
    autowaf.check_header(conf, 'cxx', 'boost/shared_ptr.hpp')
    autowaf.check_header(conf, 'cxx', 'boost/weak_ptr.hpp')
    autowaf.check_header(conf, 'cxx', 'boost/scoped_ptr.hpp')
    autowaf.check_header(conf, 'cxx', 'boost/ptr_container/ptr_list.hpp')


def build(bld):
    # Library
    obj              = bld(features = 'c cxx cshlib cxxshlib')
    obj.source       = libardour_sources
    obj.export_includes = ['.']
    obj.includes     = ['.', '../surfaces/control_protocol', '..']
    obj.name         = 'libardour'
    obj.target       = 'ardour'
    obj.uselib       = ['GLIBMM','GTHREAD','AUBIO','SIGCPP','XML','UUID',
                        'JACK','SNDFILE','SAMPLERATE','LRDF','AUDIOUNITS',
                        'OSX','BOOST','CURL','DL']
    obj.use          = ['libpbd','libmidipp','libevoral','libvamphost',
                        'libvampplugin','libtaglib','librubberband',
                        'libaudiographer']
    obj.vnum         = LIBARDOUR_LIB_VERSION
    obj.install_path = os.path.join(bld.env['LIBDIR'], 'ardour3')
    obj.defines      = [
        'PACKAGE="' + I18N_PACKAGE + '"',
        'DATA_DIR="' + os.path.normpath(bld.env['DATADIR']) + '"',
        'CONFIG_DIR="' + os.path.normpath(bld.env['SYSCONFDIR']) + '"',
        'LOCALEDIR="' + os.path.join(os.path.normpath(bld.env['DATADIR']), 'locale') + '"',
        'PROGRAM_NAME="' + bld.env['PROGRAM_NAME'] + '"',
        'EVORAL_MIDI_XML=1' 
        ]

    #obj.source += ' st_stretch.cc st_pitch.cc '
    #obj.uselib += ' SOUNDTOUCH '
    #obj.add_objects = 'default/libs/surfaces/control_protocol/smpte_1.o'

    if bld.is_defined('HAVE_LTC') :
        obj.source += ['ltc_slave.cc']
        obj.uselib += ['LTC']

    if bld.is_defined('HAVE_LILV') :
        obj.source += ['lv2_plugin.cc', 'lv2_evbuf.c', 'uri_map.cc'] 
        obj.uselib += ['LILV']
        if bld.is_defined('HAVE_SUIL'):
            obj.uselib += ['SUIL']

    if bld.is_defined('WINDOWS_VST_SUPPORT'):
        obj.source += [ 'windows_vst_plugin.cc']
        obj.includes += [ '../fst' ]
        obj.defines += [ 'WINDOWS_VST_SUPPORT' ]

    if bld.is_defined('LXVST_SUPPORT'):
        obj.source += [ 'lxvst_plugin.cc', 'linux_vst_support.cc', 'linux_vst_info_file.cc' ]
        obj.defines += [ 'LXVST_SUPPORT' ]

    if bld.is_defined('WINDOWS_VST_SUPPORT') or bld.is_defined('LXVST_SUPPORT'):
        obj.source += [ 'session_vst.cc', 'vst_plugin.cc' ]

    if bld.is_defined('HAVE_COREAUDIO'):
        obj.source += [ 'coreaudiosource.cc', 'caimportable.cc' ]
        obj.use    += ['libappleutility']

    if bld.is_defined('AUDIOUNIT_SUPPORT'):
        obj.source += [ 'audio_unit.cc' ]

    if Options.options.fpu_optimization:
        if (bld.env['build_target'] == 'i386' or bld.env['build_target'] == 'i686'):
            obj.source += [ 'sse_functions_xmm.cc', 'sse_functions.s' ]
        elif bld.env['build_target'] == 'x86_64':
            obj.source += [ 'sse_functions_xmm.cc', 'sse_functions_64bit.s' ]

    # i18n
    if bld.is_defined('ENABLE_NLS'):
        mo_files = bld.path.ant_glob('po/*.mo')
        for mo in mo_files:
            lang = os.path.basename(mo.srcpath()).replace('.mo', '')
            bld.install_as(os.path.join(bld.env['PREFIX'], 'share', 'locale',
                                        lang, 'LC_MESSAGES', I18N_PACKAGE + '.mo'),
                           mo)

    if bld.env['BUILD_TESTS'] and bld.is_defined('HAVE_CPPUNIT'):
        # Unit tests
        testobj              = bld(features = 'cxx cxxprogram')
        testobj.source       = '''
                test/dummy_lxvst.cc
                test/test_util.cc
                test/test_needing_session.cc
                test/audio_region_test.cc
                test/test_globals.cc
                test/audio_region_read_test.cc
                test/automation_list_property_test.cc
                test/bbt_test.cc
                test/tempo_test.cc
                test/interpolation_test.cc
                test/midi_clock_slave_test.cc
                test/resampled_source_test.cc
                test/framewalk_to_beats_test.cc
                test/framepos_plus_beats_test.cc
                test/framepos_minus_beats_test.cc
                test/playlist_layering_test.cc
                test/playlist_read_test.cc
                test/playlist_equivalent_regions_test.cc
                test/control_surfaces_test.cc
                test/combine_regions_test.cc
                test/region_naming_test.cc
                test/load_sessions_test.cc
                test/mtdm_test.cc
                test/testrunner.cc
        '''.split()

# Tests that don't work
#                test/mantis_3356_test.cc

        testobj.includes     = obj.includes + ['test', '../pbd']
        testobj.uselib       = ['CPPUNIT','SIGCPP','JACK','GLIBMM','GTHREAD',
                                'SAMPLERATE','XML','LRDF','COREAUDIO']
        testobj.use          = ['libpbd','libmidipp','libardour']
        testobj.name         = 'libardour-tests'
        testobj.target       = 'run-tests'
        testobj.install_path = ''
        testobj.defines      = [
            'PACKAGE="libardour3test"',
            'DATA_DIR="' + os.path.normpath(bld.env['DATADIR']) + '"',
            'CONFIG_DIR="' + os.path.normpath(bld.env['SYSCONFDIR']) + '"',
            'LOCALEDIR="' + os.path.join(
                os.path.normpath(bld.env['DATADIR']), 'locale') + '"',
            'VAMP_DIR="' + os.path.join(
                os.path.normpath(bld.env['LIBDIR']), 'ardour3', 'vamp') + '"'
            ]
        if bld.env['FPU_OPTIMIZATION']:
            testobj.source += [ 'sse_functions_xmm.cc' ]
            if (bld.env['build_target'] == 'i386'
                or bld.env['build_target'] == 'i686'):
                testobj.source += [ 'sse_functions.s' ]
            elif bld.env['build_target'] == 'x86_64':
                testobj.source += [ 'sse_functions_64bit.s' ]

        # Tester to just load a session
        session_load_tester = bld(features = 'cxx cxxprogram')
        session_load_tester.source = '''
                    test/test_util.cc
                    test/load_session.cc
                    test/dummy_lxvst.cc
            '''.split()

        session_load_tester.includes  = obj.includes
        session_load_tester.includes.append ('test')
        session_load_tester.uselib    = ['CPPUNIT','SIGCPP','JACK','GLIBMM','GTHREAD',
                             'SAMPLERATE','XML','LRDF','COREAUDIO']
        session_load_tester.use       = ['libpbd','libmidipp','libardour']
        session_load_tester.name      = 'libardour-session-load-tester'
        session_load_tester.target    = 'load-session'
        session_load_tester.install_path = ''
        session_load_tester.defines      = [
            'PACKAGE="libardour3profile"',
            'DATA_DIR="' + os.path.normpath(bld.env['DATADIR']) + '"',
            'CONFIG_DIR="' + os.path.normpath(bld.env['SYSCONFDIR']) + '"',
            'LOCALEDIR="' + os.path.join(
                os.path.normpath(bld.env['DATADIR']), 'locale') + '"',
            'VAMP_DIR="' + os.path.join(
                os.path.normpath(bld.env['LIBDIR']), 'ardour3', 'vamp') + '"'
            ]
        if bld.env['FPU_OPTIMIZATION']:
            session_load_tester.source += [ 'sse_functions_xmm.cc' ]
            if (bld.env['build_target'] == 'i386'
                or bld.env['build_target'] == 'i686'):
                session_load_tester.source += [ 'sse_functions.s' ]
            elif bld.env['build_target'] == 'x86_64':
                session_load_tester.source += [ 'sse_functions_64bit.s' ]

        # Profiling
        for p in ['runpc', 'lots_of_regions', 'load_session']:
            profilingobj = bld(features = 'cxx cxxprogram')
            profilingobj.source = '''
                    test/dummy_lxvst.cc
                    test/test_util.cc
            '''.split()

            profilingobj.source.append('test/profiling/%s.cc' % p)

            profilingobj.includes  = obj.includes
            profilingobj.includes.append ('test')
            profilingobj.uselib    = ['CPPUNIT','SIGCPP','JACK','GLIBMM','GTHREAD',
                             'SAMPLERATE','XML','LRDF','COREAUDIO']
            profilingobj.use       = ['libpbd','libmidipp','libardour']
            profilingobj.name      = 'libardour-profiling'
            profilingobj.target    = p
            profilingobj.install_path = ''
            profilingobj.defines      = [
                'PACKAGE="libardour3profile"',
                'DATA_DIR="' + os.path.normpath(bld.env['DATADIR']) + '"',
                'CONFIG_DIR="' + os.path.normpath(bld.env['SYSCONFDIR']) + '"',
                'LOCALEDIR="' + os.path.join(
                    os.path.normpath(bld.env['DATADIR']), 'locale') + '"',
                'VAMP_DIR="' + os.path.join(
                    os.path.normpath(bld.env['LIBDIR']), 'ardour3', 'vamp') + '"'
                ]
            if bld.env['FPU_OPTIMIZATION']:
                profilingobj.source += [ 'sse_functions_xmm.cc' ]
                if (bld.env['build_target'] == 'i386'
                    or bld.env['build_target'] == 'i686'):
                    profilingobj.source += [ 'sse_functions.s' ]
                elif bld.env['build_target'] == 'x86_64':
                    profilingobj.source += [ 'sse_functions_64bit.s' ]

def shutdown():
    autowaf.shutdown()

def i18n(bld):
    autowaf.build_i18n(bld, top, 'libs/ardour', I18N_PACKAGE, libardour_sources,
                       'Paul Davis')

def i18n_pot(bld):
    autowaf.build_i18n(bld, top, 'libs/ardour', I18N_PACKAGE, libardour_sources,
                       'Paul Davis')

def i18n_po(bld):
    autowaf.build_i18n_po(bld, top, 'libs/ardour', I18N_PACKAGE, libardour_sources,
                       'Paul Davis')

def i18n_mo(bld):
    autowaf.build_i18n_mo(bld, top, 'libs/ardour', I18N_PACKAGE, libardour_sources,
                       'Paul Davis')
