#!/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.
for patch in ../patches/*.patch; do
    [ -r "$patch" ] || continue  # Skip non-existing or non-readable patches
    patch -p1 <"$patch"
    if [ $? -ne 0 ]; then
        echo >&2 "Error applying '$patch'"
        exit 1
    fi
done

set -e

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

python "${CUR}"/lapack_conf.py

# 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 \
       --single-version-externally-managed \
       --record /dev/null \
       ${NUMPY_FCONFIG}

# Touch all includes such that dependency checking works properly:
# the timestamp of the includes should be *now*, not the time when
# the numpy package was created.
python <<EOF
import os
os.chdir(os.environ["SAGE_ROOT"])  # Import numpy from safe location
import numpy
os.chdir(numpy.get_include())
os.system("touch numpy/*")
EOF
