#! /usr/bin/env python

import sys
import urllib
import subprocess
import os
import stat

VERSION = '0.0.1'
APPNAME = 'pez-viewer'

if sys.platform == 'win32':
    EXE = r'.\build\%s.exe' % APPNAME
else:
    EXE = r'./build/%s' % APPNAME

def run(gc):
    gc.exec_command(EXE)
    print

def debug(gc):
    gc.exec_command('gdb ' + EXE)
    print

def options(opt):
    opt.load('gcc')
    opt.load('g++')
    #opt.load('parallel_debug', tooldir='.')

def configure(gc):
    gc.load('gcc')
    gc.load('g++')
    #gc.load('parallel_debug', tooldir='.')
    gc.env.COMMON_DEFS = 'OPENCTM_STATIC'
    gc.check_cc(fragment=c99test, msg="Checking for C99", cflags='-std=c99')
    gc.env.CFLAGS = ['-std=c99', '-Wc++-compat']
    #gc.env.CFLAGS += ['-O3']
    gc.env.CFLAGS += ['-g']
    if sys.platform == 'win32':
        gc.env.COMMON_DEFS += ' WIN32'
    if sys.platform == 'darwin':
        gc.env.LIBPATH = '/usr/X11R6/lib'

def build(gc):

    gc.recurse('tinylib')
    if sys.platform == 'win32':
        libs = 'opengl32 gdi32 comdlg32 stdc++ gdiplus'
    else:
        libs = 'X11 GL stdc++'

    glob = gc.path.ant_glob
    
    headerFolders = glob(dir = True, src = False, excl = '.hg build waf* **/*.x11')
    
    gc.program(
        source = glob('*.c*'),
        includes = headerFolders,
        lib = libs,
        use = 'ecosystem',
        defines = gc.env.COMMON_DEFS,
        target = 'pez-viewer')

def path_list(paths, prefix):
    paths = paths.split(' ')
    return map(lambda x:prefix+x, paths)

if __name__ == "__main__":
    urllib.urlretrieve("http://bitbucket.org/prideout/pez-generator/raw/tip/generated/pez.h", "pez.h")
    urllib.urlretrieve("http://bitbucket.org/prideout/pez-generator/raw/tip/generated/pez.c", "pez.c")
    urllib.urlretrieve("http://waf.googlecode.com/svn/trunk/waflib/extras/parallel_debug.py", "parallel_debug.py")
    #urllib.urlretrieve("http://waf.googlecode.com/files/waf-1.6.2", "waf")
    #os.chmod('waf', stat.S_IEXEC)

c99test = '''
int main() {
    int i;
    i = 0;
    int j = 0;
    for (int k = 0; k < 3; ++k) {
        j += k;
    }
    return i+j;
}
'''