#!/bin/sh
#
# vim:tabstop=3:expandtab:shiftwidth=3
#

_help_show_args=""
. $(dirname $0)/_option_processor 2> /dev/null

ModRegExpr="^.M "
NewRegExpr="^[?][?] "

# Setup the regular expression
if [ "$_m" = "yes" ] || [ "$__modified_only" = "yes" ]
then
   echo "# Skip new files"
   RegExpr="${ModRegExpr}"
else
   RegExpr="${ModRegExpr}|${NewRegExpr}"
fi

SkipFilter='lock.*#$|/~[$]|/Thumbs.db'
if [ "$__keep_swp" != "yes" ]
then
   SkipFilter="$(echo "$SkipFilter" | sed 's/.$/\0|/').swp\$"
fi

# Setup dry-run var
unset Run
if [ "$___dry_run" = "yes" ]
then
   Run=(echo '<skipped>')
fi

git_clean()
{
   if [ $(find $1/ -name '.access^' | wc -l) -gt 0 ]
   then
      echo "# Removing .access^ files from $1"
      ${Run[@]} find $1 -name '.access^' -exec rm {} \;
   fi

   if [ $(find $1/ -name '.attribute^' | wc -l) -gt 0 ]
   then
      echo "# Removing .attribute^ files from $1"
      ${Run[@]} find $1 -name '.attribute^' -exec rm {} \;
   fi
}

git_add_modified()
{
   (
      echo "# git repo ~/$1"
      cd ~/$1
      git status --porcelain |  egrep -v "$SkipFilter" | \
      egrep "$RegExpr" | \
      sed -e 's,RM .* -> ,,' -e 's,^.M ,,' -e 's,^?? ,,' | \
      while read File
      do
         echo "# [ADD] ~/$1/$File"
         ${Run[@]} git add "$File"
      done
   )
}

# From ~/
cd $HOME

EgrepSkip="$(awk '/^[^#]/{print $1}' .git-skip 2> /dev/null | tr '\n' '|' | sed -e 's/|$/$/' -e 's/|/$|^/g' -e 's/^/^/')"
for R in $(find . -xdev -name .git -type d 2> /dev/null | sed -e 's,/.git$,,' -e 's,^[.][/]*,,')
do
   if [ "$EgrepSkip" != "" ] && echo "$R" | egrep -q "$EgrepSkip"
   then
      echo "Skipping $(echo "$R" | sed 's,^, ~/,')"
   else
      git_clean "$R"
      git_add_modified "$R"
   fi
done
