#!/usr/bin/env bash

CUR=`pwd`

if [ -z "$SAGE_LOCAL" ]; then
   echo "SAGE_LOCAL undefined ... exiting"
   echo "Maybe run 'sage -sh'?"
   exit 1
fi

# Setting CFLAGS to have the option -m64 does not work for Numpy when
# making 64-bit builds on at least OS X and Solaris. Instead set CC
# to include the the -m64

if [ -z "$CFLAG64" ] ; then
   CFLAG64=-m64
fi

if [ "x$SAGE64" = xyes ] ; then
   CC="$CC $CFLAG64"
   export CC
fi

cd src

# Apply patches.
patches=""
if [ $UNAME = "CYGWIN" ]; then
    echo "CYGWIN: Patching numpy/linalg/setup.py"
    patches="$patches ../patches/cygwin-lapack_lite-setup.py.diff"
fi
for patch in $patches; do
    patch -p1 <"$patch"
    if [ $? -ne 0 ]; then
        echo >&2 "Error applying '$patch'"
        exit 1
    fi
done

echo "[DEFAULT]" > site.cfg
echo "library_dirs = $SAGE_LOCAL/lib" >> site.cfg
echo "include_dirs = $SAGE_LOCAL/include" >> site.cfg
echo "" >> site.cfg

if [ `uname` = "Darwin" ]; then
    unset ATLAS
    unset BLAS
    unset LAPACK
else
    export LDFLAGS="${LDFLAGS} -shared"
fi

# Make sure that the fortran objects are compiled with -fPIC
export FFLAGS="$FFLAGS -fPIC"
export FCFLAGS="$FCFLAGS -fPIC"

export NUMPY_FCONFIG="config_fc --noopt --noarch"

################################################

rm -rf "$SAGE_LOCAL"/lib/python/site-packages/numpy

# Program around a bug in SciPY's distutils.
unset CFLAGS

python setup.py install ${NUMPY_FCONFIG}

if [ $? -ne 0 ]; then
    echo "Error building numpy."
    exit 1
fi

