#!/usr/athena/bin/perl 
# Filename: autopilot.pl 
   
# Set a variable to the file name of the file with the 
# list of URLs 
$filename = "/var/www/data/autopilot/urllist"; 
   
# Set a variable to the number of lines in the file. 
# Our file has 7250 lines in it. 
$num_lines = `cat /var/www/data/autopilot/count`; 
   
# Figure out the browser type for the client 
$client_type = $ENV{'HTTP_USER_AGENT'}; 

# Break the client type into the program name and the version 
# number. 
$client_type =~ /^([^\/]*)\/([\d\.]*)/; 
$client_program = $1; 
$client_version = $2; 
   
   
# Initialize the random seed (don't worry about this) 
srand; 
# Find a random variable between 0 and the number of lines in 
# the file. This will be the line of the file that we return.
 
$which_line = int( rand( $num_lines ) );
 
# Open the file that has the list of URLs. Check to make sure it 
# opened properly.
 
if (open (LIST, $filename)) 
{
 
# The file opened fine.  Now find the line corresponding to 
# $which_line. 
# In order to do this, set up a loop to read in $which_line 
# lines. 
while( $current_line = <LIST> ) 
     { 
         $line_no++; 
         if ($line_no == $which_line) 
  { 
               last; 
  } 
  
     } 
     
  
         if ($line_no <  $which_line) 
     { 
         &return_error(); 
     } 
   

# Once we get to the end, close the file. 
close(LIST);
 
if($ENV{'QUERY_STRING'} =~ /(\d+)/){
	$n = $1;
}
else {
	$n = 10;
}
# $current_line should now contain the last line read. 
# If the client is Netscape 1.1 or higher, tell the client 
# to make the request every 10 seconds.
print("HTTP/1.0 302 Go here\n");
print("Refresh: $n; URL=http://stuff.mit.edu/cgi/autopilot?$n\n"); 
   
# Regardless of the browser type being used, return a 
# redirection
 
print ("Location: $current_line"); 
# Send the blank line to end the response. 

print "\n"; 
exit; 
} 
   
&return_error(); 
sub return_error 
{ 
   
# If there was an error, return an error status code. 
print "Status: 500 Internal Server Error\n"; 
# Return a Content Type along with the error. 
print "Content-Type: text/html\n"; 
# Print the blank line to end the response; 
print "\n"; 
# Print an error message 
print "<html>\n"; 
print "<head>\n"; 
print "<title>Autopilot Error</title>\n"; 
print "</head>\n"; 
print "<body>\n"; 
print "<h1>Autopilot was unable to retrieve a URL to     return.</h1>\n"; 
print "</body>\n"; 
print "</html>\n"; 
}     
exit; 
