#!/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 #19727)
cp "$SAGE_ROOT"/config/config.* config

# As config/acinclude.m4 is patched, we need to touch some files to prevent
# autotools to invoke black magic.
touch aclocal.m4 configure Makefile.in gf2x/gf2x-config.h.in

if [ "$SAGE_DEBUG" = "yes" ]; then
    echo "Building a debug version of gf2x."
    export CFLAGS="-O0 -g $CFLAGS"
elif $CC --version 2>/dev/null |grep 'gcc.* 5[.][12]' >/dev/null; then
    echo "Using compiler flags to work around problems with GCC 5.1/5.2 (Trac #18580,#18978)"
    export CFLAGS="-O2 -fno-forward-propagate -g $CFLAGS"
else
    export CFLAGS="-O2 -g $CFLAGS"
fi

if [ "$SAGE64" = "yes" ]; then
    echo "Building a 64-bit version of gf2x."
    export ABI=64
    CFLAGS="-m64 $CFLAGS"
fi

if [ "$SAGE_FAT_BINARY" = "yes" ]; then
    echo "Building a generic gf2x library."
    GF2X_CONFIGURE="--disable-hardware-specific-code $GF2X_CONFIGURE"
fi

echo "Configuring gf2x."
./configure --prefix="$SAGE_LOCAL" --libdir="$SAGE_LOCAL"/lib \
    $GF2X_CONFIGURE
if [ $? -ne 0 ]; then
    echo >&2 "Error: Failed to configure gf2x."
    exit 1
fi

echo "Building gf2x."
$MAKE
if [ $? -ne 0 ]; then
    echo >&2 "Error: Failed to build gf2x."
    exit 1
fi

case "$SAGE_TUNE_GF2X" in
    "full")
        echo "Complete tuning of gf2x."
        $MAKE tune-lowlevel && $MAKE tune-toom && $MAKE tune-fft
        if [ $? -ne 0 ]; then
            echo >&2 "Error: Failed to tune gf2x."
            exit 1
        fi
        ;;
    "no")
        echo "Skipping tuning of gf2x."
        echo "You can set SAGE_TUNE_GF2X to yes or full to turn it on."
        ;;
    *)
        echo "Fast tuning of gf2x."
        echo "You can set SAGE_TUNE_GF2X to full to run a complete tuning."
        $MAKE tune-lowlevel && $MAKE tune-toom TOOM_TUNING_LIMIT=100
        if [ $? -ne 0 ]; then
            echo >&2 "Error: Failed to tune gf2x."
            exit 1
        fi
        ;;
esac

echo "Deleting old gf2x files."
rm -f "$SAGE_LOCAL"/lib/libgf2x*
rm -rf "$SAGE_LOCAL"/include/gf2x*

echo "Installing gf2x."
$MAKE install
if [ $? -ne 0 ]; then
    echo >&2 "Error: Failed to install gf2x."
    exit 1
fi
