FROM docker.io/library/rust:slim AS chef

RUN apt-get update && apt-get install -y musl-tools musl-dev
RUN update-ca-certificates
RUN rustup target add x86_64-unknown-linux-musl

RUN cargo install cargo-chef

WORKDIR /app

####################################################################################################
## Planner
####################################################################################################
FROM chef AS planner
WORKDIR /app
COPY ./Cargo.lock ./
COPY ./Cargo.toml ./
COPY ./src ./src
RUN cargo chef prepare --recipe-path recipe.json

####################################################################################################
## Builder
####################################################################################################
FROM chef AS builder

# Create appuser
ENV USER=website
ENV UID=10001

RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/nonexistent" \
    --shell "/sbin/nologin" \
    --no-create-home \
    --uid "${UID}" \
    "${USER}"

WORKDIR /app

COPY --from=planner /app/recipe.json ./

RUN cargo chef cook --target x86_64-unknown-linux-musl --release --no-default--features --recipe-path recipe.json

COPY ./Cargo.lock ./
COPY ./Cargo.toml ./

COPY ./src ./src

RUN cargo build --target x86_64-unknown-linux-musl --release --no-default--features

####################################################################################################
## Final image
####################################################################################################
FROM scratch

# Import from builder.
COPY --from=builder /etc/passwd /etc/passwd
COPY --from=builder /etc/group /etc/group

WORKDIR /app

# Copy our build
COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/website ./
COPY ./static ./static
COPY ./templates ./templates
COPY ./pages ./pages
COPY ./config.toml ./config.toml

EXPOSE 8080

# Use an unprivileged user.
USER website:website

ENV RUST_LOG="debug"
ENV TLX_WATCH="false"
ENV TLX_DRAFTS="false"
ENV TLX_LOG_FORMAT="json"

ENTRYPOINT ["/app/website"]