# This step will also change soon: The Oat UI CSS will need to be downloaded and bundled in.
FROM docker.io/denoland/deno:alpine AS style-client
COPY ./web/deno.lock ./web/package.json /app/
RUN cd /app/ && deno install
COPY ./web/ /app/
RUN mkdir -p /app/prepped && deno run -A npm:postcss-cli /app/app.css -o /app/prepped/lumina_client.css

FROM ghcr.io/gleam-lang/gleam:v1.15.2-erlang-alpine AS build-client
WORKDIR /app
COPY ./web/gleam.toml ./web/manifest.toml ./
RUN gleam deps download
COPY ./web/ ./
COPY --from=style-client /app/prepped/ /app/prepped/
RUN gleam build --target javascript
RUN find ./src/ -type f -print0 | xargs -0 sha256sum | sha256sum | awk '{print $1}' > "/app/prepped/lumina_client_rev.hash"
RUN mkdir -p "build/dev/javascript/dist" && mv prepped/* "build/dev/javascript/dist"

# This step will change drastically: It'll bundle the thin clients, OatUI js, and helper code, instead of the entire web frontend.
FROM docker.io/denoland/deno:alpine AS package-client
COPY --from=build-client /app/build/dev/javascript/ /build
WORKDIR /build
RUN echo 'import { main } from "./lumina_client.mjs";document.addEventListener("DOMContentLoaded", main)' > "/build/lumina_client/entry.mjs"
RUN deno bundle --platform browser --minify /build/lumina_client/entry.mjs  --output /build/dist/lumina_client.min.mjs && \
	deno bundle --platform browser /build/lumina_client/entry.mjs  --output /build/dist/lumina_client.mjs

FROM ghcr.io/gleam-lang/gleam:v1.15.2-erlang-alpine AS package-server
RUN apk add build-base
WORKDIR /app
COPY ./server/gleam.toml ./server/manifest.toml ./
COPY ./web/ ../web/
# RUN sed -i -e 's/path = \"\.\.\/\.\.\/\.\.\//path = \"..\//g' ./gleam.toml & \
#     sed -i -e 's/path = \"\.\.\/\.\.\/\.\.\//path = \"..\//g' ./manifest.toml
RUN gleam deps download
COPY ./server/ /app/
RUN --mount=type=cache,target=/app/build \
    gleam export erlang-shipment && \
    cp -r /app/build/erlang-shipment /app/shipment_final

FROM docker.io/library/erlang:28-alpine
RUN mkdir -p /data && chown 1000 /data

COPY --from=ghcr.io/amacneil/dbmate:latest /usr/local/bin/dbmate /usr/local/bin/dbmate
COPY ./db/migrations /app/migrations
COPY --from=package-client --chown=1000 /build/dist /app/lumina/priv/static
COPY --from=package-server --chown=1000 /app/shipment_final /app

WORKDIR /app

RUN apk add --no-cache \
    dumb-init

RUN echo '#!/bin/sh' > /app/entrypoint_.sh && \
    echo 'dbmate --url "sqlite:/data/instance.db" --migrations-dir "/app/migrations" up' >> /app/entrypoint_.sh && \
    echo '/app/entrypoint.sh run' >> /app/entrypoint_.sh && \
    chmod +x /app/entrypoint_.sh

USER 1000
VOLUME /data

# ENTRYPOINT ["/app/entrypoint_.sh"]
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
CMD ["/app/entrypoint_.sh"]
