FROM osrf/ros:noetic-desktop-full

# Set up environment variables
ENV DEBIAN_FRONTEND=noninteractive
ENV CATKIN_WS=/root/catkin_ws_niryo
ENV DISPLAY=:0
ENV RESOLUTION=1920x1080

# Install core build dependencies and GUI/VNC tools
RUN apt-get update && apt-get install -y \
    python3-opencv python3-pip python3-rosdep python3-rosinstall \
    python3-rosinstall-generator python3-wstool build-essential sqlite3 \
    ffmpeg git supervisor xvfb x11vnc fluxbox novnc net-tools \
    && rm -rf /var/lib/apt/lists/*

# For noVNC index file
RUN ln -s /usr/share/novnc/vnc.html /usr/share/novnc/index.html

# Set up workspace
RUN mkdir -p $CATKIN_WS/src
WORKDIR $CATKIN_WS/src

# Clone Repositorty with sub modules
RUN git clone --recursive https://github.com/NiryoRobotics/ned_ros.git

# Create a symlink so the foxglove_bridge launch file is found where expected
RUN ln -s $CATKIN_WS/src/ned_ros/ros-foxglove-bridge/ros1_foxglove_bridge/launch $CATKIN_WS/src/ned_ros/ros-foxglove-bridge/launch

# Install workspace dependencies
WORKDIR $CATKIN_WS
RUN pip3 install -r ./src/ned_ros/requirements.txt
RUN rosdep update

# Install rosdep dependencies (ROS Control, MoveIt, Bridge)
RUN apt-get update && apt-get install -y \
    ros-noetic-ros-babel-fish ros-noetic-moveit-msgs ros-noetic-moveit \
    ros-noetic-rosbridge-server ros-noetic-tf2-web-republisher ros-noetic-ros-control \
    ros-noetic-ros-controllers ros-noetic-gazebo-ros-control ros-noetic-joint-state-controller \
    ros-noetic-effort-controllers ros-noetic-position-controllers ros-noetic-joint-trajectory-controller \
    ros-noetic-web-video-server \
    libwebsocketpp-dev nlohmann-json3-dev libasio-dev

# Build the packages
RUN /bin/bash -c "source /opt/ros/noetic/setup.bash && catkin_make"

# Setup bash environment for interactive session
RUN echo "source /opt/ros/noetic/setup.bash" >> /root/.bashrc
RUN echo "source $CATKIN_WS/devel/setup.bash" >> /root/.bashrc

# Ensure the .niryo directory exists for simulation data
RUN mkdir -p /root/.niryo/simulation

# Create launch file with explicit database filename to prevent sqlite3 errors
RUN echo '<launch>' > $CATKIN_WS/src/ned_ros/niryo_robot_bringup/launch/custom_simulation.launch && \
    echo '  <param name="/niryo_robot_database/database_path" value="/root/.niryo/simulation/niryo_programs.db" />' >> $CATKIN_WS/src/ned_ros/niryo_robot_bringup/launch/custom_simulation.launch && \
    echo '  <include file="$(find niryo_robot_bringup)/launch/desktop_gazebo_simulation.launch" />' >> $CATKIN_WS/src/ned_ros/niryo_robot_bringup/launch/custom_simulation.launch && \
    echo '</launch>' >> $CATKIN_WS/src/ned_ros/niryo_robot_bringup/launch/custom_simulation.launch

# Copy the local supervisor configuration file
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# Start Supervisord
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]