# Dockerfile
FROM greeng340or/rust-dev-ubuntu:latest AS builder

COPY . /workspace
WORKDIR /workspace

RUN apt-get update &&  \
    apt-get upgrade -y && \
    apt install -y \
    clang \
    libclang-dev \
    llvm-dev \
    python3 \
    python3-pip \
    curl \
    && curl -fsSL https://deb.nodesource.com/setup_lts.x | bash - \
    && apt-get install -y nodejs

# Use dynamic linking for proper library resolution
ENV RUSTFLAGS="-C target-feature=-crt-static"
# Limit parallel linker invocations to avoid OOM on memory-constrained builders
ENV CARGO_BUILD_JOBS=2
RUN make all

RUN if [ "$(uname -m)" = "x86_64" ]; then \
    cp target/x86_64-unknown-linux-gnu/debug/qrusty /usr/local/bin/qrusty; \
    elif [ "$(uname -m)" = "aarch64" ]; then \
    cp target/aarch64-unknown-linux-gnu/debug/qrusty /usr/local/bin/qrusty; \
    else \
    echo "Unsupported architecture" && exit 1; \
    fi

# Build webui in builder stage
RUN make build-webui

FROM ubuntu:latest

LABEL org.opencontainers.image.title="Qrusty"
LABEL org.opencontainers.image.description="A trusty priority queue server"
LABEL org.opencontainers.image.authors="greeng3@obscure-reference.com"
LABEL org.opencontainers.image.url="https://github.com/greeng340/qrusty"

# Install runtime dependencies for Python and Node.js integrations
RUN apt-get update && apt-get install -y \
    python3 \
    python3-pip \
    curl \
    ca-certificates \
    && curl -fsSL https://deb.nodesource.com/setup_lts.x | bash - \
    && apt-get install -y nodejs \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

COPY --from=builder /usr/local/bin/qrusty /usr/local/bin/qrusty
RUN chmod +x /usr/local/bin/qrusty

# Copy and install Python integration dependencies
COPY --from=builder /workspace/integrations/python/requirements.txt /tmp/requirements.txt
RUN pip3 install --break-system-packages -r /tmp/requirements.txt && rm /tmp/requirements.txt

# Copy integration examples for runtime use
COPY --from=builder /workspace/integrations /opt/qrusty/integrations

# Copy webui static files to final image
COPY --from=builder /workspace/static_webui /opt/qrusty/webui

RUN apt-get purge $(dpkg --list | egrep 'linux-image-[0-9]' | awk '{print $3,$2}' | sort -nr | tail -n +2 | grep -v $(uname -r) | awk '{ print $2}') && \
    apt-get autoremove -y; apt-get purge -y $(dpkg --list | grep '^rc' | awk '{print $2}') && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

RUN mkdir -p /data && \
    chown -R nobody:nogroup /data

VOLUME ["/data"]
EXPOSE 6784

ENTRYPOINT ["/usr/local/bin/qrusty"]
