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


# set LDFLAGS with proper flags to link against gmp/mpir and cddlib
LDFLAGS="-L$SAGE_LOCAL/lib -lcddgmp -lgmp -lm $LDFLAGS"

if [[ -z $CFLAG64 ]]; then
    CFLAG64=-m64
fi
if [[ -z $CXXFLAG64 ]]; then
    CXXFLAG64="$CFLAG64"
fi
if [[ "$SAGE64" = yes ]]; then
    echo "Building a 64-bit version of gfan."
    CFLAGS="$CFLAGS $CFLAG64"
    CXXFLAGS="$CXXFLAGS $CXXFLAG64"
    export CXXFLAG64 # Used in the patched Makefile.
    # TODO: It would be much better to (also) modify LDFLAGS here and use
    #       these instead in the Makefile when linking. (Cf. SPKG.txt.)
else
    unset CXXFLAG64 # Might come from the "global" environment.
fi

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

export CC CXX CFLAGS CXXFLAGS LDFLAGS

cd src

# Patch sources. Note that some patches (in the patches/src directory)
# have been applied to the source tarball.
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

echo "Now building gfan..."
# We don't use the makefile to install gfan so we don't need to set PREFIX
$MAKE CPPFLAGS="-I$SAGE_LOCAL/include"
if [[ $? -ne 0 ]]; then
    echo >&2 "Error building gfan."
    exit 1
fi

if [[ ! -f gfan ]]; then
    echo >&2 "Error: Build completed normally but gfan executable not found."
    exit 1
fi

echo "Removing old version of gfan (if any)..."
rm -f "$SAGE_LOCAL"/bin/gfan*


cp -pf gfan "$SAGE_LOCAL/bin/"
if [[ $? -ne 0 ]]; then
    echo >&2 "Error copying gfan executable."
    exit 1
fi

cd "$SAGE_LOCAL/bin/"
echo "Now running gfan to install links in '$SAGE_LOCAL/bin/'..."
./gfan installlinks
# XXX How about [just] checking $? here?
if [[ ! -f "$SAGE_LOCAL/bin/gfan_buchberger" ]]; then
    echo >&2 "Error: gfan links not created correctly."
    exit 1
fi
