#!/bin/bash
#
# update all Git and Subversion repositories under the current directory.

set -e

CURRENT=$PWD
# Set to newline to loop over find output correctly on spaced paths.
IFS="
"

echorun() {
  echo + "$@"
  "$@"
}

find -L "$CURRENT" \( -name .git -or -name .svn \) -print0 | while read -d '' -r SCM; do
  DIRECTORY="$(dirname "$SCM")"
  cd "$DIRECTORY" || continue
  if [ -d ../.svn ] || echo "$DIRECTORY" | grep -q "vendor/ruby"; then
    continue
  fi
  echo "== Updating $(basename "$DIRECTORY")"
  if [ -d .git/svn ]; then
    echorun git svn fetch
    echorun git svn rebase
  elif [ -d .git ]; then
    echorun git fetch --all
    if [ -n "$(git remote -v)" ]; then
      echorun git checkout --quiet master || echorun git checkout --quiet main || echorun git checkout --quiet trunk
      echorun git merge --no-edit --ff-only origin/HEAD
      git branch --merged | grep -v '\*' | xargs -n 1 git branch -d
    fi
  elif [ -d .svn ]; then
    echorun svn update
  fi
  echo
done
