#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import SCons
import shutil

Import('build')


# On Posix default SCons.LIBPREFIX = 'lib', on Windows default SCons.LIBPREFIX = ''

m4a_sources = [
    "soundsource.cpp", # required to subclass soundsource
    "soundsourcem4a.cpp",  # MP4/M4A Support through FAAD/libmp4v2
]


#Tell SCons to build the SoundSourceM4A plugin
#=========================
if int(build.flags['faad']):
    env = build.env.Clone()

    conf = Configure(env)

    have_mp4v2_h = conf.CheckHeader('mp4v2/mp4v2.h')
    have_mp4 = (have_mp4v2_h and conf.CheckLib(['mp4v2', 'libmp4v2'])) or \
        conf.CheckLib('mp4')

    have_faad = conf.CheckLib(['faad', 'libfaad'])
    have_faad_26 = False

    # We have to check for libfaad version 2.6 or 2.7. In libfaad
    # version 2.7, the type for the samplerate is unsigned long*,
    # while in 2.6 the type is uint32_t*. We can use the optional
    # call parameter to CheckLibWithHeader to build a test file to
    # check which one this faad.h supports.

    # Check for libfaad version 2.6. This check doesn't work correctly on Windows
    # And we build it manually anyway, so we know it's v2.7
    if have_faad and not build.platform_is_windows:
        have_faad_26 = (not conf.CheckLibWithHeader(
                'libfaad', 'faad.h', 'c++',
                call = 'faacDecInit2(0, 0, 0, (unsigned long*)0, (unsigned char*)0);',
                autoadd=False))

    if have_faad_26:
        env.Append(CPPDEFINES = '__M4AHACK__')
        print "libfaad 2.6 compatibility mode... enabled"
    if have_mp4v2_h:
        env.Append(CPPDEFINES = '__MP4V2__')

    env = conf.Finish()
    SHLIBPREFIX='lib' #Makes the filename "libsoundsourcem4a" consistently across platforms to make our lives easier.
    if build.platform_is_windows:
        env["LINKFLAGS"].remove("/entry:mainCRTStartup")
        env["LINKFLAGS"].remove("/subsystem:windows")
        ssm4a_bin = env.SharedLibrary('soundsourcem4a', m4a_sources, LINKCOM  = [env['LINKCOM'], 'mt.exe -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;1'])
    else:
        ssm4a_bin = env.SharedLibrary('soundsourcem4a', m4a_sources)

    #Pass this soundsourcem4a library object file back to the SConscript above us.
    Return("ssm4a_bin")
else:
    Return("")



