#!/usr/bin/env perl

use warnings;
use strict;

#
# tar2zip - converts one or more tar archives to a ZIP archive on stdout

# quick and dirty!
# TODO: somehow manages to crash when the .zip files already exist (!)

use IO::Handle;
use Archive::Zip;
use Archive::Tar;

my $stdout = new IO::Handle or die;
$stdout->fdopen(fileno(STDOUT),'w') or die;

foreach my $tarfile (@ARGV)
{
  if (!-f $tarfile || !-r $tarfile)
  {
    print STDERR "skipping $tarfile, not a file or not accessible\n";
    next;
  }

  my $tar = Archive::Tar->new($tarfile, $tarfile =~ /gz$/);

  if (!$tar)
  {
    print STDERR "skipping $tarfile, not a tar file\n";
    next;
  }

   my $zip = Archive::Zip->new() or die;

   foreach my $file ($tar->list_files())
   {
     $zip->addString($tar->get_content($file),$file);
   }

   my $zipfile = $tarfile;
   $zipfile =~ s/\.(tar.gz|tgz|)$/.zip/;

   #$zip->writeToFileHandle($stdout,0);
   $zip->writeToFileNamed($zipfile,0);
   print STDERR "written contents of $tarfile to $zipfile\n";
}
