#!/usr/bin/perl

require "../date.pm";
require "CGI.pm";
require "../svn.pm";

my $inyear = CGI::param('year');
my $inmon = CGI::param('month');

sub setval {
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =
        gmtime(time);

    srand($ENV{'REMOTE_ADDR'} . "$mday.$mon.$year");
    
    return rand(1000000);
}

sub setrand {
    my ($m, $y, $add)= @_;

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =
        gmtime(time);

    srand($m+$y+$hour+$min+$add);

    return int(rand(100000));
}

my $val = setval();

if($inyear) {

    my $rand = CGI::cookie('usercheck');
    if($rand eq $val) {

        print "Content-Type: text/plain\n";
        print "Content-Encoding: x-gzip\n\n";
        open(FILE, "gzip -c mail-$inyear-$inmon|") ||
            print "can't do it";

        while(<FILE>) {
            print $_;
        }
        close(FILE);
        exit;
    }
    else {
        my $incode = CGI::param('code');
        my $msg;
        if($incode) {
            if(($incode eq setrand($inmonth, $inyear)) ||
               ($incode eq setrand($inmonth, $inyear, 1))) {
                my $cookie = CGI::cookie(-name=> "usercheck",
                                         -value=> setval());
                print "Location: ./mbox.cgi?year=$inyear&month=$inmon\nSet-Cookie: $cookie\n\n";
                exit;
            }
            else {
                $msg= "Bad code given, retry! ";
            }
        }
        print "Content-Type: text/html\n\n";

        
        my $code = setrand($inmonth, $inyear);

        print <<POO
<html>
<head>
<title>Prove that you are in fact human</title>
</head>
<body>
$msg
Before I\'ll let you view any mbox files, I want you to prove that you are in
fact a human. Do this by entering this code (<b>$code</b>) in this form,
within 30 seconds:

<form action="mbox.cgi" method="POST">
<input type="hidden" name="year" value="$inyear">
<input type="hidden" name="month" value="$inmon">
<input type="text" name="code" value="">
<input type="submit" value="I'm human!">
</body>
</html>
POO
;
        exit;
    }
}

print "Content-Type: text/html\n\n";

print <<POO
<html>
<head>
<title>Subversion Users mboxes</title>
<link rel="STYLESHEET" type="text/css" href="/svn.css">
</head>
<body bgcolor="#ffffff">
POO
    ;
showlinks();

print <<POO
<p>
<h1>Subversion Users mboxes</h1>
POO
    ;

showmboxes();

print "<hr><a href=\"https://daniel.haxx.se/\">daniel.haxx.se</a></body></html>\n";
