#!/usr/bin/env bash

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

cd src

# Apply patches.
for patch in ../patches/*.patch; do
    patch -p1 <"$patch"
    if [ $? -ne 0 ]; then
        echo >&2 "Error applying '$patch'"
        exit 1
    fi
done

# Normally for a 64-bit build the -m64 option is added to
# gcc, but other compilers will not accept that, so
# allow it to be configured as something different if need
# be.

if [ -z $CFLAG64 ] ; then
   CFLAG64=-m64
fi

if [ "x$SAGE64" = xyes ]; then
   echo "Building a 64 bit version of cvxopt"
   CFLAGS="$CFLAGS $CFLAG64"; export CFLAGS
   CC="$CC $CFLAG64" ; export CC
fi

# Ensure FreeBSD build finds new, local math.h and complex.h
if [ "$UNAME" = FreeBSD ]; then
    export CPPFLAGS="$CPPFLAGS -I$SAGE_LOCAL/include"
fi

$PIP_INSTALL .

if [ $? -ne 0 ]; then
    echo "Error building/installing cvxopt"
    exit 1
fi

if [ "x$SAGE_SPKG_INSTALL_DOCS" = xyes ] ; then
   cd doc
# This part would be used to build the documentation with sphinx.
# cvxopt would then have to depend on sphinx.
# in 1.1.5 the documentation is shipped already built and up to date.
#   ${MAKE} -B html
#   if [ $? -ne 0 ]; then
#      echo "Error building the documentation"
#      exit 1
#   fi
# checking to see if there is previously installed documentation.
   if [ -d $SAGE_LOCAL/share/doc/cvxopt/html ] ; then
      rm -rf $SAGE_LOCAL/share/doc/cvxopt/html
   fi
   mkdir -p $SAGE_LOCAL/share/doc/cvxopt/html
   cp -r html/* $SAGE_LOCAL/share/doc/cvxopt/html/
fi

