"""Python script to build windows binaries to be fed to the "superpack".

The script is pretty dumb: it assumes python executables are installed the
standard way, and the location for blas/lapack/atlas is harcoded."""

# TODO:
#  - integrate the x86analysis script to check built binaries
#  - make the config configurable with a file
import sys
import subprocess
import os
import shutil

PYEXECS = {"2.5" : "C:\python25\python.exe",
        "2.4" : "C:\python24\python2.4.exe"}

_SSE3_CFG = r"""[atlas]
library_dirs = C:\local\lib\yop\sse3"""
_SSE2_CFG = r"""[atlas]
library_dirs = C:\local\lib\yop\sse2"""
_NOSSE_CFG = r"""[DEFAULT]
library_dirs = C:\local\lib\yop\nosse"""

SITECFG = {"sse2" : _SSE2_CFG, "sse3" : _SSE3_CFG, "nosse" : _NOSSE_CFG}

def get_python_exec(ver):
    """Return the executable of python for the given version."""
    # XXX Check that the file actually exists
    try:
        return PYEXECS[ver]
    except KeyError:
        raise ValueError("Version %s not supported/recognized" % ver)

def get_clean():
    if os.path.exists("build"):
        shutil.rmtree("build")
    if os.path.exists("dist"):
        shutil.rmtree("dist")

def write_site_cfg(arch):
    if os.path.exists("site.cfg"):
        os.remove("site.cfg")
    f = open("site.cfg", 'w')
    f.writelines(SITECFG[arch])
    f.close()

def build(arch, pyver):
    print "Building numpy binary for python %s, arch is %s" % (get_python_exec(pyver), arch)
    get_clean()
    write_site_cfg(arch)

    cmd = "%s setup.py build -c mingw32 bdist_wininst" % get_python_exec(pyver)
    build_log = "build-%s-%s.log" % (arch, pyver)
    f = open(build_log, 'w')

    try:
        try:
            subprocess.check_call(cmd, shell = True, stderr = subprocess.STDOUT, stdout = f)
        finally:
            f.close()
    except subprocess.CalledProcessError, e:
        msg = """
There was an error while executing the following command:

    %s

Error was : %s

Look at the build log (%s).""" % (cmd, str(e), build_log)
        raise Exception(msg)

    move_binary(arch, pyver)

def move_binary(arch, pyver):
    if not os.path.exists("binaries"):
        os.makedirs("binaries")

    shutil.move(os.path.join('dist', get_windist_exec(pyver)), 
            os.path.join("binaries", get_binary_name(arch)))

def get_numpy_version():
    import __builtin__
    __builtin__.__NUMPY_SETUP__ = True
    from numpy.version import version
    return version

def get_binary_name(arch):
    return "numpy-%s-%s.exe" % (get_numpy_version(), arch)

def get_windist_exec(pyver):
    """Return the name of the installer built by wininst command."""
    # Yeah, the name logic is harcoded in distutils. We have to reproduce it
    # here
    name = "numpy-%s.win32-py%s.exe" % (get_numpy_version(), pyver)
    return name

USAGE = """build.py ARCH PYTHON_VERSION

Example: build.py sse2 2.4."""

if __name__ == '__main__':
    if len(sys.argv) < 3:
        raise ValueError(USAGE)
        sys.exit(-1)

    arch = sys.argv[1]
    pyver = sys.argv[2]
    #build(arch, pyver)
    for arch in SITECFG.keys():
        build(arch, pyver)

@@ -392,16 +392,77 @@
  shutil%0D
+%0Afrom os.path import join as pjoin, split as psplit, dirname%0D
 %0A%0D%0APYEXE
@@ -2949,195 +2949,399 @@
 %0D%0A%0D%0A
-USAGE = %22%22%22build.py ARCH PYTHON_VERSION%0D%0A%0D%0AExample: build.py sse2 2.4.%22%22%22%0D%0A%0D%0Aif __name__ == '__main__':%0D%0A    if len(sys.argv) %3C 3:%0D%0A        raise ValueError(USAGE)%0D%0A        sys.exit(-1)%0D%0A
+if __name__ == '__main__':%0D%0A    from optparse import OptionParser%0D%0A    parser = OptionParser()%0D%0A    parser.add_option(%22-a%22, %22--arch%22, dest=%22arch%22, %0D%0A                      help = %22Architecture to build (sse2, sse3, nosse, etc...)%22)%0D%0A    parser.add_option(%22-p%22, %22--pyver%22, dest=%22pyver%22,%0D%0A                      help = %22Python version (2.4, 2.5, etc...)%22)%0D%0A%0D%0A    opts, args = parser.parse_args()
 %0D%0A  
@@ -3353,19 +3353,17 @@
 h = 
-sy
+opt
 s.ar
-gv%5B1%5D
+ch
 %0D%0A  
@@ -3376,26 +3376,110 @@
 r = 
-sys.argv%5B2%5D
+opts.pyver%0D%0A%0D%0A    if not arch:%0D%0A        arch = %22nosse%22%0D%0A    if not pyver:%0D%0A        pyver = %222.5%22
 %0D%0A    
-#
 buil
@@ -3498,16 +3498,17 @@
 r)%0D%0A    
+#
 for arch
@@ -3528,24 +3528,25 @@
 eys():%0D%0A    
+#
     build(ar

Use OptionParser for win32 build script.