#!/bin/sh

SRCDIR="$1"
DESTDIR="$2"
SUBDIR="$3"

PLUCKSCRIPT='
TMPFILE=$GIT_INDEX_FILE.tmp

git-ls-files -s | perl -e '\''
	while (<>) {
		if (m|\t\Q'"$SUBDIR"'\E/|) {
			$line=$_;
			s/^\d+/0/;
			print;

			$_=$line;
			s|\t\Q'"$SUBDIR"'\E/|\t|;
			print;
		} else {
			s/^\d+/0/;
			print;
		}
	}'\'' > $TMPFILE

git-update-index --index-info < $TMPFILE

rm $TMPFILE
';

PRUNESCRIPT='
git_commit_non_empty_tree()
{
	if test $# = 3 && test "$1" = $(git rev-parse "$3^{tree}"); then
		map "$3"
	else
		git commit-tree "$@"
	fi
}

git_commit_non_empty_tree "$@"
';

echo "Copying repository from $SRCDIR to $DESTDIR..."
cp -r "$SRCDIR" "$DESTDIR"

(
cd "$DESTDIR"

echo;echo;echo "Preparing repository..."

git reset --hard master

echo;echo;echo "Plucking directory $SUBDIR..."

git-filter-branch -f --index-filter "$PLUCKSCRIPT" --commit-filter "$PRUNESCRIPT" master

echo;echo;echo "Synchronizing working copy..."

git reset --hard master

echo;echo;echo "Determining usefulness of root commit..."

ROOTCOMMIT=`git-rev-list master | tail -1`

if git show $ROOTCOMMIT | grep ^diff >&/dev/null; then
	echo "Root commit introduces files."
else
	echo "Root commit does not introduce files; removing..."

	PARENTFILTER='
		read parent;

		if [ "$parent" != "-p '$ROOTCOMMIT'" ]; then
			echo $parent;
		fi
	';

	git-filter-branch -f --parent-filter "$PARENTFILTER" master

	echo;echo;echo "Synchronizing working copy..."

	git reset --hard master
fi

echo;echo;echo "Removing backup refs and compacting repository..."

rm -fr .git/logs .git/refs/original
git gc --prune
git prune

)
