#!/usr/bin/perl

# cleans and repackages the upstream source

#  Copyright 2004 Eduard Bloch <blade@debian.org>
#
#  This package is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.


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

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 
" unless (@ARGV == 1 || @ARGV == 2);

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

chomp(my $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(LIST, "find $wd |") or die ("Failed to run `find $wd`: $!");
my @files=<LIST>;
close(LIST) or die "Problems scanning the package contents!\n";
# run two times to not forget directories
for(@files) {
   chomp;
   if(/(\.o$)|(\.svn)|(CVS)|(\.cvsignore)|(config\.status)|(config\.log)/ && -e $_) {
      if(-d $_) {
         print STDOUT "rm"," -rf ",$_,"\n";
         system("rm","-rf",$_);
      }
      else
      {
         unlink $_;
      }
   }
}
      
system "rm -rf $wd/*/debian";
chdir $wd;
if($in eq $out) {
   my $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";
