#!/usr/bin/env bash

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

# libpng needs to have no default options set for grep
unset GREP_OPTIONS

if [ "$SAGE64" = yes ]; then
    CFLAGS="$CFLAGS -m64 -fPIC -g"
    LDFLAGS="$LDFLAGS -m64"
else
    CFLAGS="$CFLAGS -fPIC -g"
fi

# Pick up Sage's zlib:
export CPPFLAGS="-I$SAGE_LOCAL/include $CPPFLAGS"

cd src

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

# Needed to generate a correct import library
if [ "$UNAME" = "CYGWIN" ]; then
    MAKE="$MAKE SYMBOL_PREFIX= "
fi

# Pick up patches
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

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

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

# On Darwin, the symbolic links libpng.* created by libpng12 may interfere
# with a system-wide libPng.dylib.
# This system-wide library is likely to be a different version and on top of
# that the symbols exported there are prefixed with "_cg" (for "Core Graphics"),
# so even if by chance the functionalities of the two libraries were interchangeable,
# libraries or applications looking for one and being presented the other won't
# find the symbols they expect.
# Note the uppercase "P" which could prevent this conflict; unfortunately, the
# default filesystem used by Apple is case-insensitive.
# Also note there would be no problem if the system-wide library was not looked
# for when Sage is being built or run, but that's not the case either;
# it is at least looked for by the "ImageIO" framework:
# - when Python is built with Mac OS extensions, fixed in #4008;
# - when Mercurial is built because it uses $EDITOR, cf. #4678;
# - when R is built and it finds -lpng, cf. #4409 and #11696.
# As not all of these problems are easily dealt with and new ones may arise,
# we chose to delete the $SAGE_LOCAL/lib/libpng.* symlinks on Darwin.
# Therefore, some package as matplotlib (cf. #11686) which by default looks for
# -lpng are patched to look for -lpng12 (unless pkg-config is installed; in
# this case indeed we can use a non-conflicting libpng.pc symlinking to
# libpng12.pc).
if [ "$UNAME" = "Darwin" ]; then
    echo "Deleting libpng.*..."
    rm -rf "$SAGE_LOCAL"/lib/libpng.*
    if [ $? -ne 0 ]; then
        echo >&2 "Error deleting symlinks."
        exit 1
    fi
fi
