#!/usr/bin/env python
# Requires Python 2.6 for the subprocess module

import subprocess
from os import chdir
from os.path import isfile
import sys

from util import status

from pbs import Command, make, git

import os

def check_llvm():
    try:
        llvm_path = './llvm/Release+Asserts'
        assert isfile(llvm_path+'/lib/ocaml/llvm.cma') # is llvm.cma there?
        llvm_config = Command(llvm_path+'/bin/llvm-config')
        ver = llvm_config('--version') # try calling llvm-config
        print ver
        assert '3.1' in ver
        return True
    except:
        return False


# Test for ocaml 3.12.*
status('Testing for OCaml 3.12.*')
from pbs import ocaml, ocamlbuild
ver = ocaml('-version')
print ver
assert '3.12' in ver
print '...OK!'

# Submodule update/init
# TODO: make --recursive optional
status('Checking out submodules')
git('submodule', 'update', '--init', '--recursive')

# TODO: make install in subdir, with docs
#        requires graphviz, doxygen; target ocamlbuild to alt dir?; make clean?
# Build llvm
if check_llvm():
    status('llvm appears to be present -- skipping')
else:
    chdir('llvm')
    configure = Command('./configure')
    llvm_cfg = ['--enable-assertions', '--enable-optimized', '--enable-targets=all']#, '--enable-docs', '--enable-doxygen']
    status('''Configuring llvm:
    %s''' % cfg_str)
    print configure(llvm_cfg)
    
    status('Building llvm')
    print make('-j12')
    
    chdir('docs')
    #check_call('make ocamldoc'.split(' '))
    # optional: check_call('make doxygen'.split(' '))
    chdir('../..')
    assert check_llvm()

# Test building 
chdir('src')
status('Test: building halide.cmxa')
print ocamlbuild('halide.cmxa')
chdir('..')

status('Building C++ bindings')
print make('-C', 'cpp_bindings')

@@ -214,16 +214,148 @@
 ort os%0A%0A
+from multiprocessing import cpu_count%0Amax_load = cpu_count() * 0.9%0A%0Aminimal = False%0Aif '--minimal' in sys.argv:%0A    minimal = True%0A%0A
 def chec
@@ -1029,16 +1029,148 @@
 sive')%0A%0A
+# TODO: always run make -C llvm, just to make sure it's up to date. Does configure cache its settings when a reconfigure is forced?%0A
 # TODO: 
@@ -1488,18 +1488,146 @@
 timized'
-, 
+%5D%0A    if minimal:%0A        llvm_cfg = llvm_cfg + %5B'--enable-targets=host,ptx,x86_64,arm'%5D%0A    else:%0A        llvm_cfg = llvm_cfg + %5B
 '--enabl
@@ -1644,10 +1644,8 @@
 all'
-%5D#
 , '-
@@ -1727,15 +1727,16 @@
 ' %25 
-cfg_str
+llvm_cfg
 )%0A  
@@ -1814,19 +1814,49 @@
 make('-j
-12'
+', '--load-average=%25f' %25 max_load
 )%0A    %0A 
@@ -1880,26 +1880,38 @@
     
-#check_call('
+if not minimal:%0A        
 make
- 
+('
 ocam
@@ -1915,27 +1915,54 @@
 camldoc'
-.split(' ')
+, '-j', '--load-average=%25f' %25 max_load
 )%0A    # 
@@ -2220,18 +2220,74 @@
 , 'cpp_bindings'
-)
+, '-j1') # can be flakey with first parallel build on SSD
 %0A

Add --minimal option to bootstrap