# syntax=docker/dockerfile:1
# mangabaka-seeder: the page, the userscript and the Bun server in one image.
# Configure with MBSEED_* environment variables (docs/ARCHITECTURE.md, "Running the server").

FROM oven/bun:1.3.14-slim AS build
WORKDIR /app
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
COPY tsconfig.json ./
COPY src ./src
COPY scripts ./scripts
RUN bun run build:web

FROM oven/bun:1.3.14-slim
ARG BUILD_VERSION=dev
ARG BUILD_REPOSITORY=https://gitea.lucaswinther.info/lucasw89/mangabaka-seeder
LABEL org.opencontainers.image.title="mangabaka-seeder" \
      org.opencontainers.image.description="Seed WEBTOON covers into MangaBaka cover edit requests" \
      org.opencontainers.image.source="${BUILD_REPOSITORY}" \
      org.opencontainers.image.revision="${BUILD_VERSION}"
WORKDIR /app
# No runtime dependencies: the server, the page and the userscript build need only Bun.
COPY --from=build /app/package.json ./
COPY --from=build /app/src ./src
COPY --from=build /app/scripts ./scripts
COPY --from=build /app/dist ./dist
# Storage is off unless MBSEED_STORAGE_DIR is set (with MBSEED_PUBLIC_URL); /data/covers is the conventional place.
RUN mkdir -p /data/covers && chown -R bun:bun /data /app/dist
ENV MBSEED_HOST=0.0.0.0 \
    MBSEED_PORT=8787 \
    MBSEED_ASSETS_DIR=/app/dist/web
USER bun
EXPOSE 8787
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
  CMD ["bun", "-e", "fetch('http://127.0.0.1:' + (process.env.MBSEED_PORT ?? 8787) + '/api/config').then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))"]
# The userscript is built at start so its @connect list includes MBSEED_PUBLIC_URL's host.
CMD ["sh", "-c", "bun run scripts/build-userscript.ts && exec bun run src/server/bun.ts"]
