FROM ros:jazzy

# Create the workspace and copy all source directories into it
WORKDIR /ros2_ws
ARG TARGETARCH

COPY src ./src/
COPY patches ./patches/
COPY upstream.jazzy.repos ./upstream.jazzy.repos

# Stage any dual ROS1/ROS2 packages (e.g. livox_ros_driver2) for ROS2 without
# modifying their upstream source: generate package.xml from package_ROS2.xml so
# colcon can discover them. The ROS2 build is selected via -DROS_EDITION below.
# RUN for d in $(find /ros2_ws/src -type f -name package_ROS2.xml -exec dirname {} \;); do \
#       cp -f "$d/package_ROS2.xml" "$d/package.xml"; \
#     done

# Import all upstream repostories
RUN vcs import ./src/upstream < ./upstream.jazzy.repos

# Fixup the livox package for ros2 build
RUN cd ./src/upstream/livox_ros_driver2 && \
    rm -rf launch package.xml && \
    ln -sfn launch_ROS2 launch && \
    ln -sfn package_ROS2.xml package.xml

RUN cd ./src/upsstream/FAST_LIO && \
    git submodule update --init

# Apply patches to upstream
# RUN ./patches/apply_patches.sh

# system deps from frozen rosdep manifest — no rosdep at build or startup
# NOTE: There should be a check in your CI that this file is up to date.
# Something like: 
#   ./scripts/freeze-rosdep.sh && git diff --exit-code rosdep-packages.txt
COPY rosdep-packages.txt /tmp/rosdep-packages.txt
# The --mount=type=cache option caches the apt packages with buildkit
# The id-apt-cache-${TARGETARCH} option allows for separate caches for different architectures
# this enables parallel builds for different architectures without cache conflicts
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,id=apt-cache-${TARGETARCH} \
    rm -f /etc/apt/apt.conf.d/docker-clean \
    && apt-get update \
    && xargs -r -a /tmp/rosdep-packages.txt apt-get install -y --no-install-recommends \
    && rm -rf /var/lib/apt/lists/*

# Install dependencies with rosdep
# This will catch anything that wasn't installed via .deb's from the frozen rosdep manifest.
RUN apt-get update && \
    rosdep update && \
    rosdep install --from-paths src --ignore-src -r -y && \
    rm -rf /var/lib/apt/lists/*

RUN cd src/upstream/livox_sdk && \
    mkdir -p build && \
    cd build && rm -rf * && \
    cmake .. -DCMAKE_BUILD_TYPE=Release && \
    make -j && \
    make install

# Build the workspace with symlink install
RUN . /opt/ros/jazzy/setup.sh && \
    colcon build --symlink-install \
    --cmake-args -DROS_EDITION=ROS2 -DDISTRO_ROS=jazzy

# Source the overlay on container startup
RUN echo "source /opt/ros/jazzy/setup.bash" >> /root/.bashrc && \
    echo "source /ros2_ws/install/setup.bash" >> /root/.bashrc

CMD ["bash"]
