#!/usr/bin/perl -wT

use CGI;
use Archive::Tar;

my $query=new CGI;

my $mode=$query->param('mode') || 'list';

my $webarchive=$query->path_info();
my $archive=$query->path_translated();
my $archivename=substr($webarchive,rindex($webarchive,'/')+1);

if(!-r $archive) {
   &error("Unknown archive $webarchive");
}

if($mode eq 'list') {
   print $query->header('text/html');
   print $query->start_html("Directory of $webarchive");

   foreach my $name (Archive::Tar->list_archive($archive)) {
      print qq{<a href="$archivename?mode=retrieve&file=$name">$name</a><br>\n};
   }
   print $query->end_html();
} elsif($mode eq 'retrieve') {
   my $file=$query->param('file');
   
   defined $file or &error("Must give file parameter");

   my $tarhandle=Archive::Tar->new($archive);

   defined $tarhandle or &error("Couldn't open $webarchive");

   my $content=$tarhandle->get_content($file);

   defined $content or &error("Couldn't retrieve $file from $webarchive");

   print $query->header('text/plain');

   print $content;

} else {
   &error("Not implemented\n");
}

sub error {
   print $query->header('text/plain');
   print shift;
   exit(0);
}
