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

# 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

# Install common dependencies
RUN apt-get update && apt-get install -y \
    cmake \
    build-essential \
    curl \
    unzip \
    libopencv-dev \
    libgoogle-glog-dev \
    git \
    wget \
    python3 \
    python3-pip \
    python3-venv \
    && 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: Common backend environment
FROM common_dependencies AS backend_dependencies

ENV HOME=/root
ARG BACKEND=LIBTENSORFLOW
ENV TENSORFLOW_DIR=/root/dependencies/tensorflow
ENV LD_LIBRARY_PATH=${TENSORFLOW_DIR}/lib

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

ARG BACKEND=LIBTENSORFLOW

WORKDIR /app

COPY . .

RUN cp /tmp/versions.env /app/versions.neuriplo.env && \
    ./scripts/setup_dependencies.sh --backend tensorflow

# Build the project using CMake
RUN cmake -Bbuild -H. \
    -DDEFAULT_BACKEND=${BACKEND} \
    -DTENSORFLOW_DIR=${TENSORFLOW_DIR} \
    -DBUILD_INFERENCE_ENGINE_TESTS=OFF -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 TensorFlow runtime libraries installed during the builder stage.
COPY --from=builder /root/dependencies/tensorflow /root/dependencies/tensorflow

# 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:${TENSORFLOW_DIR}/lib

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