# The builder image, used to build the virtual environment
FROM python:3.11-buster as builder

RUN apt-get update && \
    apt-get install -y libkrb5-dev libsasl2-dev libldap2-dev libssl-dev && \
    rm -rf /var/lib/apt/lists/*

RUN pip install poetry==1.5.1

ENV POETRY_NO_INTERACTION=1 \
    POETRY_VIRTUALENVS_IN_PROJECT=1 \
    POETRY_VIRTUALENVS_CREATE=1 \
    POETRY_CACHE_DIR=/tmp/poetry_cache

WORKDIR /venv

COPY pyproject.toml ./
COPY poetry.lock ./
RUN touch README.md

RUN poetry install --no-root && \
    rm -rf $POETRY_CACHE_DIR

# The runtime image, used to just run the code provided its virtual environment
FROM python:3.11-slim-buster as runtime
RUN apt-get update && \
    apt-get install -y libldap2-dev krb5-user libxml2 --no-install-recommends && \
    rm -rf /var/lib/apt/lists/*

COPY krb5.conf /etc/krb5.conf

RUN useradd -rm app
USER app

ENV VIRTUAL_ENV=/venv/.venv \
    PATH="/venv/.venv/bin:$PATH"

COPY --from=builder ${VIRTUAL_ENV} ${VIRTUAL_ENV}

WORKDIR /app

COPY . .

STOPSIGNAL SIGINT

CMD ["uwsgi", "--socket=0.0.0.0:8000", "--protocol=http", "--manage-script-name", "--force-cwd=/app", "--mount", "/=webapp:app"]
