#!/usr/bin/env bash

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

echo "Cleaning out old PolyBoRi and BRiAl installations"
rm -rf "$SAGE_LOCAL"/lib/python/site-packages/{polybori,brial}
rm -f "$SAGE_LOCAL"/lib/lib{polybori,brial}*
rm -rf "$SAGE_LOCAL"/include/polybori*
rm -rf "$SAGE_LOCAL"/share/polybori

cd src
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

# C++11 workaround https://trac.sagemath.org/ticket/20926
export CXXFLAGS="$CXXFLAGS -std=c++98"

./configure \
    --prefix="$SAGE_LOCAL" \
    --libdir="$SAGE_LOCAL/lib" \
    --enable-shared --disable-static
if [ $? -ne 0 ]; then
    echo "Error configuring BRiAl"
    exit 1
fi

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

$MAKE install -j1
if [ $? -ne 0 ]; then
    echo "Error installing BRiAl"
    exit 1
fi
