# Build stage
FROM ubuntu:24.04 AS builder

ARG DEBIAN_FRONTEND=noninteractive
ARG POSTFIX_VERSION=3.10.8
ARG POSTFIX_TARBALL=postfix-${POSTFIX_VERSION}.tar.gz
ARG POSTFIX_URL=https://high5.nl/mirrors/postfix-release/official/${POSTFIX_TARBALL}

RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    ca-certificates \
    wget \
    tar \
    gzip \
    make \
    perl \
    m4 \
    libc6-dev \
    libdb-dev \
    libssl-dev \
    libsasl2-dev \
    libpcre3-dev \
    libpam0g-dev \
    libssl-dev \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /build

RUN wget -O ${POSTFIX_TARBALL} ${POSTFIX_URL} \
 && tar xzf ${POSTFIX_TARBALL}

WORKDIR /build/postfix-${POSTFIX_VERSION}

RUN make makefiles \
    CCARGS='-I/usr/include/sasl -DNO_NIS -DHAS_PCRE -DUSE_SASL_AUTH -DUSE_TLS -DUSE_CYRUS_SASL -DHAS_PAM' \
    AUXLIBS='-lssl -lcrypto -ldb -lsasl2 -lpam -lpcre'

RUN make -j"$(nproc)"
RUN make non-interactive-package install_root=/opt/postfix-dist

# Copy runtime libraries needed by Postfix binaries
RUN mkdir -p /opt/postfix-libs \
 && find /opt/postfix-dist -type f -executable -exec ldd {} \; \
    | awk '/=> \// {print $3} /^\// {print $1}' \
    | sort -u \
    | xargs -r -I '{}' cp -v --parents '{}' /opt/postfix-libs

RUN cd /opt/postfix-dist \
 && tar -cf /opt/postfix-dist.tar .

RUN cd /opt/postfix-libs \
 && tar -cf /opt/postfix-libs.tar .

# Final image
FROM ubuntu:24.04

ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    libc6 \
    libdb5.3t64 \
    libssl3 \
    libsasl2-2 \
    libpcre3 \
    libpam0g \
    ssl-cert \
 && rm -rf /var/lib/apt/lists/*

COPY --from=builder /opt/postfix-dist.tar /tmp/postfix-dist.tar
COPY --from=builder /opt/postfix-libs.tar /tmp/postfix-libs.tar

RUN tar -C / -xf /tmp/postfix-dist.tar \
 && tar -C / -xf /tmp/postfix-libs.tar \
 && rm -f /tmp/postfix-dist.tar /tmp/postfix-libs.tar

# Create postfix user and group
RUN groupadd -r postfix \
 && groupadd -r postdrop \
 && useradd -r -g postfix -G postdrop -d /var/spool/postfix -s /usr/sbin/nologin postfix

# Create necessary directories with correct permissions
RUN mkdir -p \
    /var/spool/postfix \
    /var/lib/postfix \
    /var/mail \
    /etc/postfix

# Spool directory must be owned by root and have specific permissions for Postfix to function correctly
RUN chown root:root /var/spool/postfix \
 && chmod 755 /var/spool/postfix \
 && /usr/sbin/postfix set-permissions

COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

# Expose ports for LMTP (24), SMTP (25), SMTPS (465), and submission (587)
EXPOSE 24 25 465 587

ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
