# This Dockerfile builds the pikepdf wheel
# Inputs:
#    - REPO - Docker repository to pull qpdf from
#    - QPDF_VERSION - The image qpdf version to copy .deb files from
#    - PIKEPDF_VERSION - Version of pikepdf to build wheel for

# Default to pulling from the main repo registry when manually building
ARG REPO="paperless-ngx/paperless-ngx"

ARG QPDF_VERSION
FROM ghcr.io/${REPO}/builder/qpdf:${QPDF_VERSION} as qpdf-builder

# This does nothing, except provide a name for a copy below

FROM python:3.9-slim-bullseye as main

LABEL org.opencontainers.image.description="A intermediate image with pikepdf wheel built"

ARG DEBIAN_FRONTEND=noninteractive
ARG PIKEPDF_VERSION
# These are not used, but will still bust the cache if one changes
# Otherwise, the main image will try to build thing (and fail)
ARG PILLOW_VERSION
ARG LXML_VERSION

ARG BUILD_PACKAGES="\
  build-essential \
  python3-dev \
  python3-pip \
  # qpdf requirement - https://github.com/qpdf/qpdf#crypto-providers
  libgnutls28-dev \
  # lxml requrements - https://lxml.de/installation.html
  libxml2-dev \
  libxslt1-dev \
  # Pillow requirements - https://pillow.readthedocs.io/en/stable/installation.html#external-libraries
  # JPEG functionality
  libjpeg62-turbo-dev \
  # conpressed PNG
  zlib1g-dev \
  # compressed TIFF
  libtiff-dev \
  # type related services
  libfreetype-dev \
  # color management
  liblcms2-dev \
  # WebP format
  libwebp-dev \
  # JPEG 2000
  libopenjp2-7-dev \
  # improved color quantization
  libimagequant-dev \
  # complex text layout support
  libraqm-dev"

WORKDIR /usr/src

COPY --from=qpdf-builder /usr/src/qpdf/*.deb ./

# As this is an base image for a multi-stage final image
# the added size of the install is basically irrelevant

RUN set -eux \
  && echo "Installing build tools" \
    && apt-get update --quiet \
    && apt-get install --yes --quiet --no-install-recommends ${BUILD_PACKAGES} \
  && echo "Installing qpdf" \
    && dpkg --install libqpdf29_*.deb \
    && dpkg --install libqpdf-dev_*.deb \
  && echo "Installing Python tools" \
    && python3 -m pip install --no-cache-dir --upgrade \
      pip \
      wheel \
      # https://pikepdf.readthedocs.io/en/latest/installation.html#requirements
      pybind11 \
  && echo "Building pikepdf wheel ${PIKEPDF_VERSION}" \
    && mkdir wheels \
    && python3 -m pip wheel \
      # Build the package at the required version
      pikepdf==${PIKEPDF_VERSION} \
      # Output the *.whl into this directory
      --wheel-dir wheels \
      # Do not use a binary packge for the package being built
      --no-binary=pikepdf \
      # Do use binary packages for dependencies
      --prefer-binary \
      # Don't cache build files
      --no-cache-dir \
    && ls -ahl wheels \
  && echo "Cleaning up image" \
    && apt-get -y purge ${BUILD_PACKAGES} \
    && apt-get -y autoremove --purge \
    && rm -rf /var/lib/apt/lists/*