FROM --platform=$BUILDPLATFORM alpine:3.23@sha256:fd791d74b68913cbb027c6546007b3f0d3bc45125f797758156952bc2d6daf40 AS downloader
RUN apk add --no-cache ca-certificates curl
COPY artifacts.sha256 download.sh /download/
ARG TARGETARCH
ARG PGPIPE_DOWNLOAD_BASE=https://www.pghorizon.com/downloads/pgpipe/v6.0.1
ENV PGPIPE_DOWNLOAD_BASE=$PGPIPE_DOWNLOAD_BASE

FROM downloader AS runtime-download
RUN --mount=type=cache,id=pgpipe-v6.0.1-runtime-${TARGETARCH},target=/download-cache,sharing=locked \
    --mount=type=secret,id=download_ca \
    sh /download/download.sh pgpipe "$TARGETARCH" /pgpipe

FROM downloader AS bootstrap-download
RUN --mount=type=cache,id=pgpipe-v6.0.1-bootstrap-${TARGETARCH},target=/download-cache,sharing=locked \
    --mount=type=secret,id=download_ca \
    sh /download/download.sh pgpipe-demo-bootstrap "$TARGETARCH" /pgpipe-demo-bootstrap

FROM postgres:16-alpine@sha256:57c72fd2a128e416c7fcc499958864df5301e940bca0a56f58fddf30ffc07777 AS database
COPY --chmod=0555 volume-guard.sh database-entrypoint.sh /usr/local/share/pgpipe-quickstart/
COPY --chmod=0555 database-ready.sh /docker-entrypoint-initdb.d/99-ready.sh
ENV PGDATA=/var/lib/postgresql/data/data
ENTRYPOINT ["/usr/local/share/pgpipe-quickstart/database-entrypoint.sh"]
CMD ["postgres"]

FROM database AS source
COPY source.sql /docker-entrypoint-initdb.d/10-source.sql

FROM database AS destination
COPY --from=bootstrap-download --chmod=0555 /pgpipe-demo-bootstrap /usr/local/bin/pgpipe-demo-bootstrap
COPY destination.sql /docker-entrypoint-initdb.d/10-destination.sql
COPY --chmod=0555 destination-bootstrap.sh /docker-entrypoint-initdb.d/20-protected-storage.sh

FROM alpine:3.23@sha256:fd791d74b68913cbb027c6546007b3f0d3bc45125f797758156952bc2d6daf40 AS config-init
COPY --chmod=0555 volume-guard.sh config-init.sh /setup/
COPY pgpipe.yaml /seed/pgpipe.yaml
ENTRYPOINT ["/setup/config-init.sh"]

# The default image contains no bootstrap helper or destination administrator binding.
FROM alpine:3.23@sha256:fd791d74b68913cbb027c6546007b3f0d3bc45125f797758156952bc2d6daf40 AS runtime
RUN apk add --no-cache ca-certificates tzdata && \
    addgroup -S -g 10001 pgpipe && \
    adduser -S -D -H -u 10001 -h /var/lib/pgpipe/data -s /sbin/nologin -G pgpipe pgpipe && \
    mkdir -p /etc/pgpipe /var/lib/pgpipe
COPY --from=runtime-download --chmod=0555 /pgpipe /usr/local/bin/pgpipe
LABEL org.opencontainers.image.title="pgpipe" org.opencontainers.image.version="6.0.1"
ENV GOMEMLIMIT=2GiB HOME=/var/lib/pgpipe/data PGPIPE_DEPLOYMENT=container
USER 10001:10001
WORKDIR /var/lib/pgpipe
EXPOSE 8080
HEALTHCHECK --interval=5s --timeout=5s --start-period=20s --retries=12 \
  CMD ["pgpipe", "healthcheck", "--config", "/etc/pgpipe/data/pgpipe.yaml", "--timeout", "3s"]
ENTRYPOINT ["pgpipe"]
CMD ["start", "--config", "/etc/pgpipe/data/pgpipe.yaml"]
