#!/usr/bin/env bash
#
# Activate the ROS bash environment, either sourcing the current workspace
# devel setup or the base ROS environment setup script.  This cascades down
# ROS versions when a development environment does not exist.
#
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

DEVEL_SETUP="${SCRIPT_DIR}/devel/setup.bash"
INSTALL_SETUP="${SCRIPT_DIR}/install/setup.bash"
# Space-separated list of ROS versions in order of consideration.
# Newer versions of ROS should be listed before older versions.
ROS_VERSIONS="melodic kinetic indigo"

if [ -f "${DEVEL_SETUP}" ]
then
  echo "Sourcing workspace devel setup"
  . "${DEVEL_SETUP}"
elif [ -f "${INSTALL_SETUP}" ]
then
    echo "Sourcing workspace install setup."
    . "${INSTALL_SETUP}"
else
  for ROS_VERSION in ${ROS_VERSIONS}
  do
    VERSION_SETUP_PATH="/opt/ros/${ROS_VERSION}/setup.bash"
    if [ -f "${VERSION_SETUP_PATH}" ]
    then
      echo "Sourcing ROS setup version: ${ROS_VERSION}"
      . "${VERSION_SETUP_PATH}"
      # Break out after sourcing the found setup script
      break
    fi
    # No version setup script found. Report that.
    echo "ERROR: Found no ROS setup script for considered ROS versions: ${ROS_VERSIONS}"
  done
fi
