#!/usr/local/bin/perl
# *MUST* have this line above.  It won't work with httpd otherwise.
# -----------------------------------------------------------------
# Query.cgi
#
# USAGE: Query.cgi [list]
#
# A perl script to randomly redirect queries to a particular replica
# of a broker. HVhttp is a list of known replicas of the broker.  
# Each replica is represented by the URL of its query page.  A replica
# is selected at random with precedence given to the local replica.
# A redirect to the appropriate query page is returned.  If the argument
# "list" is present, a list of replicas is returned.
# -----------------------------------------------------------------
@HVhttp = (
  "/Harvest/brokers/@THIS_BROKER_SHORT_NAME@/query.html"
  @REPLICAS@
);

$HVname = "@THIS_BROKER_NAME@";

# -----------------------------------------------------------------
# CGIRedir -- Mime content header
# -----------------------------------------------------------------
sub CGIRedir {
    local($url) = @_;

    print "HTTP/1.0 302 Found\r\n";
    print "MIME-Version: 1.0\r\n";
    print "Location: $url\r\n";
    print "Content-Type: text/html\r\n";
    print "\r\n";
}

# -----------------------------------------------------------------
# CGIHeader -- Mime content header
# -----------------------------------------------------------------
sub CGIHeader {
    print "HTTP/1.0 200 OK\r\n";
    print "MIME-Version: 1.0\r\n";
    print "Content-Type: text/html\r\n";
    print "Content-Transfer-Encoding: binary\r\n";
    print "\r\n";
}

# -----------------------------------------------------------------
# HVreplicas -- Display a list of replicas for the user to select.
# -----------------------------------------------------------------
sub HVreplicas {
    local($url);

    &CGIHeader;
    
    $nlocs = $#HVhttp + 1;
    print STDOUT <<EOM;
<HTML>
<HEAD>
    <TITLE> $HVname Replicas </TITLE>
</HEAD>
<BODY>
<H1>$HVname Replicas</H1>
<HR>
This broker is replicated at $nlocs locations.  Please choose
one from the list below.
<P>
<DIR>
EOM

    foreach $url (@HVhttp) {
	print "<LI> <A HREF=\"$url\">$url</A>\n";
    }

    print <<EOM
</DIR>
</BODY>
</HTML>
EOM
}


# -----------------------------------------------------------------
# main()
# -----------------------------------------------------------------
srand();

if (@ARGV[0] eq "list") {
    &HVreplicas;
} elsif ($#HVhttp == 0) {
    &CGIRedir($HVhttp[0]);
} elsif (int(rand(2)) == 0) {
    &CGIRedir($HVhttp[0]);
} else {
    &CGIRedir($HVhttp[int(rand($#HVhttp + 1))]);
}
exit 0;		# END OF PROGRAM
