# vim:filetype=python

import os
import re
from subprocess import *

target = 'anaglym'
DEBUG = False

Default(target)
if 'install_dir' in os.environ:
    install_dir = os.environ['install_dir']
else:
    install_dir = os.environ['HOME'] + '/local/' + target
if os.sep == '\\':
    platform = 'PLATFORM_WINDOWS'
else:
    platform = 'PLATFORM_LINUX'

env = Environment()
env.ParseConfig('pkg-config --cflags --libs lua5.1')
env.ParseConfig('pkg-config --cflags --libs ftgl')
env.ParseConfig('sdl-config --cflags --libs')
env.ParseConfig('ode-config --cflags --libs')
env.ParseConfig('smpeg-config --libs')

if platform == 'PLATFORM_WINDOWS':
    env.Append(LIBS = ['opengl32', 'glu32', 'mingw32'])

if platform == 'PLATFORM_LINUX':
    env.Append(LIBS = ['GL', 'GLU'])

env.Append(CPPFLAGS = ['-D'+platform, '-I.', '-DGL_GLEXT_PROTOTYPES'])
env.Append(LIBS = ['SDL_image', 'SDL_sound', 'vorbisfile'])
env.Append(CCFLAGS = ['-O2', '-Wall'])
if DEBUG:
    env.Append(CCFLAGS = ['-g'])

sources = [
        'cfs.cc',
        'sdl_keymap.cc',
        Glob('src/*.cc'),
        'OdeWorld/OdeWorld.cc',
        'PhyObj/PhyObj.cc',
        'TextureCache/TextureCache.cc',
        'wfobj/WFObj.cc',
        'glslUtil/glslUtil.c',
        ]

def CFS(target, source, env):
    source_list = []
    for s in source:
        source_list.append(str(s))
    Popen(['./cfs_gen/cfs_gen.py', str(target[0])] + source_list).wait()
    return None

def CFS_emitter(target, source, env):
    target.append(re.sub(r'\.cc?', '.h', str(target[0])))
    return target, source

def bt(cmd):
    return Popen(cmd, shell = True, stdout = PIPE).communicate()[0]

env.Append(BUILDERS = {'CFS' : Builder(action = CFS, emitter = CFS_emitter)})

cfs_sources = [
        'src/ag.lua',
        Glob('shaders/*'),
        ]

env.CFS('cfs.cc', cfs_sources)
env.Depends('cfs.cc', 'cfs_gen/cfs_gen.py')
env.Command('sdl_keymap.cc', 'gen-sdl-keymap.pl', 'perl gen-sdl-keymap.pl')
env.Program(target, sources)

env.Install('dist', target)
env.Install('dist', 'lib')
env.Install('dist', 'doc')
if platform == 'PLATFORM_WINDOWS':
    env.Install('dist', bt('which SDL.dll'))
    env.Install('dist', bt('which SDL.dll'))
    env.Install('dist', bt('which SDL_image.dll'))
    env.Install('dist', bt('which jpeg.dll'))
    env.Install('dist', bt('which libpng12-0.dll'))
    env.Install('dist', bt('which zlib1.dll'))
    env.Install('dist', bt('which libtiff-3.dll'))
    env.Install('dist', bt('which libftgl-2.dll'))
    env.Install('dist', bt('which lua5.1.dll'))
    env.Install('dist', bt('which freetype6.dll'))
    env.Install('dist', bt('which libogg-0.dll'))
    env.Install('dist', bt('which libvorbis-0.dll'))
    env.Install('dist', bt('which libvorbisfile-3.dll'))

env.Clean('dist', 'dist')
