#!/bin/sh

#
# Cherry picks a github hash or a svn rXXXXX number.
#
# Assumes that you've setup a FreeBSD upstream, per the git cheatsheet:
#
# Some advanced operations like merging or cherry-picking from FreeBSD
# require you to add some extra settings on your repo. You may need to
# configure an additional remote repository, which points to the
# official FreeBSD git repo and you probably want to configure git to
# fetch metadata that corresponds to subversion revisions.
# 
# git config --add remote.origin.fetch '+refs/notes/*:refs/notes/*'
# git remote add FreeBSD https://github.com/freebsd/freebsd
#
# This will be cherry picked into the currently checked out branch.
# The current tree should be clean before running this script.
# git cherry-pick --abort if you run into trouble. This script
# specifically doesn't do that to avoid destroying information.
#

upstream=freebsd
master=master
svn_branch=head

usage() {
    echo "USAGE: git-mfc revs.."
    exit 1
}

# always do both, but write this so we can split it out in the
# future if there's a neeed.

dofetch=true
docp=true

if [ $# -lt 1 ]; then
   usage
fi

#
# You can do this by hand before, if you like or need to find a specific
# version before merging. From the cheet sheet:
#
# git log --grep=revision=307879 --show-notes FreeBSD/master
#
# will find revision 307879. Note, revisions less than 100000
# may have false positives, but none of that is relevant until
# we get to svn r1000000.
#
if $dofetch; then
    echo "=======> Fetching upstream from ${upstream}"
    git fetch ${upstream} master
    git fetch ${upstream} '+refs/notes/*:refs/notes/*'
fi

if $docp; then

    for hash; do
	export EDITOR=/tmp/freebsd-mfc-editor

	unset svn
	echo "=======> Attempting to cherry-pick $hash"
	case $hash in
	    r*)
		svn=$hash
		echo -n "Turning svn $svn into github hash: "
		hash=$(git log --grep=${svn_branch}@${hash#r} --show-notes ${master} | grep commit | cut -d' ' -f 2)
		echo $hash
		if [ -z "$hash" ]; then
		    echo Unable to convert $svn into github hash
		    exit 1
		fi
		;;
	    *)
		echo "Don't understand $hash"
		exit 1
		;;
	esac
if false; then
    # Don't have convenient markings to make this work
	echo -n "Checking to see if $svn has been cherry picked or merged yet: "
	hash2=$(git log --grep="svn.*${svn#r}" --show-notes | grep commit | cut -d' ' -f 2)
	if [ -n "$hash2" ]; then
	    echo $hash2
	    echo "-------> Skipping $svn, already present in tree as $hash2"
	    continue
	fi
	echo nope.
fi
	(
#	    echo echo '>> $1'
#	    echo echo '"'"github-cherry-pick: $hash"'"' '>> $1'
#	    echo echo '"'"FreeBSD-svn:	$svn"'"' '>> $1'
	    echo 'fn=/tmp/junk.$$'
	    echo 'cp $1 $fn'
	    echo '(echo -n "'${svn}': " ; head -1 < $fn) > $1'
	    echo 'rm $fn'
	) > ${EDITOR}
	chmod +x ${EDITOR}
	echo git cherry-pick --edit $hash
	git cherry-pick --edit $hash || exit
	echo "-------> Successfully cherry-picked $svn"
    done
fi
