#!/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 fixes to upstream source
echo "Applying patches..."
for patch in ../patches/*.patch; do
    [ -r "$patch" ] || continue  # Skip non-existing or non-readable patches
    echo "Using $patch"
    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 #19713)
cp "$SAGE_ROOT"/config/config.* .

# The following prevents autotools to regenerate its files.
touch aclocal.m4 configure Makefile.in config.h.in

# Note: The following doesn't work with spaces in `$SAGE_LOCAL`, but we don't
#       support that anyway, since many upstream packages don't.
#       On the other hand, the only packages GLPK uses that Sage provides are
#       GMP/MPIR and zlib, so we should just use `--with-gmp="$SAGE_LOCAL"` and
#       `--with-zlib="$SAGE_LOCAL"` below (which is safe), and omit the fol-
#       lowing two lines. (TODO)
#
#       Turns out that (as of version 4.55)
#       1) GLPK unconditionally uses its own copy of zlib (cf. `SPKG.txt`),
#          and the `configure` option `--with-zlib` is no longer valid;
#       2) `configure` doesn't support specifying the location of the GMP
#          library to use; only `--with-gmp[=yes]` or `--with-gmp=no`
#          are valid options.  So we *have to* add Sage's include and
#          library directories to `CPPFLAGS` (done here) and `LDFLAGS`
#          (already the default):
CPPFLAGS="-I$SAGE_LOCAL/include $CPPFLAGS"

# Let the user set an environment variable CFLAG64 to indicate the flag
# for the C compiler to build 64-bit code. If not set, asssume it is -m64
# as that is what is used by both GCC and SunStudio, but -m64 is not used
# by IBM's compiler on AIX or HP's compiier on HP-UX
if [ -z "$CFLAG64" ] ; then
  CFLAG64=-m64 # -m64 is used by gcc and SunStudio.
fi

if [ "x$SAGE64" = xyes ] ; then
   echo "Building a 64-bit version of GLPK"
   CFLAGS="$CFLAG64 $CFLAGS"
   LDFLAGS="$CFLAG64 $LDFLAGS"
   CPPFLAGS="$CFLAG64 $CPPFLAGS"
   # Very rarly is it needed to add '-m64' to CPPFLAGS,
   # but potentially it can be.
fi

export CFLAGS LDFLAGS CPPFLAGS

./configure --prefix=$SAGE_LOCAL --libdir="$SAGE_LOCAL/lib" --with-gmp --disable-static
if [ $? -ne 0 ]; then
    echo >&2 "Error configuring GLPK."
    exit 1
fi

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

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