# docker build --rm -t neuriplo-infer:ort -f Dockerfiles/Dockerfile.onnxruntime .

# Stage 1: Common dependencies
ARG UBUNTU_VERSION=24.04
FROM ubuntu:${UBUNTU_VERSION} AS common_dependencies

# Set environment variable to avoid interactive prompts
ENV DEBIAN_FRONTEND=noninteractive
ARG NEURIPLO_VERSIONS_URL=https://raw.githubusercontent.com/olibartfast/neuriplo/master/versions.env

# Install common dependencies
RUN apt-get update && apt-get install -y \
    cmake \
    build-essential \
    libopencv-dev \
    libgoogle-glog-dev\
    git \
    wget \
    && rm -rf /var/lib/apt/lists/*

RUN wget -q -O /tmp/versions.env "${NEURIPLO_VERSIONS_URL}"

# Stage 2: Install backend-specific C++ dependencies
FROM common_dependencies AS backend_dependencies

ENV HOME=/root
ARG BACKEND=ONNX_RUNTIME

RUN . /tmp/versions.env && \
    wget https://github.com/microsoft/onnxruntime/releases/download/v${ONNX_RUNTIME_VERSION}/onnxruntime-linux-x64-gpu-${ONNX_RUNTIME_VERSION}.tgz && \
    tar -xzvf onnxruntime-linux-x64-gpu-${ONNX_RUNTIME_VERSION}.tgz -C $HOME && \
    rm onnxruntime-linux-x64-gpu-${ONNX_RUNTIME_VERSION}.tgz

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

WORKDIR /app

COPY . .

# Build the project using CMake
RUN . /tmp/versions.env && \
    cmake -Bbuild -H. \
    -DDEFAULT_BACKEND=$BACKEND \
    -DORT_VERSION=${ONNX_RUNTIME_VERSION} \
    -DONNX_RUNTIME_DIR=$HOME/onnxruntime-linux-x64-gpu-${ONNX_RUNTIME_VERSION} \
    -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"]
