#!/usr/bin/env bash

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

cd src

echo "Applying patches..."
# Apply all patches
for patch in ../patches/*.patch; do
    [ -r "$patch" ] || continue  # Skip non-existing or non-readable patches
    echo "Applying $patch"
    patch -p1 <"$patch"
    if [ $? -ne 0 ]; then
        echo >&2 "Error applying '$patch'"
        exit 1
    fi
done

echo "Configuring..."
./configure --prefix="$SAGE_LOCAL" --disable-static --libdir="$SAGE_LOCAL/lib"
if [ $? -ne 0 ]; then
   echo >&2 "Error configuring cliquer"
   exit 1
fi

echo "Building and installing ..."
$MAKE install
if [ $? -ne 0 ]; then
    echo >&2 "Error installing cliquer"
    exit 1
fi
