#!/bin/sh
# Build script for mupdf 1.28.0 (plain uname-keyed GNU Makefile, bundled
# thirdparty). NOT Template A/B - mupdf ships its own Makerules that
# selects behavior off `$(OS)` (defaulting to `uname`, which reports
# "Hammerhead" - matches none of mupdf's Darwin/Linux/OpenBSD/wasm arms),
# so force OS=Linux explicitly to pick up the Linux-shaped defaults
# (HAVE_OBJCOPY, LIB_LDFLAGS -shared -Wl,-soname, etc.) which line up with
# our GNU-ld/binutils toolchain.
#
# Use the BUNDLED thirdparty/ (freetype, harfbuzz, jbig2dec, openjpeg,
# mujs, zlib-alt) rather than USE_SYSTEM_LIBS=yes - avoids a large,
# fragile dependency reconciliation against our own freetype/harfbuzz
# ports for a single consumer. Only the X11 viewer libs (libX11/libXext/
# libXrandr/libXcursor) come from the system via pkg-config.
#
# Old (pre-2015-idiom-heavy in thirdparty/) C - GCC 14 promotes implicit-
# decl/incompatible-pointer-type/int-conversion to hard errors by default;
# -fpermissive demotes them back to warnings, -fcommon undoes GCC10+'s
# -fno-common default (tentative-definition multiple-definition errors).
set -e

PORTDIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

cd "$SRCDIR"

for p in "$PORTDIR"/patches/*.patch; do
    [ -f "$p" ] || continue
    echo "==> Applying patch: $(basename "$p")"
    patch -p1 < "$p"
done

export PKG_CONFIG_PATH="$PREFIX/lib/pkgconfig:$PREFIX/share/pkgconfig:/usr/lib/pkgconfig:$PKG_CONFIG_PATH"

# Build only first (no install target) - DESTDIR must be a make ARG on the
# install step, never exported/used on a plain build, and never omitted -
# an install-apps run without DESTDIR would write straight into the live
# $PREFIX on the build host.
gmake -j${JOBS:-1} \
    OS=Linux \
    build=release \
    HAVE_X11=yes \
    HAVE_GLUT=no \
    HAVE_OBJCOPY=yes \
    prefix="$PREFIX" \
    XCFLAGS="-fpermissive -fcommon -D__EXTENSIONS__ -D_POSIX_PTHREAD_SEMANTICS" \
    apps libs

# install-apps installs mutool + the view apps (incl. mupdf-x11);
# install-libs additionally ships libmupdf + headers for any future consumer.
gmake \
    OS=Linux \
    build=release \
    HAVE_X11=yes \
    HAVE_GLUT=no \
    HAVE_OBJCOPY=yes \
    prefix="$PREFIX" \
    DESTDIR="$PKGDIR" \
    XCFLAGS="-fpermissive -fcommon -D__EXTENSIONS__ -D_POSIX_PTHREAD_SEMANTICS" \
    install-apps install-libs
