#!/usr/bin/env bash

###########################################
## Giac
###########################################


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

#############################################################
#    Environment Variables
#############################################################
# If CFLAGS and CXXFLAGS are unset, giac looks to set -g -O2, 
#   but if they are not empty, the -g -O2 is not added
CXXFLAGS="-g -O2 $CXXFLAGS"
CPPFLAGS="-I$SAGE_LOCAL/include $CPPFLAGS"
LDFLAGS="-L$SAGE_LOCAL/lib/ $LDFLAGS"



cd src

#############################################################
#   Patches
#############################################################

echo "Applying 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

# we have patched the configure.in for the lapack install of sage so we need to rebuilt some files.
aclocal
autoconf
automake --add-missing
libtoolize

#############################################################
#   configure
#############################################################
#
#    We use the option --disable-gui to be sure that the built won't stop because the gui tries
#    to be built with a bad version of fltk.
#
#    If you want to built the gui (xcas), you need fltk from the 1.3 branch. (Not 1.1 nor 2. ) 
#    and GL headers.
#


echo "Configuring giac..."

# If you experience problems after loading the cython interface: giacpy
# (Ex: next_prime(11**25) before and after loading giacpy) try the --disable-pari
# option.
#./configure --prefix="$SAGE_LOCAL" --disable-gui --disable-pari --disable-gmpxx
# solved? trying to enable pari again in libgiac.
./configure --prefix="$SAGE_LOCAL" --disable-gui --disable-gmpxx

if [ $? -ne 0 ]; then
    exit 1
fi

#############################################################
#   Build and Install
#############################################################

echo "Building  giac..."
$MAKE

if [ $? -ne 0 ]; then
    exit 1
fi

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


#############################################################
#   Build dir for the pexpect interface
#############################################################
# create the script_subdirectory for the pexpect giac interface by running a trivial instruction
sage -c "giac(1)"
if [ $? -ne 0 ]; then
    echo >&2 "Error running the pexpect interface of giac"
    exit 1
fi
#mkdir -p $SAGE_LOCAL_EXT/giac/user
