FROM ros:jazzy-ros-base@sha256:2589a8fba5257307857890173c069852c2abf913a0be7970f172478baecb09e4

ARG GSEG3D_CORE_REVISION=116f510485ea5b4707e2b476958d34a5a067f647
ARG GSEG3D_ROS2_REVISION=5c5ba6f5ca0d682db2d59b2ad2f6a317ee938b95
ARG GROUND_CONSISTENCY_REVISION=41cec620efba6c370dccfc59a6ec1134775ff48a
ARG BUILD_JOBS=12

ENV DEBIAN_FRONTEND=noninteractive
SHELL ["/bin/bash", "-o", "pipefail", "-c"]

RUN apt-get update \
    && apt-get install --yes --no-install-recommends \
        build-essential \
        cmake \
        git \
        jq \
        libeigen3-dev \
        libgtest-dev \
        libnanoflann-dev \
        libpcl-dev \
        ninja-build \
        ros-jazzy-message-filters \
        ros-jazzy-nav2-costmap-2d \
        ros-jazzy-pcl-conversions \
        ros-jazzy-rclcpp-lifecycle \
        ros-jazzy-tf2-eigen \
        ros-jazzy-tf2-geometry-msgs \
        time \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /opt/m49/src

RUN git clone --filter=blob:none https://github.com/dfki-ric/ground_segmentation.git \
    && git -C ground_segmentation checkout --detach "${GSEG3D_CORE_REVISION}" \
    && git clone --filter=blob:none https://github.com/dfki-ric/ground_segmentation_ros2.git \
    && git -C ground_segmentation_ros2 checkout --detach "${GSEG3D_ROS2_REVISION}" \
    && git clone --filter=blob:none https://github.com/dfki-ric/nav2_ground_consistency_costmap_plugin.git \
    && git -C nav2_ground_consistency_costmap_plugin checkout --detach "${GROUND_CONSISTENCY_REVISION}"

RUN cmake -S /opt/m49/src/ground_segmentation \
        -B /opt/m49/core-build \
        -G Ninja \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_INSTALL_PREFIX=/opt/m49/core-install \
    && cmake --build /opt/m49/core-build --parallel "${BUILD_JOBS}" \
    && ctest --test-dir /opt/m49/core-build --output-on-failure \
    && cmake --install /opt/m49/core-build

RUN source /opt/ros/jazzy/setup.bash \
    && export CMAKE_PREFIX_PATH="/opt/m49/core-install:${CMAKE_PREFIX_PATH:-}" \
    && colcon build \
        --base-paths \
          /opt/m49/src/ground_segmentation_ros2 \
          /opt/m49/src/nav2_ground_consistency_costmap_plugin \
        --build-base /opt/m49/ros-build \
        --install-base /opt/m49/ros-install \
        --merge-install \
        --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON \
        --executor sequential \
        --event-handlers console_direct+

COPY qualify.sh /usr/local/bin/m49-gseg3d-qualify
RUN chmod 0755 /usr/local/bin/m49-gseg3d-qualify

ENTRYPOINT ["/usr/local/bin/m49-gseg3d-qualify"]
