# The hosted WeatherRouting (docs/online.md). Build context: the repository root, .git included (see docker-compose.yml).

# AGPL §13: the exact source this container runs, the committed files of HEAD only (`git archive`), in a folder named by
# version and commit. Without git the build fails: there is no fallback to the folder. Only the archive leaves this stage.
# On www the context is the pushed main (receive.denyCurrentBranch updateInstead), so HEAD is what the build stage builds.
FROM node:24-bookworm AS source
RUN command -v git >/dev/null || (apt-get update && apt-get install -y --no-install-recommends git && rm -rf /var/lib/apt/lists/*)
WORKDIR /src
COPY .git ./.git
RUN git config --global --add safe.directory /src \
 && commit=$(git rev-parse --short HEAD) \
 && version=$(git show HEAD:src/version.ts | sed -n 's/^export const VERSION = "\([0-9.]*\)".*/\1/p') \
 && test -n "$commit" && test -n "$version" \
 && git archive --format=tar.gz --prefix="WeatherRouting-$version-$commit-source/" -o /source.tar.gz HEAD

FROM node:24-bookworm AS build
WORKDIR /app
COPY . .
# .git came in with the context for the source stage: it goes at once, and only dist, node_modules, package.json and
# assets leave this stage.
RUN rm -rf .git
RUN npm ci
# The same name and content checks as a release's archive (tools/package/sourceArchive.ts).
COPY --from=source /source.tar.gz /tmp/source.tar.gz
RUN npx tsx tools/source-archive.ts check /tmp/source.tar.gz
RUN npm --prefix web ci
RUN npm run build
# The About window's Source code link (app/source.tar.gz).
RUN cp /tmp/source.tar.gz dist/public/source.tar.gz
RUN npm prune --omit=dev

FROM node:24-bookworm-slim
# openssh-client: the download relay; tini: reaps the relay's ssh processes and passes signals on.
RUN apt-get update && apt-get install -y --no-install-recommends openssh-client tini && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# What the friends package ships too: the build (without source maps), assets, production modules.
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/package.json ./package.json
COPY --from=build /app/assets ./assets
RUN find dist -name '*.map' -delete
ENV CONFIG_PATH=/config/config.json DATA_DIR=/data
USER node
EXPOSE 8090
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD node -e "fetch('http://127.0.0.1:8090/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
ENTRYPOINT ["tini","--"]
CMD ["node","dist/main.js"]
