#!/bin/bash
if [ $# != 1 ]; then
	echo -e "\e[93mPlease provide your desired project name as argument.\033[0m"
	exit 2
fi

name=$1
echo -e "Will initialize new behaviors repo \e[1m${name}_behaviors\033[0m ..."

echo ""
echo -e "\e[96m(1/4) Checking package dependencies...\033[0m"
#PACKAGES_TO_INSTALL="ros-${ROS_DISTRO}-rosbridge-server"
#echo "Require: $PACKAGES_TO_INSTALL" | sed -e "s/ /\n - /g"
#dpkg -s $PACKAGES_TO_INSTALL 2>/dev/null >/dev/null || sudo apt-get -y install $PACKAGES_TO_INSTALL
echo "Done"

echo ""
echo -e "\e[96m(2/4) Fetching project structure...\033[0m"
git clone https://github.com/pschillinger/flexbe_project_behaviors.git ${name}_behaviors
cd ${name}_behaviors
 # use new flexbe_app workspace layout, remove when merged into master
git fetch
git checkout feature/flexbe_app

echo ""
echo -e "\e[96m(3/4) Configuring project template...\033[0m"
sed -i -e "s/PROJECT_flexbe_states/${name}_flexbe_states/g" \
  PROJECT_flexbe_states/CMakeLists.txt \
  PROJECT_flexbe_states/package.xml \
  PROJECT_flexbe_states/setup.py
mv PROJECT_flexbe_states/src/PROJECT_flexbe_states PROJECT_flexbe_states/src/${name}_flexbe_states
mv PROJECT_flexbe_states ${name}_flexbe_states
sed -i -e "s/PROJECT_flexbe_behaviors/${name}_flexbe_behaviors/g" \
  PROJECT_flexbe_behaviors/CMakeLists.txt \
  PROJECT_flexbe_behaviors/package.xml \
  PROJECT_flexbe_behaviors/setup.py \
  PROJECT_flexbe_behaviors/manifest/example_behavior.xml
mv PROJECT_flexbe_behaviors/src/PROJECT_flexbe_behaviors PROJECT_flexbe_behaviors/src/${name}_flexbe_behaviors
mv PROJECT_flexbe_behaviors ${name}_flexbe_behaviors
rm README.md
echo -e "# ${name}_behaviors\r\nThis repo contains all ${name}-specific states and behaviors." >> README.md
echo "Done"

echo ""
echo -e "\e[96m(4/4) Initializing new repository...\033[0m"
rm -rf .git
git init
git add .
git commit -m "Initial commit"

echo ""
echo -e "\e[92mCongratulations\033[0m, your new repository  \e[1m${name}_behaviors\033[0m  is ready to be pushed!"
echo -e "Please run the following commands to push it:"
echo -e "  git remote add origin [your_repo_url]"
echo -e "  git push origin master"
echo ""
echo -e "Your new repository already contains an example behavior and examples for writing own states:"
echo -e "  rosed ${name}_flexbe_states example_state.py"
echo -e "  rosed ${name}_flexbe_states example_action_state.py"
echo ""
echo -e "Clone the following repository for a user interface (editor + runtime control) for FlexBE:"
echo -e "  git clone https://github.com/FlexBE/flexbe_app.git"
echo ""
echo -e "\e[96mMake sure to build your workspace.\033[0m"
echo ""

cd ..
if [[ ":$ROS_PACKAGE_PATH:" != *":$PWD"* ]]; then
	echo -e "\e[93mThe repository is not on the ROS_PACKAGE_PATH.\e[0m"
	echo -e "Run the following command if this was not on purpose:"
	echo -e "  roscd && cd ../src && mv $PWD/${name}_behaviors ${name}_behaviors"
	echo ""
fi
