# =============================================================================
# Belenios – Production Docker Image
# Source: https://github.com/glondu/belenios
#
# IMPORTANT BUILD NOTE:
#   opam-bootstrap.sh uses bubblewrap sandboxing which requires user namespaces.
#   Docker build disables namespaces by default, so we patch the bootstrap
#   script to pass --disable-sandboxing to opam init.
#
#   Build:
#     docker build --build-arg BELENIOS_VERSION=master -t belenios:latest .
# =============================================================================

# -----------------------------------------------------------------------------
# Stage 1: builder
# Installs all OCaml/OPAM deps and compiles Belenios from source.
# ~30 min / ~3.3 GB on first run – heavily cached on rebuilds.
# -----------------------------------------------------------------------------
FROM debian:12 AS builder

ARG BELENIOS_VERSION=master

ARG GITHUB_TOKEN
ARG BELENIOS_REPO=https://${GITHUB_TOKEN}@github.com/it-cusens/STV.git

ENV DEBIAN_FRONTEND=noninteractive
ENV BELENIOS_SYSROOT=/root/.belenios

# System build dependencies (from upstream INSTALL.md)
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
    bubblewrap \
    build-essential \
    ca-certificates \
    cracklib-runtime \
    git \
    jq \
    libgd-securityimage-perl \
    libgmp-dev \
    libncurses-dev \
    libsodium-dev \
    libsqlite3-dev \
    libssl-dev \
    m4 \
    npm \
    pkg-config \
    rsync \
    unzip \
    wget \
    zip \
    zlib1g-dev \
    && rm -rf /var/lib/apt/lists/*

# Clone at requested version
WORKDIR /src
RUN if [ "${BELENIOS_VERSION}" = "master" ]; then \
        git clone --depth 1 ${BELENIOS_REPO} belenios; \
    else \
        git clone --depth 1 --branch ${BELENIOS_VERSION} ${BELENIOS_REPO} belenios; \
    fi

WORKDIR /src/belenios

# Patch opam-bootstrap.sh: disable opam sandboxing (bubblewrap namespaces are
# blocked inside docker build). Fix documented in github.com/glondu/belenios/issues/35
RUN sed -i 's/opam init \(.*\)--bare/opam init \1--disable-sandboxing --bare/' opam-bootstrap.sh

# Bootstrap self-contained OCaml + OPAM + all OCaml library deps
RUN ./opam-bootstrap.sh

# Patch get_build.sh to skip git describe (no tags available in shallow clone).
# The script already supports BELENIOS_BUILD env var but dune resets the
# environment when invoking subprocesses, so we stub the script directly.
RUN printf '#!/bin/sh\necho "custom-build"\n' > src/platform/version/get_build.sh && \
    chmod +x src/platform/version/get_build.sh

# Build the release web server → output lands in _run/usr/
RUN . ${BELENIOS_SYSROOT}/env.sh && make build-release-server

# Create source tarball required by AGPL §13 (referenced in ocsigenserver.conf)
RUN tar czf belenios.tar.gz --exclude=.git --exclude=_build --exclude=_run \
    --warning=no-file-changed -C /src belenios || true

# -----------------------------------------------------------------------------
# Stage 2: runtime
# Minimal image – only compiled binaries + runtime shared libs.
# -----------------------------------------------------------------------------
FROM debian:12-slim AS runtime

ENV DEBIAN_FRONTEND=noninteractive

# CHANGED: added msmtp for SMTP mail sending (replaces missing /usr/lib/sendmail)
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
    ca-certificates \
    libgmp10 \
    libsodium23 \
    libsqlite3-0 \
    libssl3 \
    msmtp \
    netcat-openbsd \
    zlib1g \
    && rm -rf /var/lib/apt/lists/*

# Non-root service user
RUN groupadd --gid 1000 belenios && \
    useradd --uid 1000 --gid belenios --shell /bin/sh --create-home belenios

# CHANGED: symlink msmtp as sendmail so Belenios can invoke it
RUN ln -s /usr/bin/msmtp /usr/lib/sendmail

# Compiled server installation
COPY --from=builder /src/belenios/_run/usr          /opt/belenios/usr
COPY --from=builder /src/belenios/demo              /opt/belenios/demo
# AGPL source tarball (served at /static/source.tar.gz by ocsigenserver)
COPY --from=builder /src/belenios/belenios.tar.gz   /opt/belenios/belenios.tar.gz
# OCaml findlib + runtime libraries needed by belenios-server
COPY --from=builder /root/.belenios/opam/5.4.0/lib  /opt/belenios/ocaml/lib
COPY --from=builder /root/.belenios/opam/5.4.0/bin  /opt/belenios/ocaml/bin

# Runtime data dirs (spool, logs, uploads, lib/ocsidb)
RUN mkdir -p /data/spool /data/log /data/upload /data/lib /data/config && \
    chown -R belenios:belenios /data /opt/belenios

ENV PATH="/opt/belenios/usr/bin:${PATH}"
ENV OCAMLFIND_CONF=/opt/belenios/ocaml/lib/findlib.conf

COPY docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

USER belenios
WORKDIR /data

# ocsigenserver default port
EXPOSE 8001

HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD nc -z localhost 8001 || exit 1

ENTRYPOINT ["/entrypoint.sh"]
