#!/bin/sh

usage() {
cat >/dev/stderr <<EOT
Usage: $0 [option]
      -f force pull
    
Description:
  Check Git repositories recursively
EOT
}

FORCEPULL=0
while getopts "hf" o; do
    case "${o}" in
        h)
            usage
            exit 0
            ;;
        f)
           FORCEPULL=1
           ;;
        *)
            usage
            exit 1
            ;;
    esac
done
shift $((OPTIND-1))

export LC_ALL=C.UTF-8
for repository in `find . -name .git -type d | sort` ; do
    repos=$(dirname $repository)
    curdir=$(pwd)
    cd $repos
    quilt pop -a >/dev/null  2>/dev/null ; rm -rf .pc
    if ! git status | grep -q -e "nichts zu committen, Arbeitsverzeichnis unverändert" -e "nothing to commit, working tree clean" -e '"git push"' -e '^Untracked files' ; then
        echo $repos
        git status | grep -v -e '^ *$' -e '^  *(use "git' -e '^On branch master' -e '^no changes added to commit' -e 'Your branch is up to date with'
    fi
    if git status | grep -q -e '"git push"' ; then
        echo "Push needed in $repos"
    else
       if [ $FORCEPULL -eq 1 ] ; then
          echo "Forcing pull in $repos"
          if [ `git ls-files --other --directory --exclude-standard | wc -l` -gt 0 ] ; then
              #  There are untracked files which gbp does not like but it should be OK here
              git pull
          else
              gbp pull | grep -v \
                              -e "^gbp:info:" \
                              -e "gbp:warning: No branch tracking '.*' found - skipping." \
                              -e "Already up to date." \
                              -e "Current branch master is up to date."
          fi
       fi
    fi
    cd $curdir
done
