# syntax = docker/dockerfile:1

# Adjust BUN_VERSION as desired
ARG BUN_VERSION=1.1.2
FROM docker.io/oven/bun:${BUN_VERSION} as base

LABEL fly_launch_runtime="Bun"

WORKDIR /app

FROM base as install
RUN mkdir -p /temp/dev
COPY --link bun.lockb package.json /temp/dev/
RUN cd /temp/dev && bun install --frozen-lockfile

RUN mkdir -p /temp/prod
COPY --link bun.lockb package.json /temp/prod/
RUN cd /temp/prod && bun install --frozen-lockfile --production

FROM base as build
COPY --from=install /temp/dev/node_modules node_modules

# Copy application code
COPY --link config.toml config.toml
COPY --link src src
COPY --link bin bin
COPY --link content content
COPY --link templates templates
COPY --link static static

ENV NODE_ENV=production
RUN bun run bin/build.ts
RUN rm -fr node_modules
COPY --from=install /temp/prod/node_modules node_modules
RUN bun build src/index.ts --compile --minify --sourcemap --outfile server

FROM alpine:20240329 as postprocess

RUN echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories

RUN apk add --no-cache prettier@testing make fd brotli gzip zstd

WORKDIR /app

COPY --link Makefile ./
COPY --link config.toml ./
COPY --from=build /app/public public

RUN make format
RUN make -j4 compress

# Final stage for app image
FROM gcr.io/distroless/base-nossl

WORKDIR /app

# Copy built application
COPY config.toml /app/
COPY --from=build /app /app
COPY --from=postprocess /app/public /app/public

# Start the server by default, this can be overwritten at runtime
EXPOSE 3000
EXPOSE 9091

ENV NODE_ENV=production
CMD [ "/app/server" ]