#!/bin/bash
#
# Copyright (c) 2010, 2011 CNRS
# Authors: Joseph Mirabel
#
#
# This file is part of hpp-tools
# hpp-tools is free software: you can redistribute it
# and/or modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation, either version
# 3 of the License, or (at your option) any later version.
#
# hpp-tools is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Lesser Public License for more details.  You should have
# received a copy of the GNU Lesser General Public License along with
# hpp-tools  If not, see
# <http://www.gnu.org/licenses/>.

GIT="git --no-pager -c status.showUntrackedFiles=no"
short_output=0

output=/dev/stdout
_flush () {
  #echo "flushing"
  if [ $short_output -eq 1 ]; then
    cat $output
  fi
}
_empty () {
  #echo "emptying"
  if [ $short_output -eq 1 ]; then
    echo "" >$output
  fi
}

while getopts "h?scCv" opt; do
  case "$opt" in
    h|\?)
      echo -e "Usage: $(basename $0) [-h] [-s] [-c] [-C] <command>\n"
      echo "Options"
      echo -e "\t-h\tthis help message"
      echo -e "\t-s\thide git folders which do not generate any output"
      echo -e "\t-c\tset color.status to always (see git-config man page)"
      echo -e "\t-C\tset color.status to never"
      echo -e "\t-v\tshow version and exit"
      exit 0
      ;;
    s)
      output=$(mktemp)
      short_output=1
      ;;
    c)
      GIT="${GIT} -c color.status=always"
      ;;
    c)
      GIT="${GIT} -c color.status=never"
      ;;
    v)
      echo -e "Project:\thpp-tools"
      echo -e "Name   :\t$(basename $0)"
      echo -e "Version:\t9.0.2"
      echo -e "URL    :\thttps://github.com/humanoid-path-planner/hpp-tools"
  esac
done

current_dir=`pwd`

shift `expr ${OPTIND} - 1`
#echo $@
for child_dir in $(ls); do
  test -d "$child_dir" || continue
  ## If child_dir contains a submodule, .git is a file and not a directory
  test -d "$child_dir/.git" -o -f "$child_dir/.git" || continue
  cd "$child_dir"
  echo -e "\033[1;36m------- Folder $child_dir ---------------\033[0m" >$output
  if [ "$short_output" -eq 1 ]; then
    if [[ ! $($GIT $@ | tee -a $output | wc -l) -eq 0 ]]; then
      _flush
    fi
    _empty
  else
    $GIT $@
  fi
  cd "$current_dir"
done

if [ "$short_output" -eq 1 ]; then
  rm $output
fi
