# syntax=docker/dockerfile:1

# ---------------------------------------------------------------- construction
FROM python:3.12-slim AS build

ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /build

# requirements.txt seul dans cette couche : tant qu'il ne change pas, la
# reinstallation des dependances est reprise du cache, meme si le code a bouge.
COPY requirements.txt ./
RUN --mount=type=cache,target=/root/.cache/pip \
    python -m venv /opt/venv \
 && /opt/venv/bin/pip install -r requirements.txt

# ------------------------------------------------------------------- execution
FROM python:3.12-slim AS runtime

ARG ENCLUME_VERSION=dev
ARG ENCLUME_COMMIT=inconnu
ARG BUILD_DATE=inconnue

LABEL org.opencontainers.image.title="Enclume" \
      org.opencontainers.image.description="Generateur de configuration CLAPI pour Centreon" \
      org.opencontainers.image.version="${ENCLUME_VERSION}" \
      org.opencontainers.image.revision="${ENCLUME_COMMIT}" \
      org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.licenses="MIT"

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PATH="/opt/venv/bin:$PATH" \
    ENCLUME_VERSION="${ENCLUME_VERSION}" \
    ENCLUME_COMMIT="${ENCLUME_COMMIT}" \
    ENCLUME_CATALOG=/app/catalog \
    GUNICORN_WORKERS=2 \
    GUNICORN_TIMEOUT=30

RUN groupadd --gid 10001 enclume \
 && useradd --uid 10001 --gid enclume --home /app --no-create-home --shell /usr/sbin/nologin enclume

COPY --from=build /opt/venv /opt/venv
WORKDIR /app
COPY --chown=root:root enclume/ /app/enclume/
COPY --chown=root:root catalog/ /app/catalog/
COPY --chown=root:root migrations/ /app/migrations/
COPY --chown=root:root alembic.ini /app/alembic.ini
COPY --chown=root:root docker/entrypoint-web.sh /usr/local/bin/entrypoint-web
RUN chmod +x /usr/local/bin/entrypoint-web

USER enclume
EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health', timeout=4).status==200 else 1)"

CMD ["/usr/local/bin/entrypoint-web"]
