if [ -z "$SAGE_LOCAL" ]; then
    echo >&2 "SAGE_LOCAL undefined ... exiting"
    echo >&2 "Maybe run 'sage --sh'?"
    exit 1
fi

# r uses grep output during its build
unset GREP_OPTIONS

# Make sure CPPFLAGS and LDFLAGS are set to something (even the empty
# string) to prevent R from overriding them. Note: LDFLAGS is set by default.
# The --with-readline configure option only understands yes/no
# and cannot be used to pass this path.
CPPFLAGS="$CPPFLAGS"

# Optimization flags
if [ "$SAGE_DEBUG" = yes ]; then
    CFLAGS="-g -O0 $CFLAGS"
    FCFLAGS="-g -O0 $FCFLAGS"
else
    CFLAGS="-g -O2 $CFLAGS"
    FCFLAGS="-g -O2 $FCFLAGS"
fi

export CFLAGS CPPFLAGS FCFLAGS LDFLAGS

if [ "$UNAME" = "Darwin" ]; then
   echo "Copying fake java and javac compiler on OS X"
   cp patches/java "$SAGE_LOCAL"/bin
   cp patches/javac "$SAGE_LOCAL"/bin
fi

# Note by Karl-Dieter Crisman, April 12th 2010. X support would be nice
# to have in OSX, but see
# http://CRAN.R-project.org/bin/macosx/RMacOSX-FAQ.html#X11-window-server-_0028optional_0029
# for how differently this would have to be handled on different OSX
# versions, none trivially.  In any case, aqua, which we enable,
# performs the same function on OSX.
#
# Also, see #12172: for now, anyway, we disable X support on OS X.
#
# Note by David Kirkby, Feb 16th 2010. /usr/include/X11/Xwindows.h does
# not exist on Solaris, but R configures OK with X support. Hence I've added
# a more specific test on Solaris, by testing for a library. That library
# exists both on Solaris 10 03/2005 (SPARC) and on OpenSolaris.
if [ "$UNAME" = "Darwin" ]; then
    XSUPPORT=no
elif [ -f /usr/include/X11/Xwindows.h ]; then
    XSUPPORT=yes
elif [ "$UNAME" = "SunOS" ] && [ -f /usr/X11/lib/libXv.so ] ; then
    XSUPPORT=yes
else
    XSUPPORT=no
fi

R_CONFIGURE_BLAS="--with-blas=$(pkg-config --libs blas)"
R_CONFIGURE_LAPACK="--with-lapack=$(pkg-config --libs lapack)"
echo "R_CONFIGURE_BLAS=$R_CONFIGURE_BLAS"
echo "R_CONFIGURE_LAPACK=$R_CONFIGURE_LAPACK"

if [ "$UNAME" = "Darwin" ]; then
    # We don't want to install R as a library framework on OSX
    R_CONFIGURE="--enable-R-framework=no $R_CONFIGURE"
    # OS X 10.10 and/or Xcode 6.3 and over broke the R installation. See
    # http://trac.sagemath.org/ticket/18254.
    if [ $MACOSX_VERSION -ge 14 ]; then
        echo "OS X 10.$[$MACOSX_VERSION-4] Configuring R without aqua support."
        R_CONFIGURE="--with-aqua=no $R_CONFIGURE"
    fi
    if [ $MACOSX_VERSION -ge 16 ]; then
        echo "OS X 10.$[$MACOSX_VERSION-4] Building with clang."
        CC=clang
    fi
fi

if [ "$SAGE_FAT_BINARY" = yes ]; then
    echo "Disabling ICU, OpenMP for a binary build"
    R_CONFIGURE="--without-ICU --disable-openmp $R_CONFIGURE"
elif [ "$UNAME" = "SunOS" ]; then
    # Note by David Kirkby, 16th Feb 2010. Even after adding the iconv library
    # R would not build properly on Solaris 10, complaining of undefined symbols
    # uiter_setUTF8 and  ucol_strcollIter
    # After an email to r-help@r-project.org, Ei-ji Nakama (rim.nakama@gmail.com)
    # emailed me and said the option --without-ICU might help, which it did. I don't see
    # this option documented, but for now at least, it does allow R to build.

    echo "Disabling ICU on Solaris, using an undocumented option --without-ICU"
    echo "since the ICU library is not included on Solaris."
    R_CONFIGURE="--without-ICU $R_CONFIGURE"
fi

cd src

if [ "$UNAME" = "Darwin" ]; then
    # Fixing install_name(s)
    sed -i -e 's:\"-install_name :\"-install_name ${libdir}/R/lib/:' configure
    sed -i -e "/SHLIB_EXT/s/\.so/.dylib/" configure
fi

# Don't override R_HOME_DIR in local/bin/R while building R.
# See patches/R.sh.patch
export SAGE_BUILDING_R=yes


config()
{
    ./configure \
        --prefix="$SAGE_LOCAL" --libdir="$SAGE_LOCAL/lib" \
	--enable-R-shlib \
	--with-recommended-packages \
        --with-readline=yes \
        --with-x=$XSUPPORT \
        "$R_CONFIGURE_BLAS" \
        "$R_CONFIGURE_LAPACK" \
        $R_CONFIGURE
}

config
if [ $? -ne 0 ]; then
    echo "Configuring R without X11"
    XSUPPORT=no
    config
    if [ $? -ne 0 ]; then
        echo >&2 "Error configuring R."
        exit 1
    fi
fi

if [ "$UNAME" = "Darwin" ]; then
    # We have to move (i.e., hide) old installs of R when upgrading R in Sage on OS X.
    # Indeed Sage modifies DYLD_LIBRARY_PATH whereas R's build process
    # modifies DYLD_FALLBACK_LIBRARY_PATH, so that it is Sage's R and not the freshly
    # built one which will get loaded during the build process; in case the versions
    # differ, the build process might fail.
    # On systems using LD_LIBRARY_PATH, both Sage and R modify it and R wins,
    # so no problem should occur.
    if [ -d "$SAGE_LOCAL"/lib/R ]; then
        RINSTALL_MOVED=yes
        mv "$SAGE_LOCAL"/lib/R "$SAGE_LOCAL"/lib/R.old
    fi
fi

# Build R
$MAKE R
if [ $? -ne 0 ]; then
    echo >&2 "Error building R."
    if [ "$RINSTALL_MOVED" = yes ]; then
        mv "$SAGE_LOCAL"/lib/R.old "$SAGE_LOCAL"/lib/R
    fi
    exit 1
fi

# needed for help system
$MAKE vignettes
if [ $? -ne 0 ]; then
    echo >&2 "Error building vignettes."
    if [ "$RINSTALL_MOVED" = yes ]; then
        mv "$SAGE_LOCAL"/lib/R.old "$SAGE_LOCAL"/lib/R
    fi
    exit 1
fi

# Remove old install
rm -rf "$SAGE_LOCAL"/lib/r
rm -rf "$SAGE_LOCAL"/lib/R
rm -rf "$SAGE_LOCAL"/lib/R.old
rm -rf "$SAGE_LOCAL"/lib/libRblas.* "$SAGE_LOCAL"/lib/libRlapack.* "$SAGE_LOCAL"/lib/libR.*

# Install new version
$MAKE install
if [ $? -ne 0 ]; then
    echo >&2 "Error installing R."
    exit 1
fi

if [ "$UNAME" = "Darwin" ]; then
    echo "Removing fake java and javac compiler"
    rm -f "$SAGE_LOCAL"/bin/java
    rm -f "$SAGE_LOCAL"/bin/javac
fi
