
# Stage 1: Cuda dependencies
ARG UBUNTU_VERSION=24.04
ARG NGC_CUDA_VERSION=13.0.0
FROM nvcr.io/nvidia/cuda:${NGC_CUDA_VERSION}-devel-ubuntu${UBUNTU_VERSION} AS cuda_dependencies

# Set environment variables
ENV DEBIAN_FRONTEND=noninteractive

# Install system dependencies with version pinning
RUN apt-get update && apt-get upgrade -y && \
    apt-get install -y \
    cmake=3.* \
    build-essential=12.* \
    libopencv-dev \
    libgoogle-glog-dev \
    wget \
    git \
    && rm -rf /var/lib/apt/lists/*

COPY VERSION /tmp/neuriplo-infer.VERSION

RUN dependency_ref=develop && \
    if grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' /tmp/neuriplo-infer.VERSION; then dependency_ref=master; fi && \
    wget -q -O /tmp/versions.env "https://raw.githubusercontent.com/olibartfast/neuriplo/${dependency_ref}/versions.env"

# Stage 2: Install TensorRT dependencies
FROM cuda_dependencies AS backend_dependencies

ARG BACKEND=TENSORRT

# Download and install TensorRT
RUN . /tmp/versions.env && \
    TRT_SHORT=$(echo ${TENSORRT_VERSION} | cut -d. -f1-3) && \
    wget --tries=3 --retry-connrefused \
    https://developer.nvidia.com/downloads/compute/machine-learning/tensorrt/${TRT_SHORT}/tars/TensorRT-${TENSORRT_VERSION}.Linux.x86_64-gnu.cuda-${CUDA_VERSION}.tar.gz \
    && tar -xzvf TensorRT-${TENSORRT_VERSION}.Linux.x86_64-gnu.cuda-${CUDA_VERSION}.tar.gz -C /opt \
    && rm TensorRT-${TENSORRT_VERSION}.Linux.x86_64-gnu.cuda-${CUDA_VERSION}.tar.gz \
    && ln -s /opt/TensorRT-${TENSORRT_VERSION} /opt/tensorrt

# Set TensorRT environment variables
ENV TENSORRT_DIR=/opt/tensorrt
ENV LD_LIBRARY_PATH=${TENSORRT_DIR}/lib:${LD_LIBRARY_PATH:-}
ENV LIBRARY_PATH=${TENSORRT_DIR}/lib:${LIBRARY_PATH:-}
ENV CPATH=${TENSORRT_DIR}/include
ENV PATH=${TENSORRT_DIR}/bin:${PATH}

# Stage 3: Copy application code and build
FROM backend_dependencies AS builder

ARG BACKEND=TENSORRT

WORKDIR /app

COPY . .

# Build the project using CMake
RUN . /tmp/versions.env && \
    cmake -Bbuild -H. \
    -DDEFAULT_BACKEND=${BACKEND} \
    -DTRT_VERSION=${TENSORRT_VERSION} \
    -DTENSORRT_DIR=${TENSORRT_DIR} \
    -DBUILD_TESTS=OFF && \
    cmake --build build --config Release

# Stage 4: Final image
FROM backend_dependencies AS final

WORKDIR /app

# Copy the executable
COPY --from=builder /app/build/app/neuriplo-infer /app/neuriplo-infer

# Copy the shared libraries
COPY --from=builder /app/build/_deps/neuriplo-build/libneuriplo.so /app/
COPY --from=builder /app/build/_deps/videocapture-build/libVideoCapture.so /app/

# Set the LD_LIBRARY_PATH to include the directory where the `.so` files are located
ENV LD_LIBRARY_PATH=/app:${LD_LIBRARY_PATH}

# Set the entry point to the compiled executable
ENTRYPOINT ["./neuriplo-infer"]
