# -- build

FROM ghcr.io/astral-sh/uv:python3.14-bookworm AS build

ARG SETUPTOOLS_SCM_PRETEND_VERSION

WORKDIR /code

COPY .git .git
COPY . ./

# Generate a wheel
RUN if [ -n "$SETUPTOOLS_SCM_PRETEND_VERSION" ]; then \
      export SETUPTOOLS_SCM_PRETEND_VERSION="$SETUPTOOLS_SCM_PRETEND_VERSION"; \
    fi \
    && uv build --wheel

# -- install

FROM ghcr.io/astral-sh/uv:python3.14-bookworm AS install

ENV VIRTUAL_ENV=/opt/gwdatafind-server

WORKDIR /code

# Generate the virtual environment
RUN uv venv ${VIRTUAL_ENV}

# Install the requirements
COPY pyproject.toml .
RUN uv pip install -r pyproject.toml

# Install the app
COPY --from=build /code/dist/*.whl /code
RUN WHEEL=$(ls /code/*.whl) \
    && uv pip install $WHEEL[credentials,gunicorn,pelican]

# -- application stage

FROM python:3.14-slim AS app

LABEL org.opencontainers.image.license="GPL-3.0-or-later"
LABEL org.opencontainers.image.title="GWDataFind Server - Python 3.14 (Debian)"
LABEL org.opencontainers.image.description="The GWDataFind data discovery server application"
LABEL org.opencontainers.image.source="https://git.ligo.org/computing/gwdatafind/server"
LABEL org.opencontainers.image.vendor="IGWN"
LABEL org.opencontainers.image.authors="Duncan Macleod <duncan.macleod@ligo.org>"
LABEL org.igwn.support="Best effort"

ENV VIRTUAL_ENV=/opt/gwdatafind-server
ENV PATH="${VIRTUAL_ENV}/bin:${PATH}"

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

# Install system packages needed for the application
#
# - libgssapi-krb5-2: Required for python-gssapi
#
RUN apt-get update -yqq \
    && apt-get install -yqq \
        libgssapi-krb5-2 \
    && rm -rf /var/lib/apt/lists/*

# Create application user
RUN apt-get update -yqq \
    && apt-get install -yqq adduser \
    && addgroup --system gwdatafind \
    && adduser --system --ingroup gwdatafind --home /var/lib/gwdatafind gwdatafind \
    && rm -rf /var/lib/apt/lists/*

# Create application directories
RUN mkdir -p /var/log/gwdatafind && chown gwdatafind:root /var/log/gwdatafind \
    && mkdir -p /var/run/gwdatafind && chown gwdatafind:root /var/run/gwdatafind

# Set the user to run the application
USER gwdatafind

# Set the working directory
WORKDIR /var/lib/gwdatafind

# Install the Gunicorn configuration
COPY config/gunicorn.conf.py /etc/gwdatafind/gunicorn.conf.py

# Install the GWDataFind server configuration file
COPY config/gwdatafind-server.toml /etc/gwdatafind/gwdatafind-server.toml

# Expose the server port
EXPOSE 8080

# Command to start the server
CMD ["python3", \
     "-m", "gunicorn", \
     "--bind=0.0.0.0:8080", \
     "--config=/etc/gwdatafind/gunicorn.conf.py", \
     "--forwarded-allow-ips=*", \
     "gwdatafind_server:create_app()"]
