# syntax=docker/dockerfile:1
#
# Builder
#
ARG NIX_SUBSTITUTERS=https://cache.nixos.org

FROM nixos/nix:2.31.3 AS builder

ARG NIX_SUBSTITUTERS
RUN tee -a /etc/nix/nix.conf <<EOF
extra-experimental-features = nix-command flakes
filter-syscalls = false
substituters = $NIX_SUBSTITUTERS
EOF

RUN cp "$(nix build nixpkgs#cacert --print-out-paths)/etc/ssl/certs/ca-bundle.crt" /tmp/ca-bundle.crt

COPY . /tmp/build
WORKDIR /tmp/build

RUN --mount=type=ssh GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" nix build '.#docker_env'

# Export the built closure to a folder
RUN mkdir /tmp/nix-store-closure
RUN cp -R $(nix-store -qR result/) /tmp/nix-store-closure

# Create a folder which will be copied to /tmp in the final image
RUN install -d -o root -g root -m 0777 will_be_tmp

# Create a folder which will be copied to /nginx in the final image
RUN install -d -o 1000 -g 1000 -m 0755 will_be_slash_nginx

#
# Runner
#

FROM scratch

WORKDIR /app

ENV PATH="$PATH:/app/bin"

COPY --chmod=0644 --chown=0:0 <<EOF /etc/group
root:x:0:root
web:x:1000:web
EOF

COPY --chmod=0644 --chown=0:0 <<EOF /etc/passwd
root:x:0:0:root:/root:/bin/sh
web:x:1000:1000::/home/web:/bin/sh
EOF

ENV SSL_CERT_FILE=/etc/ssl/certs/ca-bundle.crt
ENV NIX_SSL_CERT_FILE=/etc/ssl/certs/ca-bundle.crt
COPY --from=builder /tmp/ca-bundle.crt /etc/ssl/certs/ca-bundle.crt

COPY --from=builder /tmp/nix-store-closure /nix/store
COPY --from=builder /tmp/build/result /app
COPY --from=builder /tmp/build/will_be_tmp /tmp
COPY --from=builder /tmp/build/will_be_slash_nginx /nginx

EXPOSE 8080
CMD ["/app/nginx", "-c", "/app/nginx.conf", "-e", "stderr", "-g", "daemon off;"]
