#! -*- python -*-
#
# Copyright (c) 2011 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import os.path
import json

def Pexe(env, name, sources):
    blah = name + '.nmf'
    progName = name + '.debug.pexe'
    debug_pexe = env.Program(progName, sources)
    return FinalizePexe(env, name)

def NexeNmf(env, target, source):
    tp = target[0].get_path()
    def n(arch):
        return {"url": '{0}_{1}.nexe'.format(tp, arch)}

    content = {
      "program": {
        "x86-64": n('x86_64'),
        "x86-32": n('x86_32'),
        "arm": n('arm'),
      }
    }

    json.dump(content, file(tp + '.nmf', 'wt'))

def PexeNmf(env, name):
    return env.Command(
        blah,
        prog,
        'python $NACL_SDK_ROOT/tools/create_nmf.py -o $TARGET $SOURCE -s ./pnacl/Debug',
    )

def FinalizePexe(env, source):
    env.Command(
        source + '.final.pexe',
        source + '.debug.pexe',
        '$NACL_BIN/pnacl-finalize $SOURCE -o $TARGET'
    )

def TranslatePexe(env, name, sources, arch):
    env.Command(
        '{0}_{1}.nexe'.format(name, arch),
        sources,
        '$NACL_BIN/pnacl-translate -arch ' + arch + ' $SOURCE -o $TARGET'
    )

def NaClEnvironment():
    env = Environment(BUILDERS={'NexeNmf': Builder(action=NexeNmf)})
    env.AddMethod(Pexe, 'Pexe')

    env['NACL_HOST'] = 'host_x86_64'
    env['NACL_SDK_ROOT'] = '/Users/andy/src/nacl_sdk/pepper_35'
    env['NACL_TOOLCHAIN'] = '$NACL_SDK_ROOT/toolchain/mac_pnacl/$NACL_HOST'
    env['NACL_BIN'] = '$NACL_SDK_ROOT/toolchain/mac_pnacl/bin'
    env['CONFIG'] = 'Debug'

    env['NACL_ARCH'] = 'pnacl'

    env['CC'] = '$NACL_BIN/pnacl-clang'
    env['CXX'] = '$NACL_BIN/pnacl-clang++'

    env.Append(LIBPATH=[
            '$NACL_SDK_ROOT/lib/pnacl/$CONFIG'
        ]
    )

    env.Append(CPPDEFINES=[
            'NACL_ARCH=$NACL_ARCH',
            'NACL_SDK_DEBUG',
            # 'USE_TR1'
        ]
    )

    env.Append(CPPPATH=[
            '$NACL_SDK_ROOT/include'
        ]
    )

    env.Append(CXXFLAGS=[
            '-fcolor-diagnostics'
        ]
    )

    env.Append(CFLAGS=[
            '-MMD',
            '-Wno-long-long',
        ]
    )

    env.Append(LIBS=[
            'ppapi',
            'ppapi_cpp',
        ]
    )

    return env

dumbSource = ['src/dumb/' + s for s in Split("""
    core/atexit.c
    core/duhlen.c
    core/duhtag.c
    core/dumbfile.c
    core/loadduh.c
    core/makeduh.c
    core/rawsig.c
    core/readduh.c
    core/register.c
    core/rendduh.c
    core/rendsig.c
    core/unload.c
    helpers/clickrem.c
    helpers/memfile.c
    helpers/resample.c
    helpers/sampbuf.c
    helpers/silence.c
    helpers/stdfile.c
    it/itload.c
    it/itload2.c
    it/itmisc.c
    it/itorder.c
    it/itread.c
    it/itread2.c
    it/itrender.c
    it/itunload.c
    it/loadmod.c
    it/loadmod2.c
    it/loads3m.c
    it/loads3m2.c
    it/loadxm.c
    it/loadxm2.c
    it/readmod.c
    it/readmod2.c
    it/reads3m.c
    it/reads3m2.c
    it/readxm.c
    it/readxm2.c
    it/xmeffect.c
""")]

audiereSource = ['src/audiere/' + s for s in Split("""
    basic_source.cpp
    cd_null.cpp
    debug.cpp
    device.cpp
    device_mixer.cpp
    device_nacl.cpp
    device_null.cpp
    dumb_resample.cpp
    file_ansi.cpp
    input.cpp
    input_aiff.cpp
    input_mod.cpp
    input_wav.cpp
    loop_point_source.cpp
    memory_file.cpp
    midi_null.cpp
    mpaudec/bits.c
    mpaudec/mpaudec.c
    noise.cpp
    resampler.cpp
    sample_buffer.cpp
    sound.cpp
    sound_effect.cpp
    square_wave.cpp
    threads_posix.cpp
    timer_posix.cpp
    tone.cpp
    utility.cpp
    version.cpp
""")]

sources = Split("""
andyvc.cpp  engine.cpp  menu.cpp    nichgvc.cpp ricvc.cpp   vc.cpp      xbigdvc.cpp
battle.cpp  entity.cpp  menu2.cpp   pcx.cpp     sound.cpp   vclib.cpp
control.cpp main.cpp    render.cpp  timer.cpp   vga.cpp

fs.cpp      nacl.cpp    stack.cpp   base64.cpp
""")
sources = ['src/' + s for s in sources]

#nacl_env = NaClEnvironment()
#nacl_env.Append(
#    CPPPATH=['src/dumb/include'],
#    CXXFLAGS=['-std=gnu++0x'],#, '-finstrument-functions'],
#    CPPDEFINES=['NO_FLAC', 'NO_SPEEX', 'NO_OGG', 'NO_MP3', 'AUDIERE_NACL', 'VERGE_AUDIO']
#)
#nacl_env['STRIP'] = os.path.join(nacl_utils.FindToolchain(), 'bin', 'nacl-strip')
#nexes = nacl_env.AllNaClModules(sources + audiereSource + dumbSource, 'v1nacl')
#archs = ['x86', 'x64']
#nacl_env.AddPostAction(nexes, "$STRIP $TARGET")

env = NaClEnvironment()

env.Append(
    CPPPATH=[
        'src/dumb/include'
    ],
    CXXFLAGS=[
        # '-std=c++11',
        '-std=gnu++11',
        #'-Werror', # Hahaha no way.  This code dates back to like 1997.
    ],
    CPPDEFINES=[
        'NO_FLAC',
        'NO_SPEEX',
        'NO_OGG',
        'NO_MP3',
        'AUDIERE_NACL',
        'VERGE_AUDIO'
    ]
)

pexe = env.Pexe('verge', sources + audiereSource + dumbSource)

# x64 = TranslatePexe(env, 'verge', pexe, 'x86_64')
# x86 = TranslatePexe(env, 'verge', pexe, 'x86_32')
# arm = TranslatePexe(env, 'verge', pexe, 'arm')

# nmf = env.NexeNmf('verge', pexe)
