#!/usr/bin/env bash

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

cd src

# It has been claimed that polymake is broken with paralle make, so disable it 
MAKE=make; export MAKE

# Find the latest gmp 
GMP=`cd $SAGE_ROOT/spkg/standard/; ./newest_version gmp`
echo "Using $GMP to build polymake"

# untar the spkg and move it to gmp-4.1.4 since that is what polymake expects - this is rather brain dead
tar xjf $SAGE_ROOT/spkg/standard/$GMP.spkg -C .
if [ $? -ne 0 ]; then
    echo "The gmp.spkg seems to be broken - installs from binaries require that you download the latest gmp.spkg"
    exit 1
fi
mv $GMP gmp-4.1.4

# Find the latest cddlib
CDDLIB=`cd $SAGE_ROOT/spkg/standard/; ./newest_version cddlib`
echo "Using $CDDLIB to build polymake"

# Sigh
tar xjf $SAGE_ROOT/spkg/standard/$CDDLIB.spkg -C .
if [ $? -ne 0 ]; then
    echo "The cddlib.spkg seems to be broken - installs from binaries require that you download the latest cddlib.spkg"
    exit 1
fi
mv $CDDLIB/src external/cdd

echo "" | make
if [ $? -ne 0 ]; then
    echo "Failed to configure."
    exit 1
fi

make install
if [ $? -ne 0 ]; then
    echo "Failed to build polymake"
    exit 1
fi

rm -f $SAGE_LOCAL/polymake/bin/polymake
cp polymake $SAGE_LOCAL/polymake/bin/


