#!/usr/bin/env bash

if [[ $(basename $(pwd)) != "src" ]] ; then
  echo This script must be run from the src folder
  exit
fi

for foo in $(find $(pwd) -name "package.xml") ; do
  package_name=$(basename $(realpath $(dirname $foo)))
  echo Entering package: $package_name
  cd $(realpath $(dirname $foo))
  if [[ -n $(grep -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
)
roslaunch_add_file_check(
$(find . -type f -name "*.launch")
)
endif()
EOT
    fi
  fi
done
