FROM node:22-bookworm-slim

LABEL org.opencontainers.image.description="ToolCTRL Website"

ARG APP_REVISION=local

ENV NODE_ENV=production \
    PORT=3000 \
    HOST=0.0.0.0 \
    DATA_DIR=/app/data \
    CLAMAV_HOST=127.0.0.1 \
    CLAMAV_PORT=3310 \
    CLAMAV_ENABLED=true \
    APP_REVISION=${APP_REVISION}

# Debian-Postinst soll keine Daemons im Build starten.
RUN echo 'exit 101' > /usr/sbin/policy-rc.d && chmod +x /usr/sbin/policy-rc.d

RUN apt-get update \
  && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
       ca-certificates curl tini gosu netcat-openbsd \
       clamav clamav-daemon clamav-freshclam \
  && rm -rf /var/lib/apt/lists/* /var/lib/clamav/* \
  && rm -f /usr/sbin/policy-rc.d \
  && groupadd --gid 1001 nodejs \
  && useradd --uid 1001 --gid nodejs --home-dir /app --shell /usr/sbin/nologin nodejs

# clamd: TCP 127.0.0.1:3310, DB-Verzeichnis auf der persistenten Volume,
# Example-Zeile entfernen, damit clamd/freshclam überhaupt starten.
RUN sed -i 's/^Example/#Example/' /etc/clamav/clamd.conf /etc/clamav/freshclam.conf \
  && sed -i 's|^DatabaseDirectory .*|DatabaseDirectory /app/data/clamav-db|' \
       /etc/clamav/clamd.conf /etc/clamav/freshclam.conf \
  && sed -i -e 's/^#\?TCPSocket .*/TCPSocket 3310/' \
            -e 's/^#\?TCPAddr .*/TCPAddr 127.0.0.1/' \
            /etc/clamav/clamd.conf \
  && (grep -q '^TCPSocket' /etc/clamav/clamd.conf || echo 'TCPSocket 3310' >> /etc/clamav/clamd.conf) \
  && (grep -q '^TCPAddr' /etc/clamav/clamd.conf || echo 'TCPAddr 127.0.0.1' >> /etc/clamav/clamd.conf) \
  && (grep -q '^DatabaseDirectory' /etc/clamav/clamd.conf || echo 'DatabaseDirectory /app/data/clamav-db' >> /etc/clamav/clamd.conf) \
  && (grep -q '^DatabaseDirectory' /etc/clamav/freshclam.conf || echo 'DatabaseDirectory /app/data/clamav-db' >> /etc/clamav/freshclam.conf)

WORKDIR /app

COPY --chown=nodejs:nodejs public ./public
COPY --chown=nodejs:nodejs server.js ./server.js
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

RUN mkdir -p /app/data \
  && chown -R nodejs:nodejs /app/data

EXPOSE 3000

# Lange Start-Periode: erster Container-Start lädt die Virendefinitionen
# (~300 MB, ~1–2 Min). Danach liegen sie auf der persistenten Volume und
# Folge-Starts sind in ~30 s wieder oben.
HEALTHCHECK --interval=30s --timeout=3s --start-period=900s --retries=3 \
  CMD curl -fsS http://127.0.0.1:3000/healthz >/dev/null || exit 1

ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["/entrypoint.sh"]
