FROM osrf/ros:jazzy-desktop-full
ARG USERNAME=USERNAME
ARG USER_UID=1000
ARG USER_GID=$USER_UID
ARG TARGETARCH

# Delete user if it exists in container (e.g Ubuntu Noble: ubuntu)
RUN if id -u $USER_UID ; then userdel `id -un $USER_UID` ; fi

# Create the user
RUN groupadd --gid $USER_GID $USERNAME \
    && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME \
    #
    # [Optional] Add sudo support. Omit if you don't need to install software after connecting.
    && apt-get update \
    && apt-get install -y --no-install-recommends sudo \
    && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \
    && chmod 0440 /etc/sudoers.d/$USERNAME \
    && rm -rf /var/lib/apt/lists/*

# Make sure the base image is completely up to date
RUN apt-get update \
    && apt-get upgrade -y \
    && rm -rf /var/lib/apt/lists/*


# C++ development tools
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
    build-essential \
    cmake \
    gdb \
    clang \
    clang-format \
    clang-tidy \
    libboost-all-dev \
    && rm -rf /var/lib/apt/lists/*

# Python development tools
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
    python3-pip \
    python3-dev \
    python3-argcomplete \
    python3-colcon-common-extensions \
    python3-colcon-mixin \
    python3-rosdep \
    python3-vcstool \
    && rm -rf /var/lib/apt/lists/*

# 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/*

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
    ros-${ROS_DISTRO}-rmw-cyclonedds-cpp \
    && rm -rf /var/lib/apt/lists/*


ENV SHELL=/bin/bash

# [Optional] Set the default user. Omit if you want to keep the default as root.
USER $USERNAME
CMD ["/bin/bash"]
