#!/usr/bin/env bash

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


# Dependencies check
MPIR_VERSION=`cd $SAGE_ROOT/spkg/standard/; ./newest_version mpir`
if [ $? -ne 0 ]; then
    echo "Failed to find mpir.  Please install the mpir spkg"
    exit 1
fi

CDDLIB_VERSION=`cd $SAGE_ROOT/spkg/standard/; ./newest_version cddlib`
if [ $? -ne 0 ]; then
    echo "Failed to find cddlib.  Please install the cddlib spkg"
    exit 1
fi


# Patches to apply on top of the clean upstream source under src/.
patch() {

    # libtool-ized automake sources
    cp -p patches/Makefile.am              src/Makefile.am
    cp -p patches/src-Makefile.am          src/src/Makefile.am
    cp -p patches/src-reg-Makefile.am      src/src-reg/Makefile.am
    cp -p patches/lib-src-Makefile.am      src/lib-src/Makefile.am
    cp -p patches/lib-src-reg-Makefile.am  src/lib-src-reg/Makefile.am
    rm src/configure.in
    cp -p patches/configure.ac src/
    
    # Makefile.am with all examples deleted to save disk space
    cp -p patches/examples-Makefile.am     src/examples/Makefile.am

    # remaining files are the result of running autoconf/automake
    cp -rp patches/autogenerated/* src/
}

# sage-env sets RM which will break libtool
# See http://trac.sagemath.org/sage_trac/ticket/7818#comment:28
unset RM

# apply patches on top of pristine upstream release under src/
patch

cd src

./configure --prefix="$SAGE_LOCAL" --with-gmp="$SAGE_LOCAL" --with-cdd="$SAGE_LOCAL"
if [ $? -ne 0 ]; then
   echo "Error configuring TOPCOM."
   exit 1
fi

$MAKE
if [ $? -ne 0 ]; then
   echo "Error building TOPCOM."
   exit 1
fi

$MAKE install-strip
if [ $? -ne 0 ]; then
   echo "Error installing TOPCOM."
   exit 1
fi
