: # *-*-perl-*-*
    eval 'exec perl -S $0 "$@"'
    if $running_under_some_shell;  
#
#  Harvest - Main user interface to Harvest.
#  
#  Usage: Harvest [flags]
#  Flags:
#	-novice		Simplest Q&A.  Mostly uses the defaults.
#	-expert		Most flexible Q&A.  No defaults used. (default)
#	-glimpse	Use Glimpse for the Broker. (default)
#	-wais		Use WAIS for the Broker.
#	-dumbtty	Dumb TTY mode (default).
#	-cleantty	Clean TTY mode - clears screen, etc.
#	-debug		Debug mode.
#	-dont-run	Don't run the Broker or the Gatherer.
#	-fake		Doesn't build the Harvest servers.
#	-protect	Don't change the umask.
#
#  $Id: Harvest,v 1.85 1995/11/07 01:33:37 duane Exp $;
#
#######################################################################
#
#  Copyright (c) 1994, 1995.  All rights reserved.
#  
#    The Harvest software was developed by the Internet Research Task
#    Force Research Group on Resource Discovery (IRTF-RD):
#  
#          Mic Bowman of Transarc Corporation.
#          Peter Danzig of the University of Southern California.
#          Darren R. Hardy of the University of Colorado at Boulder.
#          Udi Manber of the University of Arizona.
#          Michael F. Schwartz of the University of Colorado at Boulder.
#          Duane Wessels of the University of Colorado at Boulder.
#  
#    This copyright notice applies to software in the Harvest
#    ``src/'' directory only.  Users should consult the individual
#    copyright notices in the ``components/'' subdirectories for
#    copyright information about other software bundled with the
#    Harvest source code distribution.
#  
#  TERMS OF USE
#    
#    The Harvest software may be used and re-distributed without
#    charge, provided that the software origin and research team are
#    cited in any use of the system.  Most commonly this is
#    accomplished by including a link to the Harvest Home Page
#    (http://harvest.cs.colorado.edu/) from the query page of any
#    Broker you deploy, as well as in the query result pages.  These
#    links are generated automatically by the standard Broker
#    software distribution.
#    
#    The Harvest software is provided ``as is'', without express or
#    implied warranty, and with no support nor obligation to assist
#    in its use, correction, modification or enhancement.  We assume
#    no liability with respect to the infringement of copyrights,
#    trade secrets, or any patents, and are not responsible for
#    consequential damages.  Proper use of the Harvest software is
#    entirely the responsibility of the user.
#  
#  DERIVATIVE WORKS
#  
#    Users may make derivative works from the Harvest software, subject 
#    to the following constraints:
#  
#      - You must include the above copyright notice and these 
#        accompanying paragraphs in all forms of derivative works, 
#        and any documentation and other materials related to such 
#        distribution and use acknowledge that the software was 
#        developed at the above institutions.
#  
#      - You must notify IRTF-RD regarding your distribution of 
#        the derivative work.
#  
#      - You must clearly notify users that your are distributing 
#        a modified version and not the original Harvest software.
#  
#      - Any derivative product is also subject to these copyright 
#        and use restrictions.
#  
#    Note that the Harvest software is NOT in the public domain.  We
#    retain copyright, as specified above.
#  
#  HISTORY OF FREE SOFTWARE STATUS
#  
#    Originally we required sites to license the software in cases
#    where they were going to build commercial products/services
#    around Harvest.  In June 1995 we changed this policy.  We now
#    allow people to use the core Harvest software (the code found in
#    the Harvest ``src/'' directory) for free.  We made this change
#    in the interest of encouraging the widest possible deployment of
#    the technology.  The Harvest software is really a reference
#    implementation of a set of protocols and formats, some of which
#    we intend to standardize.  We encourage commercial
#    re-implementations of code complying to this set of standards.  
#  
#
$VERSION = "1.4beta";
&init();
umask(022) if (!$do_protect);

if (!defined($ENV{'HARVEST_HOME'})) {
	print <<EOM;

WARNING:  You do not have your HARVEST_HOME environment variable set.

For now I will use the default HARVEST_HOME of '/usr/local/harvest'...
EOM
	sleep(10);
	$ENV{'HARVEST_HOME'} = "/usr/local/harvest";
}
$ENV{'EDITOR'} = "vi" if (!defined($ENV{'EDITOR'}));
$ENV{'TMPDIR'} = "/tmp" if (!defined($ENV{'TMPDIR'}));
$ENV{'PATH'} = $ENV{'PATH'} . ":" . "$ENV{'HARVEST_HOME'}/bin" .
			      ":" . "$ENV{'HARVEST_HOME'}/lib/gatherer". 
			      ":" . "$ENV{'HARVEST_HOME'}/lib/broker". 
			      ":" . "$ENV{'HARVEST_HOME'}/lib";

print "PATH=$ENV{'PATH'}\n" if ($debug);

$this_step = 1;
&clear_screen();
&welcome();
&clear_screen();
&local_www_server(); 		$this_step++;
&choose_configuration(); 	$this_step++;
&harvest_servers(); 		$this_step++;
&auto_registration(); 		$this_step++;
if ($do_build) {
	&build_servers();	$this_step++;
} else {
	print "Skipping Build.  You're running in fake mode.\n";
}
exit 0;	# END OF PROGRAM


sub welcome {
	print <<EOM;

  ######################################################################
  #                         Welcome to Harvest!                        #
  ######################################################################

   This program will create, configure, and run a Harvest Broker and
   Gatherer.  It will allow you to index one or more WWW, FTP, or Gopher
   servers, using a set of defaults for content extraction and indexing.  
   We offer 3 standard configurations:

         1. Index your entire WWW site.
         2. Index an entire WWW site (or sites).
         3. Index selected parts of WWW, FTP, or Gopher sites.

EOM
	&print_help();
	&continue();
	print<<EOM;

   You will be asked a few questions about what you want Harvest to do,
   and about a few basic details of your WWW, FTP, or Gopher server(s).
   You'll need several megabytes of disk space to run these Harvest 
   servers; the amount of disk space needed depends on the size of the 
   servers that you're indexing.  If you are uncertain these questions, 
   then stop now and contact your server administrator.

   This program is broken down into 4 question and answer sessions. 
   Based on your answers, it will create and configure Harvest servers.
   It will also set up your system to run the Harvest servers regularly.

   A comprehensive user's manual is available for Harvest via WWW at:

         http://harvest.cs.colorado.edu/harvest/doc.html

EOM
	&continue();
	&warn_novice() if (!$expert);
}

sub print_help {
	print <<EOM;
   NOTE: When this program asks you a question, you can accept the 
         default answer shown within the square brackets [ ]'s by 
         pressing ENTER, or you can enter your own answer.

EOM
}

sub warn_novice {
	print <<EOM;

   You are running this program as a Novice user.  Therefore, we're
   assuming that your WWW server is http://$this_dns_host/.

EOM
	&continue();
}

#  Clears the screen if possible
sub clear_screen {
	system("/usr/ucb/clear") if (-x "/usr/ucb/clear" && $do_clear);
}

#  Asks the user to continue or not.  Exits on "no"
sub continue {
	$vals{"YorN"} = "yes";
	&get_ans("Do you want to continue?", "YorN");
	print "\nGood-bye.\n", exit 0 if ($vals{"YorN"} !~ /^y/io);
}

#  Pauses until the user hits enter
sub pause {
	print "Press ENTER to continue...";
	$garbage = <STDIN>;
	undef $garbage;
}

#  Gets an answer from the user
sub get_ans {
	local($prompt, $tag) = @_;

	$default_value = $vals{$tag};
	if (length($prompt) + length($default_value) > 60) {
		print $prompt, ":\n\t", "[$default_value]: ";
	} else {
		print $prompt, " [$default_value]: ";
	}
	chop($in = <STDIN>);
	$vals{$tag} = $in if ($in !~ /^\s*$/io);
	print "CHOOSE: '$in'\n" if ($debug);
}

#
#  This is an ugly hack so that it works with Perl 4.036 on Solaris 2.3.
#  The backticks (`) don't work on Solaris like they should. -Darren.
#
sub grab_cmd_output {
	local($the_cmd) = @_;
	undef $the_var;
	unlink("/tmp/cmdoutput.$$");
	system("$the_cmd > /tmp/cmdoutput.$$");
	open(CMDOUT, "< /tmp/cmdoutput.$$") || return "none";
	$the_var = <CMDOUT>;
	close(CMDOUT);
	unlink("/tmp/cmdoutput.$$");
	return $the_var;
}

sub local_www_server {
	print <<EOM;
----------------------------------------------------------------------
STEP $this_step: Describe your local WWW server.
----------------------------------------------------------------------

   The Harvest Broker requires that you have access to a WWW server 
   (e.g., httpd).  If you don't currently run a WWW server, then you
   will need to install and configure one before you can run Harvest.

EOM
	$vals{'Local-WWW-Host'} = $this_dns_host;
	$vals{'Local-WWW-Port'} = 80;

	&get_ans("On which host does your WWW server run?",
		"Local-WWW-Host") if ($expert);
	&get_ans("On which port does your WWW server run?",
		"Local-WWW-Port") if ($expert);

	print "No questions needed for novice mode.\n" if (!$expert);
}

sub choose_configuration {
	while (1) {
		$vals{'Standard-Configuration'} = 1;
		print <<EOM;

----------------------------------------------------------------------
STEP $this_step: Select a standard configuration.
----------------------------------------------------------------------

   We offer 3 standard configurations:

         1. Index your entire WWW site.
         2. Index an entire WWW site (or sites).
         3. Index selected parts of WWW, FTP, or Gopher sites.

EOM
		&get_ans("Please select a configuration", 
			   "Standard-Configuration");
		if ($vals{'Standard-Configuration'} eq "1" ||
	            $vals{'Standard-Configuration'} eq "2" ||
	            $vals{'Standard-Configuration'} eq "3") {
			last;
		} else {
			print "INVALID SELECTION.  Please try again.\n";
		}
	}
	if ($vals{'Standard-Configuration'} eq "1") {
		$vals{'Server-Short-Name'} = "$this_dns_host";
		$vals{'Server-Description'} = "Contents of the $vals{'Server-Short-Name'} WWW server";
	} elsif ($vals{'Standard-Configuration'} eq "2") {
		$vals{'Server-Short-Name'} = "none";
		$vals{'Server-Description'} = "none";
	} elsif ($vals{'Standard-Configuration'} eq "3") {
		$vals{'Server-Short-Name'} = "none";
		$vals{'Server-Description'} = "none";
	}
}

sub harvest_servers {
	print <<EOM;

----------------------------------------------------------------------
STEP $this_step: Configure your new Harvest servers.
----------------------------------------------------------------------

   To configure your Harvest Broker and Gatherer, answer the following:

EOM

	while (1) {
		&get_ans("Enter a short description of this Harvest server",
			"Server-Description");
		$vals{'Server-Description'} = $1
			if ($vals{'Server-Description'} =~ /^([^\n]*)\n/o);
		if ($vals{'Server-Description'} eq "none") {
			print "INVALID RESPONSE.  Please try again.\n";
		} else {
			last;
		}
	}
	while (1) {
		&get_ans("Enter a one-word description of this Harvest server",
			"Server-Short-Name");
		$vals{'Server-Short-Name'} = $1
			if ($vals{'Server-Short-Name'} =~ /^(\S+)\s+/o);
		if ($vals{'Server-Short-Name'} eq "none") {
			print "INVALID RESPONSE.  Please try again.\n";
		} else {
			last;
		}
	}

	$vals{'Gatherer-Directory'} = $ENV{'HARVEST_HOME'} .
		"/gatherers/" . $vals{'Server-Short-Name'};
	$vals{'Gatherer-Port'} = 8500;
	$vals{'Broker-Directory'} = $ENV{'HARVEST_HOME'} .
		"/brokers/" . $vals{'Server-Short-Name'};
	$vals{'Broker-Port'} = $vals{'Gatherer-Port'} + 1;
	$vals{'Broker-Password'} = "";

	&get_ans("Where do you want to install the Gatherer?",
		"Gatherer-Directory") if ($expert);
	&get_ans("On which port should the Gatherer run?",
		"Gatherer-Port") if ($expert);
	&get_ans("Where do you want to install the Broker?",
		"Broker-Directory") if ($expert);
	$vals{'Broker-Port'} = $vals{'Gatherer-Port'} + 1 if ($expert);
	&get_ans("On which port should the Broker run?",
		"Broker-Port") if ($expert);
	&get_ans("Enter a password for the Broker administrative commands",
		"Broker-Password");

	$vals{'Broker-Indexer'} = "Glimpse" if ($use_glimpse);
	$vals{'Broker-Indexer'} = "WAIS" if ($use_wais);
	$vals{'Broker-WAIS-Flavor'} = "freeWAIS Version 0.3" if ($use_wais);
	&get_ans("Which type of WAIS software are you using?",
		"Broker-WAIS-Flavor") if ($use_wais);
	$vals{'Broker-WAIS-Port'} = $vals{'Broker-Port'} + 1 if ($use_wais);

	if ($vals{'Standard-Configuration'} eq "1") {
 		$vals{'Gatherer-URLs'} = "http://" .  $vals{'Local-WWW-Host'};
 		$vals{'Gatherer-URLs'} .= ":" . $vals{'Local-WWW-Port'}
			if ($vals{'Local-WWW-Port'} ne "80");
		$vals{'Gatherer-URLs'} .= "/\n";
			
	} elsif ($vals{'Standard-Configuration'} eq "2") {
		print <<EOM;

Enter the hostnames of the WWW servers that you'd like to index.  Terminate
this list by entering a period ('.') on a line by itself.  If you want to use
a port number other than 80, then append it to the hostname with a colon
(e.g., "www.cs.colorado.edu:9000").
EOM
		$vals{'Gatherer-URLs'} = "";
		print "Enter hostname: ";
		while (<STDIN>) {
			chop;
			last if (/^\./o);
			$vals{'Gatherer-URLs'} .= "http://$_/\n" if (/\S+/o);
			print "Enter hostname: ";
		}
	} elsif ($vals{'Standard-Configuration'} eq "3") {
		print <<EOM;

Enter the list of URLs for the collections that you'd like to index.
The URLs that you enter below will be classified as 'RootNodes' and will 
be enumerated (e.g. by recursive FTP directory listings for FTP URLs).
Terminate this list by entering a period ('.') on a line by itself.
EOM
		$vals{'Gatherer-URLs'} = "";
		print "Enter URL: ";
		while (<STDIN>) {
			chop;
			last if (/^\./o);
			$vals{'Gatherer-URLs'} .= "$_\n" if (/\S+/o);
			print "Enter URL: ";
		}
	}
}

sub auto_registration {
	print <<EOM;

----------------------------------------------------------------------
STEP $this_step: Registration information about your Harvest servers.
----------------------------------------------------------------------

   We ask that you register your new Harvest servers with our global 
   registry.  Please answer the following short questions.  Later, 
   after the installation is complete, we will ask you if you'd like 
   to register your Harvest servers or not using the information that 
   you provide below.

EOM
	$vals{'Email-Address'} = $ENV{'USER'} . "\@" . $this_dns_host;
	&get_ans("Enter your correct Email address:", "Email-Address");
}


sub init {
	$| = 1;
	chop($today = &grab_cmd_output("date"));

	$hostname_cmd = "hostname";
	$hostname_cmd = "/usr/bin/hostname" if (-x "/usr/bin/hostname");
	$hostname_cmd = "/usr/ucb/hostname" if (-x "/usr/ucb/hostname");
	$hostname_cmd = "/bin/hostname" if (-x "/bin/hostname");
	chop($this_host = &grab_cmd_output("$hostname_cmd"));

	($this_dns_host, @x) = gethostbyname($this_host); undef @x;
	$this_dns_host = &verify_dns_host($this_dns_host);
	$vals{'Gatherer-Host'} = $this_dns_host;
	$soif{'Broker-Host'} = $this_dns_host;
	$do_run = 1;
	$do_clear = 0;
	$do_protect = 0;
	$do_build = 1;
	$expert = 1;
	$debug = 0;
	$use_wais = 0;
	$use_glimpse = 1;
	while ($_ = shift(@ARGV)) {
		$expert = 0 		if (/^-novice/o);
		$expert = 1 		if (/^-expert/o);
		$do_clear = 0 		if (/^-dumbtty/o);
		$do_protect = 1 	if (/^-protect/o);
		$do_clear = 1 		if (/^-cleantty/o);
		$do_build = 0 		if (/^-fake/o);
		$do_run = 0 		if (/^-dont-run/o);
		$debug = 1 		if (/^-debug/o);
		$use_wais = 1, $use_glimpse = 0 		
					if (/^-wais/o);
		$use_glimpse = 1, $use_wais = 0
			 		if (/^-glimpse/o);
	}
	$do_clear = 0 if ($debug);
}

#
#  build_servers - Create the Harvest server configuration files.
#
sub build_servers {
	print <<EOM;

----------------------------------------------------------------------
STEP $this_step: Create and run the Harvest servers.
----------------------------------------------------------------------

   Now, this program will create Harvest servers based on your input.
   Then, it will run the Harvest servers.

EOM
	if ($debug) {
		foreach $k (sort keys %vals) {
			print "$k: $vals{$k}\n";
		}
	}
	&create_gatherer();
	&create_broker();
	&run_gatherer() if ($do_run);
	&run_broker() if ($do_run);
	print "Done.\n";
	print <<EOM;

   Your Harvest Servers are now running.  To access them, refer to

       http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/brokers/$vals{'Server-Short-Name'}/summary.html

EOM
	&register();
}

sub create_broker {
	print "Creating the Broker...\n";
	$tmpfile = "$ENV{'TMPDIR'}/cbout.$$";
	open(CREATE, "| CreateBroker > $tmpfile") || 
		die "Cannot run CreateBroker: $!\n";
	#
	#  Run CreateBroker using the default Glimpse indexer
	#
	print CREATE <<EOM if ($use_glimpse);
$vals{'Server-Description'}
$vals{'Server-Short-Name'}
$vals{'Broker-Host'}
$vals{'Broker-Port'}
$vals{'Broker-Password'}
$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}
$vals{'Email-Address'}
description
glimpse
$ENV{'HARVEST_HOME'}/lib/broker/glimpse
$ENV{'HARVEST_HOME'}/lib/broker/glimpseindex
$ENV{'HARVEST_HOME'}/lib/broker/glimpseserver
$vals{'Broker-Host'}
$vals{'Broker-Directory'}
yes
yes
yes
$vals{'Gatherer-Host'}
$vals{'Gatherer-Port'}
3
yes
no
EOM
	#
	#  Run CreateBroker using the default WAIS indexer
	#
	print CREATE <<EOM if ($use_wais && $vals{'Broker-WAIS-Flavor'} =~ /freewais/io);
$vals{'Server-Description'}
$vals{'Server-Short-Name'}
$vals{'Broker-Host'}
$vals{'Broker-Port'}
$vals{'Broker-Password'}
$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}
$vals{'Email-Address'}
description
wais
no
$vals{'Broker-Host'}
$vals{'Broker-WAIS-Port'}



$vals{'Broker-Directory'}
yes
yes
yes
$vals{'Gatherer-Host'}
$vals{'Gatherer-Port'}
3
yes
no
EOM
	#
	#  Run CreateBroker using the WAIS Inc. indexer
	#
	print CREATE <<EOM if ($use_wais && $vals{'Broker-WAIS-Flavor'} !~ /freewais/io);
$vals{'Server-Description'}
$vals{'Server-Short-Name'}
$vals{'Broker-Host'}
$vals{'Broker-Port'}
$vals{'Broker-Password'}
$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}
$vals{'Email-Address'}
description
wais
yes
$vals{'Broker-Host'}
$vals{'Broker-WAIS-Port'}




$vals{'Broker-Directory'}
yes
yes
yes
$vals{'Gatherer-Host'}
$vals{'Gatherer-Port'}
3
yes
no
EOM
	close(CREATE);
	print "Successfully created the Broker!\n";
	system("/bin/cat $tmpfile") if ($debug);
	unlink($tmpfile);

	$sfile = "$vals{'Broker-Directory'}/summary.html";
	open(SUMMARY, "> $sfile") || die "Cannot write $sfile: $!\n";
	print SUMMARY <<EOM;
<HTML>
<head>
<title>Harvest Server Summary: $vals{'Server-Short-Name'}</title>
</head>
<body>
<h1>Harvest Server Summary</h1>
<p>
This is a summary for the Harvest Servers that index
<strong>$vals{'Server-Description'}</strong>.
</p>
<ul>
<li>
You can 
<a
href="http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/brokers/$vals{'Server-Short-Name'}/query.html">query</a>
the Broker.

<li>
You can 
<a href="http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/brokers/$vals{'Server-Short-Name'}/admin/admin.html">
administrate</a> the Broker.

<li>
You can view some
<a href="http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/brokers/$vals{'Server-Short-Name'}/stats.html">
statistics</a> about the Broker.

<li>
You can view some
<a href="http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/brokers/$vals{'Server-Short-Name'}/description.html">
descriptive information</a> about the Broker.

<li>
You can view the 
<a href="http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/gatherers/$vals{'Server-Short-Name'}/$vals{'Server-Short-Name'}.cf">Gatherer's workload</a>.

<li>
You can view the 
<a
href="http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/cgi-bin/HarvestGather.cgi?host=$vals{'Gatherer-Host'}\&port=$vals{'Gatherer-Port'}\&timestamp=0\&flag=">
Gatherer's database</a> <em>(may be very large!)</em>.
</ul>
<p>
For instructions on how to maintain your Harvest servers, see the 
<a href="http://harvest.cs.colorado.edu/harvest/doc.html">
Harvest User's Manual</a>.
</p>
</body>
</HTML>
EOM
	close(SUMMARY);
}

sub create_gatherer {
	print "Creating the Gatherer...\n";
	if (-d $vals{'Gatherer-Directory'}) {
		print "WARNING: There is already a Gatherer in the specified directory\n";
		print "(e.g., $vals{'Gatherer-Directory'}).\n";
		&continue();
	} else {
		mkdir($vals{"Gatherer-Directory"}, 0755) ||
			die "Cannot create $vals{'Gatherer-Directory'}: $!\n";
	}
	chmod(0755, $vals{'Gatherer-Directory'}) ||
		die "Cannot write to $vals{'Gatherer-Directory'}: $!\n"
		if (!-w $vals{"Gatherer-Directory"});

	$cffile = "$vals{'Gatherer-Directory'}/$vals{'Server-Short-Name'}.cf";
	print "CREATING: $cffile\n" if ($debug);
	open(CF, "> $cffile") || die "Cannot write $cffile: $!\n";
	print CF <<EOM;
#
#  $vals{'Server-Short-Name'}.cf - configuration file for the 
#  $vals{'Server-Description'} Gatherer
#
#  Created by $vals{'Email-Address'} on $today
#
EOM
	# this may have single quotes
	print CF "Gatherer-Name:\t", $vals{'Server-Description'}, "\n";
	print CF <<EOM;
Gatherer-Port:\t$vals{'Gatherer-Port'}
Top-Directory:\t$vals{'Gatherer-Directory'}

<RootNodes>
# Enter URLs for RootNodes here
$vals{'Gatherer-URLs'}
</RootNodes>

<LeafNodes>
# Enter URLs for LeafNodes here
</LeafNodes>
EOM
	close(CF);

	$pfile = "$vals{'Gatherer-Directory'}/RunGatherer";
	print "CREATING: $pfile\n" if ($debug);
	open(BIN, "> $pfile") || die "Cannot write $pfile: $!\n";
	print BIN <<EOM;
#!/bin/sh
#
#  RunGatherer - Runs the $vals{'Server-Description'} Gatherer
#
HARVEST_HOME=$ENV{'HARVEST_HOME'}; export HARVEST_HOME
PATH=\${HARVEST_HOME}/bin:\${HARVEST_HOME}/lib/gatherer:\${HARVEST_HOME}/lib:\$PATH
export PATH
cd $vals{'Gatherer-Directory'}
exec Gatherer "$vals{'Server-Short-Name'}.cf"
EOM
	close(BIN);
	chmod(0755, $pfile) || die "Cannot chmod $pfile: $!\n";

	$pfile = "$vals{'Gatherer-Directory'}/RunGatherd";
	print "CREATING: $pfile\n" if ($debug);
	open(BIN, "> $pfile") || die "Cannot write $pfile: $!\n";
	print BIN <<EOM;
#!/bin/sh
#
#  RunGatherd - Exports the $vals{'Server-Description'} Gatherer's database
#
HARVEST_HOME=$ENV{'HARVEST_HOME'}; export HARVEST_HOME
PATH=\${HARVEST_HOME}/lib/gatherer:\$PATH; export PATH
exec gatherd -d $vals{'Gatherer-Directory'}/data $vals{'Gatherer-Port'}
EOM
	close(BIN);
	chmod(0755, $pfile) || die "Cannot chmod $pfile: $!\n";

	print "Successfully created the Gatherer!\n";
	$vals{"YorN"} = "no";
	&get_ans("Would you like to edit the Gatherer's workload specification?", "YorN");
	if ($vals{'YorN'} =~ /^y/io) {
		system("$ENV{'EDITOR'} $cffile");
		print "\nOk.  Done editing.\n\n";
	}
}

sub run_gatherer {
	print "Running the Gatherer.\n";
	print "WARNING:  For large sites, this may take several hours...\n";
	$tmpfile = $ENV{'TMPDIR'} . "/rungather.$$";
	unlink($tmpfile);
	system("$vals{'Gatherer-Directory'}/RunGatherer > $tmpfile");
	system("/bin/cat $tmpfile") if ($debug);
	unlink($tmpfile);
	print "Done running the Gatherer!\n";
}

sub run_broker {
	print "Running the Broker.\n";
	print "WARNING:  For large sites, this may take several hours...\n";
	sleep(15);	# wait a little for Gatherer to start exporting...
	$tmpfile = $ENV{'TMPDIR'} . "/runbroker.$$";
	unlink($tmpfile);
	system("$vals{'Broker-Directory'}/RunBroker > $tmpfile");
	system("/bin/cat $tmpfile") if ($debug);
	unlink($tmpfile);
	print "Done running the Broker!\n";
}

sub register {
	$vals{"YorN"} = "yes";
	&get_ans("Would you like to register your Harvest servers now?", "YorN");
	if ($vals{"YorN"} =~ /^y/io) {
		&do_register_gatherer();
		&do_register_broker();
	}
	&join_mailing_list() if (! -r "$ENV{'HOME'}/.harvest-user");
}

sub join_mailing_list {
	$vals{"YorN"} = "yes";
	&get_ans("Would you ($vals{'Email-Address'}) like to join the harvest-users\@cs.colorado.edu mailing list (for software updates and other discussions, etc.)?", "YorN");
	return if ($vals{"YorN"} !~ /^y/io);
	$mailcmd = "/bin/mail";
	$mailcmd = "/bin/binmail" if (-x "/bin/binmail");
	open(MAIL, "| $mailcmd majordomo\@cs.colorado.edu $vals{'Email-Address'}") || 
		die "Cannot run $mailcmd: $!\n";
	print MAIL <<EOM;
To: majordomo\@cs.colorado.edu
Cc: $vals{'Email-Address'}
Subject: subscribe harvest-users

subscribe harvest-users $vals{'Email-Address'}

.
EOM
	close(MAIL);
	if (open(ACK, ">> $ENV{'HOME'}/.harvest-user")) {
		print ACK "Subscribed to harvest-users\@cs.colorado.edu.\n";
		close(ACK);
	}
}

sub do_register_gatherer {
	$tmpfile = "$ENV{'TMPDIR'}/soif.$$";
	$soiftype = "GATHERER";
	$soifurl = "http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/gatherers/$vals{'Server-Short-Name'}/$vals{'Server-Short-Name'}.cf";
	undef %soif;
	$soif{'Gatherer-Name'} = $vals{'Server-Description'};
	$soif{'Gatherer-Host'} = $vals{'Gatherer-Host'};
	$soif{'Gatherer-Port'} = $vals{'Gatherer-Port'};
	$soif{'Gatherer-Version'} = "$VERSION";
	$soif{'Maintainer'} = $vals{'Email-Address'};

	&print_soif();
	&mail_hsr();
	unlink($tmpfile);
	print "Registered your Gatherer with the Harvest Server Registry.";
}

sub do_register_broker {
	$tmpfile = "$ENV{'TMPDIR'}/soif.$$";
	$soiftype = "BROKER";
	$soifurl = "http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/brokers/$vals{'Server-Short-Name'}/query.html";
	undef %soif;
	$soif{'Broker-Name'} = $vals{'Server-Description'};
	$soif{'Broker-Host'} = $vals{'Broker-Host'};
	$soif{'Broker-Port'} = $vals{'Broker-Port'};
	$soif{'Broker-Version'} = "$VERSION";
	$soif{'Broker-Query-Page'} = "$soifurl";
	$soif{'Broker-Description-File'} = "http://$vals{'Local-WWW-Host'}:$vals{'Local-WWW-Port'}/Harvest/brokers/$vals{'Server-Short-Name'}/description.html";
	$soif{'Maintainer'} = $vals{'Email-Address'};

	&print_soif();
	&mail_hsr();
	unlink($tmpfile);
	print "Registered your Broker with the Harvest Server Registry.";
}

sub mail_hsr {
	# Send the template to the HSR
	open(MAIL, "| /bin/mail 'harvest+hsr\@transarc.com'") || 
		die "Cannot send mail to HSR: $!\n";
	print MAIL <<EOM;
To: harvest+hsr\@transarc.com
Subject: $soiftype Registration for $soifurl


EOM
	$uuencode = "uuencode";
	$uuencode = "/bin/uuencode" if (-x "/bin/uuencode");
	$uuencode = "/usr/bin/uuencode" if (-x "/usr/bin/uuencode");
	$uuencode = "/usr/ucb/uuencode" if (-x "/usr/ucb/uuencode");
	open(UUE, "$uuencode $tmpfile new.soif |") ||
		die "Cannot $uuencode SOIF: $!\n";
	while (<UUE>) {
		print MAIL;
	}
	close(UUE);
	print MAIL "\n\n.\n";
	close(MAIL);
}

sub print_soif {
	# Print the SOIF template to a tmpfile
	open(SOIF, "> $tmpfile") || die "Cannot write $tmpfile: $!\n";
	print SOIF "\@$soiftype { $soifurl\n";
	foreach $k (sort keys %soif) {
		print SOIF $k, "{", length($soif{$k}), "}:\t";
		print SOIF $soif{$k}, "\n";
	}
	print SOIF "}\n";
	close(SOIF);
}

#
#  Makes sure that the dns host is fully specified
#
sub verify_dns_host {
	local($thehost) = @_;
	return $thehost if ($thehost =~ /^.*\.(arpa|com|edu|gov|int|mil|nato|net|org|[a-z]{2,2})$/io);

	print <<EOM;

  WARNING: your hostname ($thehost) does not appear to be a 
  fully-qualified Internet hostname.  If you intend to register your
  server with the Harvest Server Registry (HSR) so that it can be
  located by other users around the Internet, we require fully-qualified
  host names.  Please enter your fully-qualified DNS host name below.  
  (You can peruse the HSR at http://harvest.cs.colorado.edu/HSR/)

EOM
	$vals{'DNS-HostName'} = "none";
	while ($vals{'DNS-HostName'} eq "none") {
	  &get_ans("Enter the fully-qualified DNS host name for $thehost", 
		 "DNS-HostName");
	}
	$thehost = $vals{'DNS-HostName'};
	delete $vals{'DNS-HostName'};	# don't need
	return $thehost;
}
