#!/usr/bin/env bash

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

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

# If the environment variable SAGE64=yes, force building a 64-bit version:
if [ "x$SAGE64" = xyes ]; then
    echo "Building a 64-bit version of ppl"
    CC="$CC $CFLAG64"
    export CC
fi

# Make sure that we prefer Sage's mpir library over system-wide gmp/mpir installs
export CXXFLAGS="$CXXFLAGS -I$SAGE_LOCAL/include"

cd src

# Apply patch: patch out tests that
# * fail to compile on Solaris gcc 4.5.1
# * break when setting MAKE="make -jN"
# They cover code that is not exposed by the Cython wrapper
for patch in ../patches/*.patch; do
    [ -r "$patch" ] || continue
    patch -p1 <"$patch"
    if [ $? -ne 0 ]; then
        echo >&2 "Error applying '$patch'"
        exit 1
    fi
done

# Enable only what's needed for Sage
PPL_CONFIGURE="--enable-coefficients=mpz --disable-fpmath $PPL_CONFIGURE"

# First try configuring both the C and C++ interfaces.
# If that fails (for example, because of a broken version of m4),
# try to configure again with only the C++ interface, which is
# sufficient for Sage.  See #11391 and #12672.
./configure --prefix="$SAGE_LOCAL" --libdir="$SAGE_LOCAL/lib" \
    --with-gmp-include="$SAGE_LOCAL/include" \
    --with-gmp-lib="$SAGE_LOCAL/lib" \
    --enable-interfaces=c,c++ \
    $PPL_CONFIGURE
if [ $? -ne 0 ]; then
    echo >&2 "Error configuring PPL with both C and C++ interfaces, trying"
    echo >&2 "again with only the C++ interface."
    ./configure --prefix="$SAGE_LOCAL" --libdir="$SAGE_LOCAL/lib" \
        --with-gmp-include="$SAGE_LOCAL/include" \
        --with-gmp-lib="$SAGE_LOCAL/lib" \
        $PPL_CONFIGURE \
        --enable-interfaces=c++
    if [ $? -ne 0 ]; then
        echo >&2 "Error configuring the Parma Polyhedra Library."
        exit 1
    fi
fi

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

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