#!/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"



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


#############################################################
#   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..."


#    --disable-gmpxx  (broken built)

./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 Giac."
    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

