#! /usr/bin/perl -w

$kernel_path = shift() || _help();
$orig = shift() || _help();
$new = shift() || _help();

# mangle orig so it's relative to the top of the linux source
$kernel_path =~ s|/+$||;
$kernel_path =~ s|/[^/]*$||;
$relative = substr $orig, length($kernel_path) + 1;

die("$new not found") if(!-e $new);

if(!-e $orig) {
    $new_time = gmtime((stat($new))[9]);
    print "--- $relative.orig $new_time\n";
    print "+++ $relative $new_time\n";
    open(NEW, "$new");
    $count = 0;
    while(<NEW>) {$count++;}
    close(NEW);
    print "@@ -0,0 +1,$count @@\n";
    open(NEW, "$new");
    while(<NEW>) {print "+$_";}
    close(NEW);
} else {
    open(DIFF, "diff -u $orig $new |") or die("couldn't diff files");
    while(<DIFF>) {
	s/(^---\s+)$orig(\s+.*)/$1$relative\.orig$2/;
	s/(^\+\+\+\s+)$new(\s+.*)/$1$relative$2/;
	print;
    }
    close(DIFF);
}

sub _help {
    print "Usage: patch_fragment <kernel path> <old> <new>\n";
    exit(1);
}
