#!/usr/bin/env bash

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

cd src

# Apply patches.  See SPKG.txt for information about what each patch
# does.
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

# Use newer version of config.guess and config.sub (see Trac #19757)
cp "$SAGE_ROOT"/config/config.* build-aux


export CFLAGS="-g -O2 -fPIC $CFLAGS"
export CXXFLAGS="-g -O2 -fPIC $CXXFLAGS"

if [ "$SAGE64" = "yes" ]; then
   echo "64 bit build"
   CFLAGS="-m64 $CFLAGS "; export CFLAGS
   CXXFLAGS="-m64 $CXXFLAGS "; export CXXFLAGS
   CPPFLAGS="-m64 $CPPFLAGS "; export CPPFLAGS
   LDFLAGS="-m64 $LDFLAGS"; export LDFLAGS
fi


if [ "$LINBOX_BLAS" != "" ]; then
    echo "Using environment variable LINBOX_BLAS=$LINBOX_BLAS"
elif [ $UNAME = "CYGWIN" ]; then
    # TODO: we should install a suitable blas.pc on Cygwin
    echo "Using system-wide Cygwin LAPACK BLAS."
    if [ ! -f "/usr/lib/libblas.a" ]; then
        echo "*************************************************"
        echo "*"
        echo "* On Cygwin you must install the standard LAPACK Cygwin package"
        echo "* via the Cygwin setup.exe program in the 'Math' category."
        echo "*"
        echo "*************************************************"
        exit 1
    fi
    LINBOX_BLAS="-lblas"
else
    LINBOX_BLAS="$(pkg-config --libs cblas)"
fi

echo "*************************************************"
echo " Using --with-blas=$LINBOX_BLAS"
echo "*************************************************"

./configure --prefix="$SAGE_LOCAL" --libdir="$SAGE_LOCAL/lib" \
    --with-default="$SAGE_LOCAL" \
    --with-blas="$LINBOX_BLAS" \
    --enable-optimization --disable-static
if [ $? -ne 0 ]; then
    echo "Error configuring fflas-ffpack"
    exit 1
fi

$MAKE
if [ $? -ne 0 ]; then
    echo "Error building fflas-ffpack"
fi

$MAKE install
if [ $? -ne 0 ]; then
    echo "Error installing fflas-ffpack"
    exit 1
fi
