# build stage: build wheel + extract dependencies
FROM ghcr.io/astral-sh/uv:0.10.10-python3.14-trixie as build

ENV PIP_DEFAULT_TIMEOUT=100
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
ENV PIP_NO_CACHE_DIR=1

WORKDIR /app

COPY . ./

RUN uv export --no-dev --no-editable --no-emit-project --locked \
    --format requirements.txt -o requirements.txt
RUN uv build --wheel

# install stage: install gwcelery + dependencies
FROM python:3.14-trixie as install

ENV PIP_DEFAULT_TIMEOUT=100
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
ENV PIP_NO_CACHE_DIR=1

# install kerberos for ciecplib
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        libkrb5-dev && \
	rm -rf /var/lib/apt /var/lib/dpkg /var/lib/cache /var/lib/log

WORKDIR /app

COPY --from=build /app/requirements.txt /app
COPY --from=build /app/dist/*.whl /app

# create virtualenv
RUN python -m venv /opt/venv

# ensure virtualenv python is preferred
ENV PATH="/opt/venv/bin:$PATH"

RUN pip install --upgrade pip
RUN pip install -r requirements.txt
RUN pip install --no-deps *.whl

# final stage: installed app
FROM python:3.14-slim-trixie as app

COPY --from=install /opt/venv /opt/venv

# Install htgettoken and Kerberos for ciecplib.
ADD --chmod=0644 \
    https://hypatia.aei.mpg.de/debian/keys/hypatia-key.asc \
    /etc/apt/keyrings/hypatia-key.asc

RUN codename="$(. /etc/os-release && printf '%s' "$VERSION_CODENAME")" \
    && printf '%s\n' \
        "deb [signed-by=/etc/apt/keyrings/hypatia-key.asc] https://hypatia.aei.mpg.de/debian/ ${codename} lvk" \
        > /etc/apt/sources.list.d/lscdebian.list

RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        libkrb5-dev libssl-dev htgettoken krb5-user libgomp1 && \
	rm -rf /var/lib/apt /var/lib/dpkg /var/lib/cache /var/lib/log

# create app user
RUN groupadd --gid 1000 gwcelery && \
    useradd --uid 1000 --gid 1000 -m gwcelery

USER gwcelery

WORKDIR /home/gwcelery

# ensure virtualenv python is preferred
ENV PATH="/opt/venv/bin:$PATH"

# disable OpenMP, MKL, and OpenBLAS threading by default
# it will be enabled selectively by processes that use it
ENV OMP_NUM_THREADS=1
ENV MKL_NUM_THREADS=1
ENV OPENBLAS_NUM_THREADS=1

# web application configuration
ENV FLASK_RUN_PORT=5556
ENV FLASK_URL_PREFIX=/gwcelery
ENV FLOWER_PORT=5555
ENV FLOWER_URL_PREFIX=/flower

# set dev configuration by default
ENV CELERY_CONFIG_MODULE=gwcelery.conf.dev

ENTRYPOINT ["gwcelery"]
