#!/usr/bin/env bash

# shellcheck disable=SC2044
for foo in $(find "$(pwd)" -name "package.xml") ; do
  package_name=$(basename "$(realpath "$(dirname "$foo")")")
  echo Entering package: "$package_name"
  cd "$(realpath "$(dirname "$foo")")" || exit
  if grep -q -i "roslaunch_add_file_check" CMakeLists.txt; then
    echo Package "$package_name" already has roslaunch_add_file_check - skipping
  else
    if [[ -n $(find . -type f -name "*.launch") ]] ; then
      echo Adding roslaunch_add_file_check to "$package_name"
cat <<EOT >> CMakeLists.txt

## WARNING: automatically generated code; can be (and probably is) very buggy
if(CATKIN_ENABLE_TESTING)
find_package(catkin REQUIRED COMPONENTS
roslaunch
)
EOT

## The roslaunch_add_file_check macro supports as parameter either a folder or a single launchfile
## Here we call the macro for each of the launchfiles in the package
  for launchfile in $(find . -type f -name "*.launch") ; do
cat <<EOT >> CMakeLists.txt
roslaunch_add_file_check(${launchfile})
EOT
  done

## Close if(CATKIN_ENABLE_TESTING)
cat <<EOT >> CMakeLists.txt
endif()
EOT

    fi
  fi
done