#!/bin/sh

_in_what_ros_pkg () {
  looking_path=$(pwd)
  found=$(find $looking_path -maxdepth 1 -iname package.xml | wc -l)
  while [ $found -eq 0 ]; do
    looking_path=$(dirname $looking_path)
    [ "$looking_path" = "/" ] && return
    found=$(find $looking_path -maxdepth 1 -iname package.xml | wc -l)
  done
  echo $(basename $looking_path)
}

git_jsk_commit () {
  tmp_file=$(mktemp -t XXXXX)
  changed=$(git status --porcelain | grep '^M' | awk '{printf "  - %s\n", $2}')
  if [ "$changed" != "" ]; then
    changed="Modified:\n${changed}"
  fi
  added=$(git status --porcelain | grep '^A' | awk '{printf "  - %s\n", $2}')
  if [ "$added" != "" ]; then
    added="Added:\n${added}"
  fi
  pkg=$(_in_what_ros_pkg)
  if [ "$pkg" != "" ]; then
    pkg="[${pkg}] "
  fi
  echo "${pkg}\n\n${changed}\n${added}" > ${tmp_file}
  git commit --verbose --template ${tmp_file} "$@"
}

git_jsk_commit "$@"
