#!/usr/bin/bash

if [ -z "$TMPDIR" ]; then
	TMPDIR=/tmp
fi

function usage() {
	echo $0 '[-r <references>] <destination> [git arguments]'
	echo '<references>      append "References:" line with this argument'
	echo '<destination>     destination directory (can be user@machine:dir)'
	echo "<git arguments>   what's passed to git"
	echo
	echo Examples:
	echo $0 '-r bnc#12345 /tmp -1 0ea859964fcba'
	echo $0 'krtek@machine.org:/tmp v0.1..v0.2'
	exit 1
}

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

AUTO_MAINLINE=
MAINLINE="--add-header 'Patch-mainline: no'"
MAINLINE_FORCE=
GITREPO=
REF=
STARTNR=
while getopts "g:m:r:s:" OPT; do
	case "$OPT" in
		g) GITREPO="--add-header 'Git-repo: $OPTARG'"
		;;
		m) MAINLINE="--add-header 'Patch-mainline: $OPTARG'"
		   MAINLINE_FORCE="$OPTARG"
		;;
		r) REF="--add-header 'References: $OPTARG'"
		;;
		s) STARTNR="--start-number $OPTARG"
		;;
		*) usage
		;;
	esac
done

shift $(($OPTIND-1))
MACHINE="$1"
shift

PATCHES=$TMPDIR/patches
GITARGS="-o $PATCHES -s -k --no-renames $GITREPO $MAINLINE $REF $STARTNR"

rm -rf $PATCHES

eval git format-patch $GITARGS $@ || exit 1

for patch in $PATCHES/*; do
	SHA=`head -1 $patch|sed 's/^From \([0-9a-fA-F]*\) .*$/\1/'`
	sed -ni "2,$ p" $patch
	if [ -z "$MAINLINE_FORCE" ]; then
		AUTO_MAINLINE=`git name-rev --refs=refs/tags/v[2-9].* $SHA|sed 's@^.*tags/v*\([a-zA-Z0-9\.-]*\).*$@\1@'`
		if echo "$AUTO_MAINLINE" | grep -q undefined; then
			CONTAINED_IN="`git branch -r --contains $SHA linus/master next/master|head -1`"
			if [ "$CONTAINED_IN" = "  linus/master" ]; then
				AUTO_MAINLINE="no tag yet"
			elif [ "$CONTAINED_IN" = "  next/master" ]; then
				AUTO_MAINLINE="Queued in subsystem maintainer repository"
			else
				AUTO_MAINLINE=""
			fi
		fi
	fi
	if [ -n "$AUTO_MAINLINE" ]; then
		sed -i "s/^Patch-mainline: no$/Git-commit: $SHA\nPatch-mainline: $AUTO_MAINLINE/" $patch
	elif [[ -n "$GITREPO" || "$MAINLINE_FORCE" =~ ^v[0-9] ]]; then
		sed -i "s/^Patch-mainline: .*$/Git-commit: $SHA\n&/" $patch
	fi
done

if [ "$MACHINE" != "nop" ]; then
	scp -o StrictHostKeyChecking=no -C $PATCHES/* $MACHINE || exit 1
	echo Copied to $MACHINE

	rm -rf $PATCHES
fi
