#!/usr/bin/perl

$backupdir=shift(@ARGV);

foreach $file (@ARGV)
{
  if(length($file)==0) { next; }
  $targz=0;
  if($file=~m/\.gz$/) { $targz=1; }
  $basedir=$file;
  if(($i=rindex($basedir,"/"))>=0) {
    $basedir=substr($basedir,0,$i);
  }
  else {
    $basedir="";
  }
  if(open(F,$file))
  {
    $buffer="";
    # Check if the file is the same of a previous copy (to keep the last-update date):
    $bcopy="";
    $M1=1024*1024;
    if(open(B,"$backupdir/$file"))
    {
      $n=$b=$M1;
      while($n>=$M1 && $b>=$M1) {
        $n=read(F,$buffer,$M1);
        $b=read(B,$bcopy,$M1);
	if($n!=$b) {
	  last;
	}
	if($targz) {
	  $buffer=substr($buffer,0,4).substr($buffer,8); # Skip gzip timestamp
	  $bcopy=substr($bcopy,0,4).substr($bcopy,8); # Skip gzip timestamp
	  $targz=0;
	}
	if($buffer ne $bcopy) {
	  $n=-1;$b=-2;
	  last;
	}
      }
      close(B);
      if($n==$b) {
         @s=stat("$file");
         @sb=stat("$backupdir/$file");
	 if($s[9]>$sb[9]) {
	   system("touch -r '$backupdir/$file' '$file'");
	   if(length($basedir)>0) {
	     system("touch -r '$backupdir/$basedir' '$basedir'");
	   }
	 }
         #print "File OK: $file\n";
      }
      else {
         print "NOT the same $file, not touching.\n";
      }
    }
    else {
      print "Not found backup for $file.\n";
    }
    # Delete anyway the .orig file:
    if( -f "$file.orig") { unlink("$file.orig"); }
    close(F);
  }
}
