#!/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

for patch in ../patches/*.patch; do
    [ -r "$patch" ] || continue  # Skip non-existing or non-readable patches
    echo "Applying $patch"
    patch -p1 <"$patch"
    if [ $? -ne 0 ]; then
        echo >&2 "Error applying '$patch'"
        return 1
    fi
done

## The following *could* be put into Makefile.conf

# This is the place where arithmetic tables and some other input files are
# searched by default.
export MTXLIB="$DOT_SAGE/meataxe"
# Directory where executables are installed.
export MTXBIN="$SAGE_LOCAL/bin"
# Default compiler flags
export CFLAGS1="-std=gnu99 -O -Wall -fPIC"
# Field size up to GF(256)
export ZZZ=0

# In principle, one should uncomment for field sizes up to GF(2^16).
# But upstream doesn't provide the required sources.
#export ZZZ=1

# The following is just to make MeatAxe's Makefile happy
touch Makefile.conf

# We create a directory for the multiplication tables
mkdir -p $MTXLIB

if [ $? -ne 0 ]; then
    echo >&2 "Error creating directory for multiplication tables."
    exit 1
fi

## Install! Aparently MeatAxe would rebuild everything when
## testing, and "make check" also installs. So, if a test
## is requested then we do it in one go.

if [ "x$SAGE_CHECK" = xyes ]; then
    $MAKE check
else
    $MAKE
fi

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

## Surprisingly, MeatAxe's Makefile does NOT install the binaries
## in MTXBIN. Hence, we do it manually.

mv bin/* "$MTXBIN"
if [ $? -ne 0 ]; then
    echo >&2 "Error copying MeatAxe executables."
    exit 1
fi

# We move the meataxe library to a permanent location
mv tmp/libmtx.a "$SAGE_LOCAL/lib"
if [ $? -ne 0 ]; then
    echo >&2 "Error copying MeatAxe library."
    exit 1
fi

cp src/meataxe.h "$SAGE_LOCAL/include/"
if [ $? -ne 0 ]; then
    echo >&2 "Error copying MeatAxe header."
    exit 1
fi

# Are we supposed to install the documentation?
if [ "x$SAGE_SPKG_INSTALL_DOCS" = xyes ] ; then
    mkdir -p $SAGE_SHARE/doc/meataxe/
    cp -r doc/* $SAGE_SHARE/doc/meataxe/
    if [ $? -ne 0 ]; then
        echo "Error copying documentation."
        exit 1
    else
        echo "The documentation can be found in $SAGE_SHARE/doc/meataxe/"
    fi
fi
