FROM nvidia/cuda:12.1.1-devel-ubuntu22.04

SHELL ["/bin/bash", "-c"]

# Install dependencies
RUN --mount=type=cache,target=/var/cache/apt \
    --mount=type=bind,source=docker/scripts/install-tools.sh,target=/tmp/install-tools.sh \
    bash /tmp/install-tools.sh
RUN --mount=type=cache,target=/var/cache/apt \
    --mount=type=bind,source=docker/scripts/install-ros2.sh,target=/tmp/install-ros2.sh \
    bash /tmp/install-ros2.sh
RUN --mount=type=cache,target=/var/cache/apt \
    --mount=type=bind,source=docker/scripts/install-clang.sh,target=/tmp/install-clang.sh \
    bash /tmp/install-clang.sh
RUN --mount=type=cache,target=/root/.cache/pip \
    --mount=type=bind,source=docker/scripts/install-python-requirements.sh,target=/tmp/install-python-requirements.sh \
    bash /tmp/install-python-requirements.sh
RUN --mount=type=cache,target=/var/cache/apt \
    --mount=type=bind,source=docker/scripts/install-3rdparty.sh,target=/tmp/install-3rdparty.sh \
    bash /tmp/install-3rdparty.sh

# Last installation layer as we update ROS dependencies often
RUN --mount=type=cache,target=/var/cache/apt \
    --mount=type=bind,source=.,target=/tmp/ros_ws \
    /tmp/ros_ws/docker/scripts/install-rosdep.sh

# Clean cache
RUN apt-get autoremove -y \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Create a non-root user
ARG USERNAME=dev
ARG USER_UID=1000
ARG USER_GID=$USER_UID
RUN groupadd --gid $USER_GID $USERNAME \
    && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME \
    && apt-get update \
    && apt-get install -y sudo \
    && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \
    && chmod 0440 /etc/sudoers.d/$USERNAME \
    && apt-get autoremove -y \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Create a workspace directory
RUN mkdir -p /workspace/go2-devcontainer/src/go2-devcontainer \
    && cd /workspace/go2-devcontainer \
    && chown -R $USERNAME:$USERNAME /workspace/go2-devcontainer/

RUN --mount=type=bind,source=docker/config/docker.bashrc,target=/tmp/docker.bashrc \
    cat /tmp/docker.bashrc >> /home/$USERNAME/.bashrc

# Clone unitree_ros2
RUN --mount=type=cache,target=/var/cache/apt \
    --mount=type=bind,source=docker/scripts/install-unitree-ros2.sh,target=/tmp/install-unitree-ros2.sh \
    bash /tmp/install-unitree-ros2.sh

# NVIDIA-related environment variables
ENV NVIDIA_VISIBLE_DEVICES \
    ${NVIDIA_VISIBLE_DEVICES:-all}
ENV NVIDIA_DRIVER_CAPABILITIES \
    ${NVIDIA_DRIVER_CAPABILITIES:+$NVIDIA_DRIVER_CAPABILITIES,}graphics

USER $USERNAME