#!/usr/bin/env bash

cd src

# workaround for incorrect permissions, see Trac #15742
chmod 755 install-sh

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

# Workaround for bugs with -D_FORTIFY_SOURCE=2 on antiques
export CPPFLAGS='-U_FORTIFY_SOURCE'

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

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

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

# pkgconf is an alternative to the "official" pkg-config, and does not
# automatically install a "pkg-config" binary.
rm -f "$SAGE_LOCAL/bin/pkg-config"   # delete old version
m4 ../patches/pkg-config.in > pkg-config.out
if [ $? -ne 0 ]; then
    echo >&2 "Error creating the pkg-config script."
    exit 1
fi
cp pkg-config.out "$SAGE_LOCAL/bin/pkg-config"
chmod 755 "$SAGE_LOCAL/bin/pkg-config"
