#!/usr/bin/env bash

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

CFLAGS="$CFLAGS -I$SAGE_LOCAL/include -g"

COMPILER=`testcc.sh $CC`

if [ "$COMPILER"  = "GCC" ] ; then
   CFLAGS="$CFLAGS -fPIC -Wall -pedantic"
elif [ "$COMPILER" = "Sun_Studio" ] ; then
   CFLAGS="$CFLAGS -Kpic"
elif [ "$COMPILER" = "HP_on_HP-UX" ] ; then
   CFLAGS="$CFLAGS + z"
fi

if [ "x$SAGE_DEBUG" = "xyes" ]; then
   CFLAGS="$CFLAGS -O0"
   ENABLE_DEBUG="--enable-debug"
else
   CFLAGS="$CFLAGS -O2"
   ENABLE_DEBUG=""
fi

if [ "x$SAGE64" = "xyes" ]; then
    CFLAGS="$CFLAGS -m64"
fi

export CFLAGS

if [ "x$SAGE_FAT_BINARY" = "xyes" ]; then
    DISABLE_SSE2="--disable-sse2"
else
    DISABLE_SSE2=""
fi

# otherwise we might run into problems with old headers
rm -rf "$SAGE_LOCAL/include/m4ri"


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

# Configure and build M4RI
./configure \
    --prefix="$SAGE_LOCAL" \
    --libdir="$SAGE_LOCAL/lib" \
    --enable-shared --disable-static \
    $ENABLE_DEBUG $DISABLE_SSE2
if [ $? -ne 0 ]; then
    echo "Error configuring m4ri"
    exit 1
fi

$MAKE
if [ $? -ne 0 ]; then
    echo "Error building m4ri"
    exit 1
fi

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