#!/usr/bin/perl -w

use strict;
use File::Find;

my $gunzip = "gunzip";
my $bzip2  = "bzip2";

sub gz2bz2 {
  my $orig = $_;
  my $base = $_;
  my $dest = $_;
  # Find all gzip compressed files based on file names
  if (($base =~ s/\.gz$//) or ($base =~ s/\.tgz$/\.tar/)) {
    if ( -l $orig ) {
      # Create a new symlink to the renamed destination
      $dest = readlink($orig);
      $dest =~ s/\.gz$/\.bz2/;
      symlink($dest, "$base.bz2");
      # Remove the old link - leave the original dest
      # intact for when we get to that file
      unlink($orig);
    }
    else {
      # decompress with gunzip and recompress with bzip2
      system "$gunzip $orig && $bzip2 $base";
    }
  }
}

if (@ARGV) {
  find(\&gz2bz2, @ARGV);
}
else {
  find(\&gz2bz2, ".");
}

1;
