# Stage 1: Build stage with necessary build dependencies
FROM quay.io/fedora/python-312:latest AS build-stage
LABEL \
name="python-312-with-rust" \
vendor="Fedora Infrastructure" \
license="MIT"

USER root
# Add RPM-only modules and build dependencies
RUN dnf install -y \
    python3-pyrpmmd \
    python3-poetry \
    poetry \
    cargo \
    logrotate \
    git \
    gcc \
    gcc-c++ \
    libffi-devel \
    openssl-devel

# Clone MirrorManager2 source code from the Git repo
RUN mkdir -p /opt/mirrormanager2
WORKDIR /opt/mirrormanager2
RUN git clone https://github.com/fedora-infra/mirrormanager2.git .

RUN sed -e 's/signed_fpca/signed_rosca/' -i mirrormanager2/perms.py mirrormanager2/auth.py
RUN pip install --prefix=/install .

# Stage 2: Final stage with runtime dependencies
FROM quay.io/fedora/python-312:latest AS runtime
LABEL \
name="python-312-with-rust" \
vendor="Fedora Infrastructure" \
license="MIT"

USER root
# Add only runtime dependencies
RUN dnf install -y \
    python3-pyrpmmd \
    uwsgi \
    uwsgi-plugin-python3 \
    logrotate

# Copy installed dependencies from the build stage
COPY --from=build-stage /install /usr/

# Copy in the tree
#COPY --from=build-stage /opt/mirrormanager2 /opt/mirrormanager2
ADD run.py /opt/mirrormanager2/

FROM runtime AS database
COPY client_secrets.json /etc/mirrormanager/
COPY mirrormanager2.cfg /etc/mirrormanager/
ENV MM2_CONFIG=/etc/mirrormanager/mirrormanager2.cfg
RUN /usr/bin/python3 -m flask -A mirrormanager2.app db sync

FROM runtime as final
COPY --from=database /var/tmp/mirrormanager2_dev.sqlite /var/tmp/mirrormanager2_dev.sqlite

# Set working directory
WORKDIR /opt/mirrormanager2

# Expose necessary ports
EXPOSE 5000
COPY client_secrets.json /etc/mirrormanager/
COPY mirrormanager2.cfg /etc/mirrormanager/
ENV MM2_CONFIG=/etc/mirrormanager/mirrormanager2.cfg

COPY static/rocky /usr/lib/python3.12/site-packages/mirrormanager2/static/rocky
COPY templates/rocky /usr/lib/python3.12/site-packages/mirrormanager2/templates/rocky

# Define entrypoint script to start the application
CMD [ "uwsgi", "--socket", "0.0.0.0:5000", \
               "--uid", "uwsgi", \
               "--plugins", "python3", \
               "--protocol", "http", \
               "--enable-threads", \
               "--master", \
               "-b", "65535", \
               "--wsgi-file", "/opt/mirrormanager2/run.py" ]

