#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';

my %alias = ('mk-log-parser' => 'mk-query-digest');

my $input = shift; # Might be something like mk-query-digest\&bug
my $bug;
( $input, $bug ) = $input =~ m/(.*?)(.&bug)?$/;
if ( $input ) {

   if ( $alias{$input} ) {
      print "Status: 302 Moved\nLocation: http://www.maatkit.org/get/$alias{$input}\n\n";
      exit(0);
   }

   # Get a list of the Maatkit scripts, and try to find one that matches the
   # input.
   my %scripts = map { (my $s = $_) =~ s!^.*/!!; $s => $_;  } <trunk/mk-*/mk-*>;
   my ($script) = grep { m/$input/ } keys %scripts;
   if ( $script ) {
      if ( $bug ) {
         # Redirect to the bug site
	 $script =~ s/-/_/g;
         print "Status: 302 Moved\nLocation: http://code.google.com/p/maatkit/issues/list?q=Label:Tool-$script&sort=type\n\n";
	 exit(0);
      }
      if ( $script ne $input ) {
         # So wget will save the file as the correct name
         print "Status: 302 Moved\nLocation: http://www.maatkit.org/get/$script\n\n";
	 exit(0);
      }
      print "Content-type: application/x-perl\n";
      print "Content-Disposition:attachment;filename=$script\n\n";
      open my $file, "<", $scripts{$script} or die $!;
      local $/ = undef;
      print <$file> or die $!;
      close $file or die $!;
      exit(0);
   }
}

print "Status: 404 Not Found\n";
print "Content-type: text/plain\n\n";
print "No such script found\n";
exit(0);
