# Compile the launcher and collect Alpine/musl Postfix runtime dependencies.
FROM docker.io/library/alpine:3.24 AS build
RUN apk add --no-cache postfix postfix-pcre cyrus-sasl cyrus-sasl-login ca-certificates tzdata \
    go lddtreepax python3
COPY install/postfix-entrypoint.go /build/postfix-entrypoint.go
COPY tests/smoke.go /build/smoke.go
RUN go vet /build/postfix-entrypoint.go && go vet /build/smoke.go \
    && CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /usr/local/bin/postfix-entrypoint /build/postfix-entrypoint.go \
    && CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /build/smoke /build/smoke.go \
    && newaliases
COPY build/runtime-root.py /build/runtime-root.py
RUN python3 /build/runtime-root.py /runtime /usr/local/bin/postfix-entrypoint \
    /usr/libexec/postfix/master /usr/libexec/postfix/anvil /usr/libexec/postfix/bounce \
    /usr/libexec/postfix/cleanup /usr/libexec/postfix/discard /usr/libexec/postfix/error \
    /usr/libexec/postfix/flush /usr/libexec/postfix/local /usr/libexec/postfix/lmtp \
    /usr/libexec/postfix/pickup /usr/libexec/postfix/proxymap /usr/libexec/postfix/qmgr \
    /usr/libexec/postfix/scache /usr/libexec/postfix/showq /usr/libexec/postfix/smtp \
    /usr/libexec/postfix/smtpd /usr/libexec/postfix/tlsmgr /usr/libexec/postfix/trivial-rewrite \
    /usr/libexec/postfix/verify /usr/libexec/postfix/virtual /usr/libexec/postfix/postlogd \
    /usr/sbin/postalias /usr/sbin/postcat /usr/sbin/postconf /usr/sbin/postdrop \
    /usr/sbin/postkick /usr/sbin/postlock /usr/sbin/postlog /usr/sbin/postmap \
    /usr/sbin/postqueue /usr/sbin/postsuper /usr/sbin/sendmail

# Test in the exact shell-free filesystem; publication depends on this stage.
FROM scratch AS test
COPY --from=build /runtime/ /
ENV PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
RUN --mount=type=bind,from=build,source=/build/smoke,target=/ci-smoke ["/ci-smoke"]

# Export the pristine runtime, excluding smoke-test credentials, queues and logs.
FROM scratch
COPY --from=build /runtime/ /
COPY --from=test /tmp/smoke-passed /usr/share/postfix-build-check
LABEL org.opencontainers.image.source="https://git.k2patel.in/k2patel/docker-postfix" \
    org.opencontainers.image.description="Alpine/musl distroless Postfix SMTP relay" \
    org.opencontainers.image.licenses="MIT"
ENV PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
EXPOSE 25
VOLUME ["/var/spool/postfix"]
HEALTHCHECK --interval=30s --timeout=10s --retries=3 --start-period=40s \
    CMD ["/usr/local/bin/postfix-entrypoint", "--healthcheck"]
ENTRYPOINT ["/usr/local/bin/postfix-entrypoint"]
