Import('use');

def isOSX():
    import re
    import sys
    return "darwin" in sys.platform

def isWindows():
    import re
    import sys
    return "win32" in sys.platform

obj_files = []

usePartialLinking = False

def setupPartialLinking():
    def linkPartial(target, source, env):
        env.Execute(Action('@ld -r -o %s %s' % (target[0].path, ' '.join([x.path for x in source]))))

    linkLine = 'Partial link $TARGET $SOURCES'
    try:
        linkLine = use['LINKCOMSTR']
    except KeyError:
        pass

    import SCons
    static_obj, shared_obj = SCons.Tool.createObjBuilders(use)
    partialBuilder = Builder(action = Action(linkPartial, cmdstr = linkLine),
                             suffix = '.o',
                             src_suffix = '.o',
                             src_builder = static_obj)
    use.Append(BUILDERS = {'PartialObject' : partialBuilder})

if usePartialLinking:
    setupPartialLinking()

partial = [0]
def addFiles(files):
    if usePartialLinking:
        obj_files.append(use.PartialObject('partial%d.o' % partial[0], map(lambda x: x.replace('src/', ''), files)))
        partial[0] = partial[0] + 1
    else:
        obj_files.append(map(lambda x: x.replace('src/', ''), files))

def findDirectory(name):
    import os.path
    where = '.'

    for i in xrange(0, 5):
        if os.path.exists("%s/%s" % (where, name)):
            return "%s/%s" % (where, name)
        where = os.path.join(where, '..')
    raise Exception("Could not find the %s directory" % name)

import sys
sys.path.append(findDirectory("scons"))
import helpers

obj_files = []

def findCmake():
    return findDirectory('cmake')
    
filelist = helpers.read_cmake_list("%s/FileList.cmake" % findCmake())

for i in filelist:
    addFiles(filelist[i])

def useSDL():
    return use['MUGEN_BACKEND'] == 'sdl'

def useAllegro5():
    return use['MUGEN_BACKEND'] == 'allegro5'

def useAllegro4():
    return use['MUGEN_BACKEND'] == 'allegro'

def useMinpspw():
    import os
    try:
        return int(os.environ['minpspw'])
    except KeyError:
        return False

def icon():
    if isWindows() and not useMinpspw():
        return ['util/windows/game.res']
    else:
        return []

def main():
    return ['xmain.cpp']

options = {'networking': use['MUGEN_NETWORKING'],
           'sdl': useSDL(),
           'allegro': useAllegro4(),
           'allegro5': useAllegro5()
          }

# Make this a function so we don't clobber the 'use' variable
def buildStuff(use):
    SConscript('mugen/SConscript', exports = ['use'])

mugenEnv = use.Clone()

buildStuff(mugenEnv)

mugenBinary = mugenEnv.Program('Mugen', obj_files + main() + icon())
mugenEnv.Depends(mugenBinary, mugenEnv['ARCHIVES'])

x = []
x.append(mugenBinary)

Return('x')