# Build and runtime stages for OpenDKIM on Ubuntu 16.04
FROM ubuntu:16.04 AS builder

ARG DEBIAN_FRONTEND=noninteractive
ARG OPENDKIM_VERSION=2.10.3
ARG OPENDKIM_TARBALL=opendkim-${OPENDKIM_VERSION}.tar.gz
ARG OPENDKIM_URL=https://downloads.sourceforge.net/project/opendkim/${OPENDKIM_TARBALL}

RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    ca-certificates \
    wget \
    tar \
    gzip \
    make \
    autoconf \
    automake \
    libtool \
    pkg-config \
    libssl-dev \
    libmilter-dev \
    libbsd-dev \
    zlib1g-dev \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /build

RUN wget -O ${OPENDKIM_TARBALL} ${OPENDKIM_URL} \
 && tar xzf ${OPENDKIM_TARBALL}

WORKDIR /build/opendkim-${OPENDKIM_VERSION}

# Basic build:
# - prefix /usr
# - config in /etc/opendkim
# - pid file under /run/opendkim
RUN ./configure \
    --prefix=/usr \
    --sysconfdir=/etc \
    --localstatedir=/var \
    --disable-shared \
    --enable-static

RUN make -j"$(nproc)"

# Install into staging root
RUN make DESTDIR=/opt/opendkim-dist install

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

# Pack staged install and copied libs as tarballs to avoid BuildKit COPY-to-/ issues
RUN cd /opt/opendkim-dist \
 && tar -cf /opt/opendkim-dist.tar .

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

# Final runtime image
FROM ubuntu:16.04

ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    ssl-cert \
    inetutils-syslogd \
 && rm -rf /var/lib/apt/lists/*

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

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

RUN groupadd -f opendkim \
 && (id -u opendkim >/dev/null 2>&1 || useradd -r -g opendkim -d /var/lib/opendkim -s /usr/sbin/nologin opendkim)

RUN mkdir -p \
    /etc/opendkim \
    /etc/opendkim/keys \
    /run/opendkim \
    /var/lib/opendkim \
 && chown -R opendkim:opendkim /etc/opendkim/keys /run/opendkim /var/lib/opendkim

RUN touch /etc/opendkim/KeyTable /etc/opendkim/SigningTable /etc/opendkim/TrustedHosts \
 && chown opendkim:opendkim /etc/opendkim/KeyTable /etc/opendkim/SigningTable /etc/opendkim/TrustedHosts

RUN touch /etc/rsyslog.d/stdout.conf && \
    mkdir -p /etc/rsyslog.d/ && \
	echo "*.*    /dev/stdout" > /etc/rsyslog.d/stdout.conf

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


EXPOSE 8891

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