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

# Stage 1: Common dependencies
ARG UBUNTU_VERSION=22.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 \
    unzip \
    && 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=LIBTORCH
ARG Torch_DIR=$HOME/libtorch/share/cmake/Torch/
# Compute platform from pytorch.org, i.e. cu118, cu121, rocm6.0 or cpu
ARG COMPUTE_PLATFORM=cpu
RUN . /tmp/versions.env && \
    wget https://download.pytorch.org/libtorch/$COMPUTE_PLATFORM/libtorch-cxx11-abi-shared-with-deps-${PYTORCH_VERSION}%2B$COMPUTE_PLATFORM.zip && \
    unzip libtorch-cxx11-abi-shared-with-deps-${PYTORCH_VERSION}+$COMPUTE_PLATFORM.zip -d $HOME && \
    rm libtorch-cxx11-abi-shared-with-deps-${PYTORCH_VERSION}+$COMPUTE_PLATFORM.zip

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

WORKDIR /app

COPY . .

# Build the project using CMake
RUN cmake -Bbuild -H. -DDEFAULT_BACKEND=$BACKEND -DTorch_DIR=$Torch_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"]
