#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# builder image
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# start from an existing image
FROM alpine AS builder

# run this command in the guest system (package installation)
RUN apk add --no-cache curl build-base linux-headers bison flex perl

# run this command in the guest system (source code download)
ARG PGV=18.4
RUN curl -L \
      https://ftp.postgresql.org/pub/source/v${PGV}/postgresql-${PGV}.tar.gz \
    | tar xz

# go to the working directory and execute every remaining command from it
WORKDIR /postgresql-${PGV}

# run this command in the guest system (program compilation)
RUN ./configure --prefix=/opt/postgres \
      --without-icu --without-readline --without-zlib --without-llvm \
      --without-tcl --without-perl --without-python --without-gssapi \
      --without-pam --without-bsd-auth --without-ldap --without-bonjour \
      --without-selinux --without-systemd --without-libedit-preferred \
      --without-liburing --without-libcurl --without-libnuma  \
      --without-libxml --without-libxslt --without-lz4 --without-zstd \
      --without-openssl \
      --disable-nls --disable-debug --disable-profiling --disable-coverage \
      --disable-dtrace --disable-tap-test --disable-injection-point \
      --disable-depend --disable-cassert \
 && make -j$(nproc) \
 && make install \
 && strip /opt/postgres/bin/* \
 && ( strip /opt/postgres/lib/*.so* || true )

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# final image
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# start from an existing image
FROM alpine

# run this command in the guest system (package installation)
RUN apk add --no-cache musl-locales

# copy the compiled programs from the builder image to the final image
COPY --from=builder /opt/postgres/bin/postgres \
                    /opt/postgres/bin/initdb \
                    /opt/postgres/bin/pg_ctl \
                    /opt/postgres/bin/psql \
     /usr/bin
COPY --from=builder /opt/postgres/lib/libpq.so.5 \
                    /opt/postgres/lib/dict_snowball.so \
                    /opt/postgres/lib/plpgsql.so \
     /usr/lib
COPY --from=builder /opt/postgres/share \
     /usr/share

# run this command in the guest system (user declaration)
RUN echo 'postgres:x:70:70::/var/lib/postgresql:/bin/sh' >>/etc/passwd \
 && echo 'postgres:x:70:' >>/etc/group \
 && echo 'postgres:!::0:::::' >>/etc/shadow

# create a working directory and execute every remaining command from it
WORKDIR /mini_postgres

# copy the specified file(s) from the host to the working directory
COPY mini_postgres.sh .

# run this command by default (from the working directory)
CMD ["/bin/sh", "mini_postgres.sh"]
