# better-sqlite3 is a native module, so dependencies are compiled in a build stage
# and only the finished node_modules are carried into the runtime image.
FROM node:22-bookworm-slim AS deps
RUN apt-get update \
 && apt-get install -y --no-install-recommends python3 make g++ ca-certificates \
 && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY package.json ./
RUN npm install --omit=dev

FROM node:22-bookworm-slim
ENV NODE_ENV=production
RUN apt-get update \
 && apt-get install -y --no-install-recommends \
      openssl ca-certificates tini util-linux \
      # Fonts for the server-rendered badge, and brother_ql to drive the label printer.
      fonts-liberation python3 python3-pip \
 && pip3 install --break-system-packages --no-cache-dir "brother_ql==0.9.4" \
 && rm -rf /var/lib/apt/lists/*
WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY package.json ./
COPY src ./src
COPY public ./public
COPY scripts ./scripts
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh

RUN chmod +x /usr/local/bin/docker-entrypoint.sh \
 && mkdir -p /data/photos /data/certs \
 && chown -R node:node /data /app

# Starts as root only long enough to fix ownership of a bind-mounted /data,
# then the entrypoint drops to the node user before running anything.
VOLUME ["/data"]
EXPOSE 3000 3001

HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
  CMD node scripts/healthcheck.mjs

ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/docker-entrypoint.sh"]
CMD ["node", "src/server.js"]
