#!/usr/bin/env bash

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

cd src/

###############################################################################
# Apply patches (if any):
###############################################################################

ls ../patches/*.patch &>/dev/null && \
for patch in ../patches/*.patch; do
    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 #19761)
cp "$SAGE_ROOT"/config/config.* build-aux

###############################################################################
# Set up environment variables:
###############################################################################

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

# Some systems have problems when parts of LinBox are compiled with
# the commentator enabled and other parts with the commentator
# disabled.  Therefore, disable it always.
export CPPFLAGS="$CPPFLAGS -DDISABLE_COMMENTATOR"

if [ "$SAGE64" = yes ]; then
    echo "Building a 64-bit version of LinBox."
    if [ -z "$CFLAG64" ]; then
        CFLAG64=-m64
    fi
    CFLAGS="$CFLAGS $CFLAG64"
    CXXFLAGS="$CXXFLAGS $CFLAG64"
    CPPFLAGS="$CPPFLAGS $CFLAG64"
    LDFLAGS="$LDFLAGS $CFLAG64"
fi

# C++11 workaround https://trac.sagemath.org/ticket/20926
CXXFLAGS="$CXXFLAGS -std=c++98"

###############################################################################
# Configure, build and install LinBox:
###############################################################################

./configure --prefix="$SAGE_LOCAL" --libdir="$SAGE_LOCAL/lib" \
            --with-default="$SAGE_LOCAL" \
            --enable-sage --enable-optimization --disable-static
if [ $? -ne 0 ]; then
    echo >&2 "Error configuring LinBox."
    exit 1
fi

$MAKE
if [ $? -ne 0 ]; then
    echo >&2 "Error building LinBox."
    exit 1
fi

$MAKE install
if [ $? -ne 0 ]; then
    echo >&2 "Error installing LinBox."
    exit 1
fi
