#!/usr/athena/bin/perl -T

$WWWROOT = "/var/www/root";

print <<HTTPHEAD;
Content-Type: text/html
Status: $ENV{'REDIRECT_STATUS'} Forbidden

<!doctype HTML public "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Forbidden</title>
</head>

<body>
<h1>403 Forbidden</h1>

<p>You don't have permission to access that URL on this server.  </p>

HTTPHEAD

$ru = $ENV{'REDIRECT_URL'};

if ($ru =~ m:^/people/(.*?)/:) {
   $person = $1;
   unless($actual = readlink "$WWWROOT/people/$person") {
      $actual = $ru;
   }
} else {
   $actual = $ru;
}

undef $addr;

if ($actual =~ m|/afs/sipb(\.mit\.edu)?/user/(\w{2,8})|) {
   $addr = $2;
} elsif ($actual =~ m%/afs/athena(\.mit\.edu)?/user/(./.|./other|other)/(\w{2,8})%) {
   $addr = $3;
}

# safely exec hesinfo to determine if the address we've divined is
# valid
if($addr) {
   $pid = open(CHILD, "-|");
   if(defined $pid) {
      if($pid == 0) {
# keep hesinfo from writing to our stderr
         open(SAVERR, ">&STDERR") || warn "unable to dup stderr\n";
         open(STDERR, ">/dev/null") || warn "stderr redirect failed\n";

         exec "/bin/athena/hesinfo", $addr, "pobox";

# retrieve stderr because we have an error to report
         open(STDERR, ">&SAVERR");
         die "exec failed (/bin/athena/hesinfo): $!\n";
      } else {
         @hesdata = <CHILD>;
         close(CHILD);
# child will return zero on success, nonzero on failure
         if($? != 0) {
            undef $addr;
         }
      }
   } else {
      warn "unable to fork to exec hesinfo\n";
   }
}

# if all the above tests are passed, $addr will have a value, otherwise
# it'll be undefined
if($addr) {
   print <<UCONTACT;

<p>You tried to access</p>
<div align=center><code>http://stuff.mit.edu$ENV{'REDIRECT_URL'}</code></div>
<p>A possible contact address for the owner of this web page is 
<a href="mailto:$addr\@mit.edu">$addr\@mit.edu</a>.
If you send mail, please include the URL you tried to access in
the message you send so the owner of the page can fix the problem more
easily.</p>
UCONTACT
} else {
   print <<WCONTACT;

<p>Perhaps you'd like to try our <a href="/storyfun">StoryFun service</a> instead... <hr>

<p>Please direct questions to <a href="/comment">stuffmaster\@mit.edu</a> </p>
WCONTACT
}

print <<HTTPTAIL;
</body>
</html>
HTTPTAIL

exit 0;
