# gf2x builds fine without symlinks enabled, but enabling them confuses the mingw gcc
# (gf2x turns some of its headers into symlinks to other headers, which works
# fine when `ln -s` just copies the file to the new destination, but fails when it creates
# a symlink that is only understandable to MSYS-build software, which the compiler
# intentionally isn't)

# Unset MSYS to turn off symlinks so we don't run into that problem
unset MSYS

cd src

# Use newer version of config.guess and config.sub (see Issue #19727)
cp "$SAGE_ROOT"/config/config.* config

if [ "$SAGE_DEBUG" = "yes" ]; then
    echo "Building a debug version of gf2x."
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 (Issue #18580,#18978)"
    export CFLAGS="-fno-forward-propagate $CFLAGS"
fi

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

sdh_configure $GF2X_CONFIGURE
sdh_make

# The gf2x tuning code gets thrown off when building on Windows by the fact that executables
# have an exe extension (instead of having no extension like on other platforms) because it tries
# to find the source file corresponding to a binary by appending ".c" to the file name of the executable
# (so it ends up looking for filename.exe.c instead of filename.c)
# Avoid that by just disabling tuning on MSYS
if [ -n "$MSYSTEM" ]; then
    echo "Disabling tuning gf2x on MSYS"
    SAGE_TUNE_GF2X="no"
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
        if [ $? -ne 0 ]; then
            echo >&2 "Error: Failed to tune gf2x."
            exit 1
        fi
        ;;
esac

sdh_make_install
