cd src

# OpenBLAS does not build on 32bit Haswell. Upstream suggests to pass BINARY=32 to default to NEHALEM kernels
# See https://github.com/xianyi/OpenBLAS/issues/657
# Right now this affect all 32bit CPUs.
if [ `python -c "from __future__ import print_function; import platform; print(platform.architecture()[0])"` = "32bit" ]; then
    echo >&2 "Building a 32bit version of OpenBLAS."
    OPENBLAS_CONFIGURE="$OPENBLAS_CONFIGURE BINARY=32"
fi

if [ "x$SAGE_DEBUG" = "xyes" ]; then
    OPENBLAS_CONFIGURE="$OPENBLAS_CONFIGURE DEBUG=1"
fi

if [ "x$SAGE_FAT_BINARY" = "xyes" ]; then
    # See https://github.com/xianyi/OpenBLAS/issues/510
    OPENBLAS_CONFIGURE="$OPENBLAS_CONFIGURE TARGET=PRESCOTT"
fi

echo "Building OpenBLAS: $MAKE $OPENBLAS_CONFIGURE"

if ! (sdh_make libs netlib shared $OPENBLAS_CONFIGURE); then
    if [[ $OPENBLAS_CONFIGURE == *"TARGET"* ]]; then
        sdh_die "Error building OpenBLAS"
    else
        # The recommended TARGET is ATOM if CPU fails
        # See https://github.com/xianyi/OpenBLAS/issues/1204
        OPENBLAS_CONFIGURE="$OPENBLAS_CONFIGURE TARGET=ATOM"
        echo "Error building OpenBLAS"
        echo "Retrying building OpenBLAS: $MAKE $OPENBLAS_CONFIGURE"
        sdh_make libs netlib shared $OPENBLAS_CONFIGURE
    fi
fi

sdh_make_install PREFIX="$SAGE_LOCAL" NO_STATIC=1 $OPENBLAS_CONFIGURE
cd ..
./write_pc_file.py

# OpenBLAS's Makefile has a bug w.r.t. calling install_name_tool when
# DESTDIR is set.  It should *not* include the DESTDIR in the library's
# install_name; we set the correct install_name here
if [ "$UNAME" = "Darwin" ]; then
    cd "$SAGE_DESTDIR_LOCAL/lib"
    for dylib in lib*openblas*.dylib; do
        install_name_tool -id "$SAGE_LOCAL/lib/$dylib" "$dylib"
    done
fi
