#!/usr/bin/env bash

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

system_curl=""

if [ "$UNAME" = "Darwin" ]; then
    system_curl="--system-curl"
    unset MACOSX_DEPLOYMENT_TARGET
fi

./bootstrap --prefix=$SAGE_LOCAL \
    --system-bzip2 \
    --system-zlib \
    $system_curl \
    -- \
    -DCMAKE_PREFIX_PATH=$SAGE_LOCAL \
    -DCMAKE_TESTS_CDASH_SERVER=NOTFOUND

if [ $? -ne 0 ]; then
    echo >&2 "Error configuring CMake."
    exit 1
fi

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