#!/usr/bin/perl -w
use strict;
use File::Temp qw/tempfile/;
use File::Which qw/which/;

die 'bad params' if (scalar @ARGV != 1);

my $stable_path = '/home/latest/repos/stable-queue/queue-4.4/';
my $patch = $ARGV[0];
my $file;
my $hunk;

if (!-f $patch && -f "$stable_path/$patch") {
	$patch = "$stable_path/$patch";
}

open(P, "patch --dry-run -f -p1 -i '$patch' |") or
	die "patch failed to execute: $!";
while (<P>) {
	chomp;
	if (/^No file to patch\./) {
		die "the file does not exist";
	}
	if (/^(checking|patching) file (.*)$/) {
		$file = $2;
		next;
	}
	if (/^Hunk #([0-9]+) (FAILED|succeeded at [0-9]+ with fuzz)/) {
		$hunk = $1;
		last;
	}
}
close P;

if (!defined($file) || !defined($hunk)) {
	die "couldn't find file or hunk";
}

print "Looking for hunk $hunk in $file\n";

my $has_file = 0;
my $has_hunk = 0;
my $at_hunk = 0;

my $tmp = File::Temp->new();
open P, "<$patch";
while (<P>) {
	chomp;
	if (/^\+\+\+ [^\/]+\/(\S+)/) {
		$has_file = ($1 eq $file);
		next;
	}
	next unless ($has_file);
	if (/^@@/) {
		$has_hunk = (++$at_hunk == $hunk);
		next;
	}
	next unless ($has_hunk);
	last if (/^---\s/);
	if (s/^[- ]//) {
		print $tmp "$_\n";
	}
}
close P;
close $tmp;

my $diff = which('colordiff') || 'diff';

system("$diff -up " . $tmp->filename . " $file | less -p '^[- ]'") == 0 ||
	die "cannot exec diff | less";

1;
