ARG DOCKER_REGISTRY=10.60.129.132:8890
ARG PYTHON_IMAGE=python:3.9.8
FROM ${DOCKER_REGISTRY}/${PYTHON_IMAGE} AS base

# Install poetry to manage dependencies
RUN pip install \
      --no-cache-dir \
      --trusted-host 10.60.129.132 \
      --index-url http://10.60.129.132/repository/PyPI/simple \
      --upgrade pip && \
    pip install \
      --no-cache-dir \
      --trusted-host 10.60.129.132 \
      --index-url http://10.60.129.132/repository/PyPI/simple \
      poetry==1.8.5

WORKDIR /

COPY pyproject.toml poetry.lock poetry.toml ./

# Install requirements inside the created virtualenv
RUN poetry install

# Copy SDK source
COPY ai-platform-sdk /tmp/ai-platform-sdk

# Install SDK into Poetry venv
RUN /.venv/bin/pip install \
    --no-cache-dir \
    --trusted-host 10.60.129.132 \
    --index-url http://10.60.129.132/repository/PyPI/simple \
    /tmp/ai-platform-sdk

# cleanup
RUN rm -rf /tmp/ai-platform-sdk

FROM ${DOCKER_REGISTRY}/${PYTHON_IMAGE}

# Run as a different user than root
ARG USER_ID=1000
ARG GROUP_ID=1000

RUN groupadd -r -g $GROUP_ID cmp_backend \
&& useradd --no-log-init -r -u $USER_ID -g $GROUP_ID cmp_backend

# ADD sources.list
RUN echo 'deb http://10.60.129.132/repository/debian-proxy/ bullseye main\ndeb http://10.60.129.132/repository/debian-security-proxy/ bullseye-security main\ndeb http://10.60.129.132/repository/debian-proxy/ bullseye-updates main' > /etc/apt/sources.list
# Install postgres client to run it inside docker-entrypoint
RUN apt-get update -y && \
    apt-get install -y --no-install-recommends postgresql-client gettext tini && \
    rm -rf /var/lib/apt/lists/*

# Some python configurations that works best with docker
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Change working directory
WORKDIR /app

# Switch to non-root user
USER cmp_backend:cmp_backend

# Copy virtualenv into the image
COPY --from=base --chown=cmp_backend:cmp_backend /.venv /.venv
ENV PATH="/.venv/bin:${PATH}"

# Copy code into the image
COPY --chown=cmp_backend:cmp_backend ./docker-entrypoint.sh ./docker-entrypoint.sh
COPY --chown=cmp_backend:cmp_backend ./uwsgi.ini ./uwsgi.ini
COPY --chown=cmp_backend:cmp_backend ./backend ./backend

# WSGI server runs on port 8000
EXPOSE 8000

# Configurable UWSGI options
# These variables should be substituted with suitable values
# on different environments
ENV UWSGI_PROCESSES=4 \
    UWSGI_THREADS=8 \
    UWSGI_MAX_REQUESTS=1000 \
    UWSGI_RELOAD_ON_RSS=320 \
    UWSGI_EVIL_RELOAD_ON_RSS=352 \
    UWSGI_MODULE=backend.wsgi \
    UWSGI_CHDIR=/app/backend \
    UWSGI_STATIC_MAP="/static/=/app/backend/static/" \
    UWSGI_STATIC_EXPIRES_URI="/static/.*\.[a-f0-9]{12,}\.(css|js|png|jpg|jpeg|gif|ico|woff|ttf|otf|svg|scss|map|txt) 315360000"

# Entrypoint for the django application
ENTRYPOINT ["/app/docker-entrypoint.sh"]

# Run the WSGI server
CMD ["uwsgi", "uwsgi.ini"]
