#!/usr/bin/env bash

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

#################################
# Set up environment variables: #
#################################

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 Givaro."
    CFLAGS="$CFLAGS $CFLAG64"
    CPPFLAGS="$CPPFLAGS $CFLAG64"
    CXXFLAGS="$CXXFLAGS $CXXFLAG64"
    LDFLAGS="$LDFLAGS $CFLAG64"
fi

# It shouldn't be necessary to add Sage's include directory here,
# since we configure with '--with-gmp=...'.
# Also, '-I...' should normally be added to (just) CPPFLAGS.
CFLAGS="$CFLAGS -fPIC -I\"$SAGE_LOCAL/include\""
CXXFLAGS="$CXXFLAGS -fPIC -I\"$SAGE_LOCAL/include\""

export CFLAGS CPPFLAGS CXXFLAGS LDFLAGS

cd src/

# Use newer version of config.guess and config.sub (see Trac #19728)
cp "$SAGE_ROOT"/config/config.* build-aux

./configure --prefix="$SAGE_LOCAL" --libdir="$SAGE_LOCAL/lib" --with-gmp="$SAGE_LOCAL/" --enable-shared

if [ $? -ne 0 ]; then
    echo >&2 "Error configuring givaro"
    exit 1
fi

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

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