#!/bin/sh
# git Commit Reorder

USAGE="basecommittish commitish-1 [commitish-2 [...]]"
. git-sh-setup

if [ $# -lt 2 ]
then
	usage
fi

trap "rm -f $revlist $revlisttemp" 0 15

revlist=`mktemp -t git-reorder-XXXXXX`
revlisttemp=`mktemp -t git-reorder-XXXXXX`

master="`git branch | egrep '^\*' | cut -f 2 -d " "`"

firstrev="`git-rev-parse "$1"`" || exit 1
git log "$firstrev".. | egrep '^commit ' | cut -f 2 -d " " | grep -v "$firstrev" | tac > $revlist

shift

# Check that all revisions on the command line are good.
for each in "$@"
do
	rev="`git-rev-parse "$each"`"
	if [ $? -ne 0 ] || ! grep $rev $revlist > /dev/null
	then
		echo "Either $rev revision is not a valid revision, or it didn't happen since $firstrev."
		exit 1
	fi
done

# Create a new branch at the first point from which we want to reorder.

echo Rewound to $firstrev...
git checkout -b cleanup "$firstrev"

# Apply all the patches we want to move to the beginning in the order given. Strike them off the list of commits that have transpired since the initial revision.
for each in "$@"
do
	echo Moving desired commit $each...
	rev="`git-rev-parse "$each"`"
	if git cherry-pick -r "$rev"
	then
		grep -v "$rev" $revlist > $revlisttemp
		cat $revlisttemp > $revlist
	else
		git checkout $master
		git branch -D cleanup
	fi
done

# Apply all the other commits that "don't" get re-ordered.
for each in `cat $revlist`
do
	echo Moving remaining commit $each...
	if ! git cherry-pick -r "$each"
	then
		git checkout $master
		git branch -D cleanup
	fi
done

# Promote this to master
#git branch -f $master cleanup
#git checkout $master
#git branch -d cleanup

