# Copyright 2023 James Pace
# SPDX-License-Identifier: Apache-2.0
FROM docker.io/library/ros:rolling as base

# Set up common stuff needed in the builder and the
# deploy container.
ENV DEBIAN_FRONTEND noninteractive
RUN apt update -y && \
    apt upgrade -y && \
    rm -rf /var/lib/apt/lists/*

# Set up user.
# Touch file in home directory so we don't get bothered first call to sudo
RUN userdel -r ubuntu && \
    useradd -m -G sudo -s /bin/bash -u 1000 j7s && \
    bash -c 'echo "%sudo  ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers.d/container' && \
    chmod 0440 /etc/sudoers.d/container && \
    touch /home/j7s/.sudo_as_admin_successful

# Switch user.
USER j7s

# Set up rosdep
RUN rosdep update

# Compile as the builder.
FROM base AS builder

RUN mkdir -p /home/j7s/workspace/
COPY --chown=1000:1000 src/  /home/j7s/workspace/src
WORKDIR /home/j7s/workspace
RUN sudo apt update -y && \
    echo "set -ex" > deps.bash && \
    rosdep install --ignore-src --simulate --reinstall --default-yes --from-path src >> deps.bash && \
    bash deps.bash && \
    sudo rm -rf /var/lib/apt/lists/*
RUN . /opt/ros/$ROS_DISTRO/setup.sh && \
    colcon build

# Build deploy image.
FROM base AS deploy
COPY --from=builder /home/j7s/workspace/install /opt/j7s
COPY --from=builder /home/j7s/workspace/deps.bash /opt/j7s/deps.bash
RUN sudo apt update -y && \
    bash /opt/j7s/deps.bash && \
    sudo rm -rf /var/lib/apt/lists/*

# Setup entrypoint.
COPY ./docker/entrypoint.bash /entrypoint.bash
ENTRYPOINT ["/entrypoint.bash"]
CMD ["bash"]
