FROM docker.io/library/rust:1.85-slim-bookworm AS cargo

RUN apt-get update && apt-get install -y gcc-mingw-w64-x86-64

WORKDIR /usr/src/sort-machine/

RUN rustup target add x86_64-unknown-linux-musl
RUN rustup target add x86_64-pc-windows-gnu

COPY sort-machine/ ./sort-machine/
COPY sort-machine-cli/ ./sort-machine-cli/
COPY sort-machine-server/src/ ./sort-machine-server/src/
COPY sort-machine-server/Cargo.toml ./sort-machine-server/Cargo.toml
COPY Cargo.toml Cargo.lock ./

RUN cargo build --release --package sort-machine-server
RUN cargo build --release --bin sort-machine --target x86_64-unknown-linux-musl
RUN cargo build --release --bin sort-machine --target x86_64-pc-windows-gnu

FROM docker.io/library/node:22.6-bookworm-slim as node

RUN apt-get update && apt-get install -y imagemagick

WORKDIR /usr/src/sort-machine/

COPY sort-machine-server/web/ ./web/
COPY sort-machine-server/*.sh ./

RUN ./bundle-web.sh --minify
RUN ./create-icons.sh

FROM docker.io/library/debian:bookworm-slim as bundle

RUN apt-get update && apt-get install -y zip

WORKDIR /usr/src/sort-machine/

COPY . .
RUN zip -r sort-machine.zip *

WORKDIR /srv/sort-machine/www/

COPY --from=node /usr/src/sort-machine/dist/ .
COPY --from=cargo /usr/src/sort-machine/target/x86_64-unknown-linux-musl/release/sort-machine download/
COPY --from=cargo /usr/src/sort-machine/target/x86_64-pc-windows-gnu/release/sort-machine.exe download/
RUN cp /usr/src/sort-machine/sort-machine.zip download/

FROM docker.io/library/debian:bookworm-slim AS runtime

RUN useradd sort-machine
USER sort-machine
WORKDIR /srv/sort-machine

COPY --from=cargo /usr/src/sort-machine/target/release/sort-machine-server /usr/local/bin/
COPY --from=bundle /srv/sort-machine/www/ /srv/sort-machine/www/

ENV PORT=8000
ENV STATIC=/srv/sort-machine/www/
ENV CACHE_STATIC=true

EXPOSE ${PORT}

ENTRYPOINT [ "sort-machine-server" ]
