#!/usr/bin/perl -w

#######################################################
#                                                     #
# This program takes compressed and gzipped programs  #
# in the current directory and turns them into bzip2  #
# format.  It handles the .tgz extension in a         #
# reasonable way, producing a .tar.bz2 file.          #
#                                                     #
# FIX: This script has been modified so that it       #
# it converts bz2-files to xz-files.                  #
# Original script is here:                            #
# http://tldp.org/HOWTO/Bzip2.html                    #
# http://tldp.org/HOWTO/Bzip2-10.html                 #
#                                                     #
#######################################################
$counter = 0;
$saved_bytes = 0;
$totals_file = '/tmp/machine_xz_total';
$machine_xz_total = 0;

@raw = (defined @ARGV)?@ARGV:<*>;

foreach(@raw) {
    next if /^bz2xz/;
    next unless /\.(tbz|bz2)$/;
    push @files, $_;
}
$total = scalar(@files);

foreach (@files) {
    if (/tbz$/) {
        ($new=$_) =~ s/tbz$/tar.xz/;
    } else {
        ($new=$_) =~ s/\.bz2$/.xz/i;
    }
    $orig_size = (stat $_)[7];
    ++$counter;
    print "Repacking $_ ($counter/$total)...\n";
    if ((system "bzip2 -cd $_ |xz -9e >$new") == 0) {
        $new_size = (stat $new)[7];
        $factor = int(100*$new_size/$orig_size+.5);
        $saved_bytes += $orig_size-$new_size;
        print "$new is about $factor% of the size of $_. :",($factor<100)?')':'(',"\n";
        unlink $_;
    } else {
        print "Arrgghh!  Something happened to $_: $!\n";
    }
}
print "You've "
    , ($saved_bytes>=0)?"saved ":"lost "
    , abs($saved_bytes)
    , " bytes of storage space :"
    , ($saved_bytes>=0)?")":"("
    , "\n"
    ;

unless (-e '/tmp/machine_xz_total') {
    system ('echo "0" >/tmp/machine_xz_total');
    system ('chmod', '0666', '/tmp/machine_xz_total');
}


chomp($machine_xz_total = `cat $totals_file`);
open TOTAL, ">$totals_file"
     or die "Can't open system-wide total: $!";
$machine_xz_total += $saved_bytes;
print TOTAL $machine_xz_total;
close TOTAL;

print "That's a machine-wide total of ",`cat $totals_file`," bytes saved.\n";

