#!/usr/bin/perl 
# 
# (gpl) by tomas pospisek <tpo_deb@sourcepole.ch> 
#
# 02-11-28  v0.2    tpo
 
use strict; 
use warnings; 
use English; 
 
sub main(); 
main(); 
 
sub usage() { 
  print "xxpatch file|dir diff [diff] [...]\n"; 
  print "\tPatch file or directory with diff[s] and display the diff\n"; 
  print "\twith xxdiff. The original file or directory is left unaltered\n"; 
  print "\tThe diff has to be in a format that print lets patch guess the\n"; 
  print "\tfilename to patch, like f.ex. the \"diff -u\" format.\n";
  exit 1; 
} 
 
sub main() { 
  my $fileOrDir = shift (@ARGV); 
  my $tempdir = `mktemp -t -d xxdiff.XXXXXXXXXX`; 
  $? == 0 or die; 
  chop $tempdir; 
 
  my $curdir  = `pwd`; 
  my $copy = `basename $fileOrDir`; chop $copy; 
  $fileOrDir = `realpath $fileOrDir`; chop $fileOrDir;
 
  usage() unless (defined($fileOrDir) and defined($ARGV[0])) ; 
 
        # make a copy of the file|dir to patch 
  system("cp -a $fileOrDir $tempdir") == 0 or die; 
 
  chdir $tempdir or die "Couldn't change into $tempdir\n";
 
        # change into $tempdir and maybe into copy-dir 
  if ( -d $fileOrDir ) { 
    print "xxpatching directory $fileOrDir\n"; 
    chdir $copy or die "Couldn't change into $tempdir/$copy\n"; 
  } else { 
    print "xxpatching file $fileOrDir\n"; 
  } 
 
        # apply patches 
  while( $_ = shift(@ARGV) ) { 
    system("patch < $_"); $? == 0 or die; 
  } 
 
        # exec xxdiff an patched copy 
  chdir $tempdir or die "Couldn't change into $tempdir\n";
  print ("pwd".`pwd`."\n"); 
  print ("xxdiff $fileOrDir $copy\n"); 
  system("xxdiff $fileOrDir $copy"); 
 
        # don't like this, but is there a better way? 
  # system("rm -r $tempdir"); 
} 
