#! /usr/bin/perl -w

# Remove trailing whitespace from modified lines in a workign file
#
# ARGV[0]: working file
# ARGV[1]: Unified diff between original and working file

use strict;
use FileHandle;
use File::Temp qw( :mktemp );

my ($file, $diff) = @ARGV;
my %lines;

my $dfh = new FileHandle("< $diff")
    or die "$ARGV[1]: $!\n";
while (<$dfh>) {
    if (/^@@ -(\d+)(?:,(\d+)) \+(\d+)(?:,(\d+)) @@/) {
	my ($ln, $n, $lr) = ($2 || 1, $3, $4 || 1);
	while ($ln || $lr) {
	#print "[$ln,$lr]\n";
	    $_ = <$dfh>;
	    defined $_ or die "Bad patch";
	    if (/^\+/) {
		$lines{$n} = 1
		    if (/[ \t]$/);
		$lr--;
		$n++;
	    } elsif (/^-/) {
		$ln--;
	    } else {
		$ln--;
		$lr--;
		$n++;
	    }
	}
    }
}
$dfh->close;

if (%lines) {
    my $fh = new FileHandle("< $file")
	or die "$file: $!\n";
    my ($tmp, $tmpname) = mkstemp("$file.XXXXXX")
	or die "$file.XXXXXX: $!\n";
    print "Removing trailing whitespace from line(s) ",
	  join(', ', (keys %lines)), " of $file\n";
    while (<$fh>) {
	s/[ \t]+$//
	    if $lines{$.};
	print $tmp $_;
    }
    $fh->close;
    $tmp->close
	or die "$tmpname: $!\n";
    rename $tmpname, $file
    	or die "Renaming $tmpname to $file: $!\n";
}

exit (%lines ? 1 : 0);
