#!/bin/bash

UBUNTU_VERSION=$(cut -f2 <<< $(lsb_release -r))
if [ "$UBUNTU_VERSION" != "24.04" ]; then
    echo "Unsupported version of Ubuntu"
    exit 1
fi

# Install ROS 2 Jazzy if not already installed
if [ -f /opt/ros/jazzy/setup.bash ]; then
    echo "ROS 2 Jazzy already installed... skipping installation"
else
    echo "Updating Ubuntu"
    sudo apt dist-upgrade -y
    sudo apt update
    sudo apt dist-upgrade -y

    echo "Installing ROS 2 Jazzy"
    sudo apt update && sudo apt install curl -y
    export ROS_APT_SOURCE_VERSION=$(curl -s https://api.github.com/repos/ros-infrastructure/ros-apt-source/releases/latest | grep -F "tag_name" | awk -F\" '{print $4}')
    curl -L -o /tmp/ros2-apt-source.deb "https://github.com/ros-infrastructure/ros-apt-source/releases/download/${ROS_APT_SOURCE_VERSION}/ros2-apt-source_${ROS_APT_SOURCE_VERSION}.$(. /etc/os-release && echo ${UBUNTU_CODENAME:-${VERSION_CODENAME}})_all.deb"
    sudo dpkg -i /tmp/ros2-apt-source.deb

    sudo apt update && sudo apt install -y ros-jazzy-desktop ros-dev-tools
    sudo rosdep init
    rosdep update
fi

if [ -z "$ROS_DISTRO" ]; then
    source $HOME/.bashrc
    if [ -z "$ROS_DISTRO" ]; then
        echo "ROS not sourced with .bashrc... Adding to bashrc"
        echo "source /opt/ros/jazzy/setup.bash" >> $HOME/.bashrc
        source /opt/ros/jazzy/setup.bash
    fi
fi

if [ -z "$ROS_DISTRO" ]; then
    echo "ROS_DISTRO is still not set... something went wrong"
    exit 1
fi

# Install GitHub CLI if not already installed
if command -v gh &> /dev/null; then
    echo "GitHub CLI (gh) already installed... skipping installation"
else
    echo "Installing GitHub CLI (gh)"
    sudo apt update && sudo apt install -y gh
fi

# Set up ROS helper scripts
if [ ! -d $HOME/ros2_helper_scripts ]; then
    cd $HOME
    git clone https://github.com/robustify/ros2_helper_scripts.git
    echo "export PATH=\$HOME/ros2_helper_scripts/:\$PATH" >> $HOME/.bashrc
    source $HOME/.bashrc
else
    echo "$HOME/ros2_helper_scripts already exists... skipping clone"
fi

# Set up ROS workspace
if [ ! -d $HOME/ros ]; then
    echo "Initializing ROS workspace"
    mkdir -p $HOME/ros/src

    cd $HOME/ros/src
    git clone https://github.com/mradov-ou/ece5532_gazebo.git
    git clone https://github.com/robustify/audibot.git -b gz_harmonic
    cd $HOME/ros
    rosdep install --from-paths src --ignore-src -r -y
    source /opt/ros/${ROS_DISTRO}/setup.bash
    $HOME/ros2_helper_scripts/release.bash
    echo "source $HOME/ros/install/setup.bash" >> $HOME/.bashrc
else
    echo "$HOME/ros already exists... skipping workspace initialization"
fi
