#!/usr/local/bin/perl
#############################################################################
# Sends users off to a random location ....                                 #
#                                                                           #
# usage: http://www.aquapal.co.uk/cgi-bin/jarandom.pl?file=urlfile          #
#                                                                           #
# where urlfile is a plain text file with one url per line                  #
#                                                                           #
# Copyright (c) 1997 Jason Anthony, janthony@aquapal.co.uk                  #
#                                                                           #
# http://www.aquapal.co.uk/jason.html                                       #
#############################################################################

my($version) = "1.0";
my(@urls);
my($numUrls);
my(@fields);
my($field);
my($key);
my($value);
my($fileName);
my($url);
my($i);

srand();

@fields = split( /&/, $ENV{'QUERY_STRING'} );

$fileName = "";
foreach $field (@fields) {
    ($key, $value) = split(/=/,$field);

    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;

    if ($key eq "file") {
        $fileName = $value;
    }
}

if ($fileName eq "") {
    print "Content-type: text/html\n\n";
    print "<HTML><HEAD><TITLE>Error</TITLE></HEAD>\n";
    print "<BODY BGCOLOR=\"#FFFFFF\">\n";
    print "<H1>Error</H1>\n";
    print "Usage: <STRONG>/cgi-bin/random.pl?file=name of url file</STRONG><P>\n";
    print "file format is one url per line<P><HR>\n";
    print "<FONT SIZE=\"1\">Copyright &copy 1997, <A HREF=\"http://www.aquapal.co.uk/jason.html\">Jason Anthony</A></FONT><P>\n";
    print "</BODY></HTML>\n";
} else {
    if (!(-e $fileName)) {
        print "Content-type: text/html\n\n";
        print "<HTML><HEAD><TITLE>Error</TITLE></HEAD>\n";
        print "<BODY BGCOLOR=\"#FFFFFF\">\n";
        print "<H1>Error</H1>\n";
        print "Error: file <STRONG>$fileName</STRONG> not found<P>\n";
        print "<FONT SIZE=\"1\">Copyright &copy 1997, <A HREF=\"http://www.aquapal.co.uk/jason.html\">Jason Anthony</A></FONT><P>\n";
        print "</BODY></HTML>\n";
    } else { 
        open( OPENFILE, $fileName );
        @urls = <OPENFILE>;
        close( OPENFILE );

        $numUrls = @urls;
# loop ten times, because random routine was a bit dodgy in earlier versions of perl.
        for($i=0;$i<10;$i++) {
            $url = @urls[int(rand($numUrls))];
            $url =~ s/\n//g;
            if (!($url eq "")) { last; }
        }
        if ($url eq "") { $url = "http://www.aquapal.co.uk/jason.html"; }
        print "Location: $url\n\n";
    }
}

