#!/usr/bin/env perl
# This is a wrapper around the GIT_EXTERNAL_DIFF compatible
# git-difftool-helper script.
#
# Copyright (c) 2009 David Aguilar

use strict;
use warnings;

use File::Basename qw(dirname);

# Prints usage and exits
sub usage
{
	print << 'USAGE';

usage: git difftool [--no-prompt] [--tool=tool] ["git diff" options]
USAGE
	exit 1;
}

# Sets PATH, GIT_PAGER, and GIT_EXTERNAL_DIFF so that
# git-difftool-helper is invoked by 'git diff'.
sub setup_environment
{
	my @paths = ( dirname($0), split(':', $ENV{PATH}) );
	$ENV{PATH} = join(':', @paths);
	$ENV{GIT_PAGER} = '';
	$ENV{GIT_EXTERNAL_DIFF} = 'git-difftool-helper';
}

# Sets an environment variable recognized by git-difftool-helper
# to signal that we shouldn't prompt before viewing each file.
sub no_prompt
{
	$ENV{GIT_DIFFTOOL_NO_PROMPT} = 'true';
}

# Sets a default value for the merge tool used by git-difftool-helper.
sub setup_mergetool
{
	$ENV{GIT_MERGE_TOOL} = shift;
}

# Processes command-line flags and generates a corresponding
# 'git diff' command.  Any arguments that are unknown to this
# script are assumed to be arguments intended for 'git diff'.
sub generate_command
{
	my @command = ('git', 'diff');
	my $skip_next = 0;

	my $idx = -1;
	for my $arg (@ARGV) {
		$idx++;

		if ($skip_next) {
			$skip_next = 0;
			next;
		}

		if ($arg eq '-h' or $arg eq '--help') {
			usage()
		}

		if ($arg eq '--no-prompt') {
			no_prompt();
			next;
		}

		if ($arg eq '-t' or $arg eq '--tool') {
			$skip_next = 1;
			if ( scalar(@ARGV) <= $idx + 1 ) {
				usage();
			}
			setup_mergetool($ARGV[$idx + 1]);
			next;
		}

		if ($arg =~ /^--tool=/) {
			$arg = substr($arg, 7);
			setup_mergetool($arg);
			next;
		}
		push @command, $arg;
	}
	return @command
}

# Sets up the git-difftool environment and execs 'git diff'.
sub main
{
	setup_environment();
	exec(generate_command());
}

main()
