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

# Get vars
eval "$(grep '^#[^#=[:space:]]\+=[^=[:space:]]\+$' .git-skip 2> /dev/null | \
        sed 's|^#||')"

# No _option_processor, al arguments are passed (for what it brings ;-) )
GitCommand=$(echo `basename $0` | sed 's/^git[-]//')

if [ "$GitCommand" = "" ]
then
   echo "! [ERROR] git command not found in the script name" >&2
   exit 1
fi

# setup ssh_askpass cache for push and pull
if ( [ "$GitCommand" = "pull" ] || [ "$GitCommand" = "push" ] ) && \
   [ "$GIT_ASKPASS" != "" ] && [ -r $GIT_ASKPASS ] && \
   grep -qw ssh_askpass $GIT_ASKPASS
then
   # setup ssh_askpass cache vars (single input)
   $(ssh_askpass --exports | grep -w SSH_ASKPASS_CACHE)
fi

# Add EDITOR var if not set (missing -m will be caught by the EDITOR)
if [ "$EDITOR" = "" ]
then
   EDITOR=vi
   export EDITOR
fi

if [ "$GitCommand" = "push" ] && [ "$1" == "--help" ]
then
   (
   echo
   echo "Usage: $(basename $0) [EXTRA_OPTS] [OPTS] [ARGS]"
   echo
   echo "Extra opts:"
   echo "   ---dry-run"
   if [ "$GitCommand" = "push" ]
   then
      echo "   --all-remotes"
   fi
   echo
   ) >&2
   exit 0
fi

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

# 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
      (
         if ! cd "$R"
         then
            echo "! [WARNING] Unable to run: cd ~/$R"
         else
            echo "# git repo $(pwd | sed "s,^$HOME,~,")"
            if [ "$GitCommand" = "push" ] && [ "$1" == "--all-remotes" ]
            then
               for Remote in $(git remote | sort -r)
               do
                  echo "# Remote: $Remote"
                  ${Run[@]} git $GitCommand $Remote
                  [ ${#PUSH_SLEEP} -ne 0 ] && sleep $PUSH_SLEEP
               done
            else
               ${Run[@]} git $GitCommand $*
               if grep -q '^pu' <<< "$GitCommand"
               then
                  [ ${#PUSH_SLEEP} -ne 0 ] && sleep $PUSH_SLEEP
               fi
            fi
         fi
      )
   fi
done
