#!/usr/bin/perl
# cleans and repackages the upstream source
# (c) 2004, Eduard Bloch <blade@debian.org>
# License: GPL

use Cwd 'abs_path';
use File::Basename;

$in = abs_path($ARGV[0]);
$out= ($ARGV[1]) ? abs_path($ARGV[1]) : $in ;

die "
uclean -- remove suspicious/redundant files from upstream source
  tarball, convert bz2 -> gz and/or recompress better

Usage:
  uclean FILE
    fix the source in tarball FILE, recompress, store in the same file 
  uclean FILE NEW
    fix the source in tarball FILE, recompress, store in a new file 
" if !@ARGV;

chomp($wd=`mktemp -d`);
chdir $wd || die "Could not create the temp directory!\n";

die "Problems creating the temporary directory..." if (!$wd);

system("unp $in || tar zxvf $in || tar jcvf $in || unzip $in");
if(<*>) {
   chdir <*>;
}
else {
   die "No file contents? Check $wd\n";
}
system "make clean distclean";
open($l, "find $wd |");
@files=<$l>;
close($l) or die "Problems scanning the package contents!\n";
# run two times to not forget directories
for(@files) {
   chomp;
   if(/(\.o$)|(\.svn)|(CVS)|(\.cvsignore)/ && -e $_) {
      if(-d $_) {
         print STDOUT "rm"," -rf ",$_,"\n";
         system("rm","-rf",$_);
      }
      else
      {
         unlink $_;
      }
   }
}
      
system "rm -rf $wd/*/debian";
chdir $wd;
if($in eq $out) {
   $old=dirname($out)."/upstream-".basename($out);
   rename($out,$old) || die "Could not rename $out to $old";
}
system("tar c * | gzip -9 > $out") && die "Could not create $out!\n";
system "rm -rf $wd";
