#!/bin/bash
# Rebase local branches from old git-svn repo to new repo.

if [[ $# == 0 ]]
then
  echo "Usage: $0 BRANCH..." >&2
  exit 1
fi

# name of the remote containing the git-svn history
gcc_old_remote=gcc-old
# ancestor of all commits in git-svn repo
gcc_old_root=3cf0d8938a953ef13e57239613d42686f152b4fe

set -x

for branch
do
  # check that this branch is based on git-svn ancestry
  git merge-base --is-ancestor $gcc_old_root $branch || continue

  upstream=$(git rev-parse --symbolic-full-name $branch@{u} | sed -n s,^refs/heads,gcc-old,p)
  [[ $upstream ]] || continue
  # show the commits on the branch that will be rebased
  git log --pretty="format:%H %s" $upstream..$branch
  echo
  # find the last upstream commit in the branch
  base=$(git merge-base $branch $upstream)
  [[ $base ]] || continue
  # extract its SVN revision
  svnrev=$(git log --grep='^git-svn-id:' -1 $base | sed -n 's/^ *git-svn-id: .*@\([[:digit:]]\+\) .*/\1/p')
  [[ $svnrev ]] || continue
  # find equivalent commit in master
  onto=$(git log --pretty=format:%H --grep="From-SVN: r$svnrev$" $branch@{u})
  [[ $onto ]] || continue

  git rebase --onto $onto $upstream $branch
done
