#!/usr/bin/env bash

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

rm -f "$SAGE_LOCAL/bin/sqlite3"

cd src

# Apply patches
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 #19711)
cp "$SAGE_ROOT"/config/config.* .


# Compile for 64-bit if SAGE64 is set to 'yes'
if [ "x$SAGE64" = "xyes" ] ; then
    CFLAGS="$CFLAGS -m64 "
fi


# Build with -O0 if debugging requested
if [ "$SAGE_DEBUG" = "yes" ]; then
    CFLAGS="-g -O0 $CFLAGS"
else
    CFLAGS="-g -O2 $CFLAGS"
fi

export CPPFLAGS="$CPPFLAGS -I$SAGE_LOCAL/include"
export CFLAGS

# Old OS X systems need -DSQLITE_WITHOUT_ZONEMALLOC
if uname -sr |grep 'Darwin [0-8][.]' >/dev/null; then
    export CPPFLAGS="$CPPFLAGS -DSQLITE_WITHOUT_ZONEMALLOC"
fi


# We need to explicitly add --enable-readline because of a bug in the
# configure script of SQLite 3.13.0:
# http://www.mail-archive.com/sqlite-users%40mailinglists.sqlite.org/msg08804.html
./configure --prefix="$SAGE_LOCAL" --enable-readline --libdir="$SAGE_LOCAL/lib"
if [ $? -ne 0 ]; then
    echo >&2 "Error configuring sqlite."
    exit 1
fi

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

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