#!/usr/bin/perl -w
use strict;
use Cwd;
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use File::Basename;

#
# Version: $ bzr-revision-id $
#

local $SIG{ALRM} = sub { die "timeout\n" };
alarm(300);

my $tmp = '/tmp';
my $dir = param('dir');
my $format = param('format') || 'zip';
if (!$dir && !defined($ENV{SCRIPT_FILENAME})) {
  $dir = basename(cwd);
  chdir('..');
  $format = 'zip';
}

if (!$dir) {
  print "Content-Type: text/plain\r\n\r\n";
  open SCRIPT, $ENV{SCRIPT_FILENAME};
  print <SCRIPT>;
  close SCRIPT;
} elsif ($dir =~ /^[\w-]+$/ && -d "$dir") {
  my $bzrid = "tag:$1,$2-$3-$4:$5:$6:$7-$8" if (`cd $dir && bzr version-info 2>/dev/null| grep -e '^revision-id:'` =~ /^revision-id:\s+(.+?)-(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})-(.+)$/);
  if (defined($bzrid)) {
    $tmp = "$tmp/$dir";
    mkdir($tmp);
    open(FILES, "find $dir -type f | grep -v '^$dir/.bzr' |");
    my $tag = '\$'.' bzr-revision-id '.'\$';
    while (<FILES>) {
      chomp;
      my $filedir = dirname($_);
      `mkdir -p $tmp/../$filedir`;
      `sed -e 's/$tag/$bzrid/g' < $_ > $tmp/../$_ && touch -r $_ $tmp/../$_`;
    }
    close FILES;
    chdir("$tmp/..");
  }
  if ($format eq 'zip' || ($ENV{REQUEST_URI} =~ /\.zip$/)) {
    print "Content-Type: application/zip\r\n\r\n";
    print `zip -qr - $dir -x '*/.doaprc' -x '*/.bzr*' -x '*/CVS/*' -x '*/.htaccess' -x '*/header.html' -x '*/footer.html' -x '*/._*'`;
  } else {
    print "Content-Type: application/x-tar\r\n\r\n";
    print `tar chz --exclude '.doaprc' --exclude '.bzr*' --exclude 'CVS' --exclude .htaccess --exclude header.html --exclude footer.html --exclude ._* $dir`;
  }
  if (defined($bzrid)) {
    `rm -rf $tmp`;
  }
} elsif (defined($ENV{REQUEST_URI})) {
  print "Status: 404 Not Found\r\n";
  print "Content-Type: text/html\r\n\r\n";
  print <<EOF;
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL $ENV{REQUEST_URI} ($dir) was not found on this server.</p>
</body></html>
EOF
} else {
  print STDERR "Sorry, the directory ($dir) was not found.\n";
}

