: # *-*-perl-*-* 
    eval 'exec perl -S $0 "$@"'
    if $running_under_some_shell;
#
# CreateReplica,v 1.7 1995/08/17 17:14:13 hardy Exp
#  CreateReplica - Assumes the binary broker distribution is un-tarred in its 
#                  final directory, assumes that anonymous ftp has been set up,
#                  assumes that httpd is running.  From here, builds the state
#                  associated with a replica: a mirrord/floodd pair and configuration,
#                  and creates a Harvest Broker via the CreateBroker script.
#
#  Usage: CreateReplica
#
#  Erh-Yuan Tsai, erhyuant@catarina.usc.edu, February 1995

# debugging flag for fetching parameters from some site
$DEBUG_URL = 0;

$USAGE = "$0 options
options:
-h	This message.
-m	Creating replica for master site.
-l	Specify parameters locally without querying a remote site.
-g url	Get paramters from mirrord home page of a remote site.
        (-g http://harvest.cs.colorado.edu:4100/parameters)
\n";

if ( ! -f "/tmp/socket.ph" )
{
    print "Building socket.ph";
    &create_mk_socket_ph ("/tmp/$$.c");
    system ("cc /tmp/$$.c -o /tmp/$$.exec");
    system ("/tmp/$$.exec > /tmp/socket.ph");
    unlink ("/tmp/$$.c", "/tmp/$$.exec");
}
require '/tmp/socket.ph';
umask (022);
$version_no = "0.997";
$home = $ENV{'HOME'};

$whoami_cmd = "whoami";
$whoami_cmd = "/bin/whoami" if (-x "/bin/whoami");
$whoami_cmd = "/usr/bin/whoami" if (-x "/usr/bin/whoami");
$whoami_cmd = "/usr/ucb/whoami" if (-x "/usr/ucb/whoami");
chop($this_person = &grab_cmd_output("$whoami_cmd"));
$USER = $this_person;

$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_host_full, @x) = gethostbyname($this_host);

undef @x;

$configure_locally = 0;		# Don't use network configuration.  
				# Off by default
$As_Client = 1;			# default, run as a client

#
# Parse command line arguments.
#
&Getopts ('hmg:l');
if ($opt_h) { 
  print "$USAGE";
  exit (0);
}


print <<EOM;

  ----------------------------------------------------------------------
  ----------------------------------------------------------------------
	Welcome to the Harvest Broker Replication Creation Tool
	           (CreateReplica version $version_no)

                     !!!!!!!!!!STOP!!!!!!!!!! 
   BEFORE RUNNING THIS PROGRAM, YOU NEED TO COMPLETE THE FOLLOWING STEPS:
                     !!!!!!!!!!STOP!!!!!!!!!! 

   0. A. Run 'CreateReplica -h' for command usage 
      B. See http://excalibur.usc.edu/research/mirrord.html for a
         list of brokers that you can replicate and their parameter URLS 
         (e.g. CreateReplica -g http://harvest.cs.colorado.edu:4000/parameters )

   1. A. If the Harvest binary distribution is not installed on your system, 
	 then get it from http://harvest.cs.colorado.edu/harvest/gettingsoftware.html
	 DO NOT FOLLOW THE INSTRUCTIONS FOR INSTALLING HARVEST; simply untar the 
	 distribution into a convenient directory, such as /usr/local/harvest.
      B. If Harvest is already installed on your system, check that steps C & D
	 are in your .cshrc file and proceed to steps E & F.
      C. \$ setenv HARVEST_HOME /usr/local/harvest # The directory used in step A.
      D. \$ set path = (\$path \${HARVEST_HOME}/lib/broker)
      E. Edit \$HARVEST_HOME/cgi-bin/BrokerQuery.pl.cgi and substitute your 
	 perl path name for /usr/local/bin/perl on line 1 
      F. Edit \$HARVEST_HOME/cgi-bin/BrokerQuery.pl.cgi and substitute \$HARVEST_HOME
         as needed on line: \$ENV{'HARVEST_HOME'} = "/usr/local/harvest";

   2. Install an httpd. If none is available,  check 
         ftp://ftp.cs.colorado.edu/pub/distribs/harvest/INSTRUCTIONS.html#step2
      for more information about using different httpds with Harvest.

      If you are using the NCSA httpd, modify it as follows:

      A. Append the following line to /usr/local/etc/httpd/conf/srm.conf 
         ScriptAlias /Harvest/cgi-bin/ /usr/local/etc/harvest/cgi-bin/
      B. Add a symbolic link to where your new harvest broker (e.g. www-home-pages) runs 
	 \$ ln -s \${HARVEST_HOME}/brokers/www-home-pages /usr/local/etc/httpd/htdocs/Harvest
    
   3. Install anonymous FTP, if not already installed.  Note that the anonymous
      FTP, httpd, and broker replica can each run on different machines if 
      the directories can be named across machines.

   4. A. Create a directory for your replica's data:
	 \$ cd ~ftp/pub/$USER; mkdir www-home-pages; )
      B. Change the ownership of www-home-pages to the account from which the
	 replicator is run.
	 \$ chown $USER www-home-pages

   5. If you changed your path or HARVEST_HOME variables, then kill this 
      script ^C and execute it again.
  ----------------------------------------------------------------------
  ----------------------------------------------------------------------
EOM

# ' Fake out font-lock mode.

$inpt{"YorN"} = "<CR>";
&ask_ans("Hit carriage return to continue", "YorN");
print "\n";

# Continue parse command line arguments.
# Create a master site
if ($opt_m) { 
  $As_Client = 0; 
  # assume configure locally
  $configure_locally = 1;
}

# query master's parameters from a remote url
if ($opt_g)
{
    $group_master_url = $opt_g;
    print "Group_master_url = $group_master_url\n";
}

# without query remote site
if ($opt_l)
{
    $configure_locally = 1;
}

if (! $configure_locally && ! $opt_g)
{
    &get_default_url ("http://excalibur.usc.edu/research/mirrord.html");
}

# Hopefully we retrieve the group master url.

if (! $configure_locally)
{
    if ($group_master_url)
    {	
	print "Initializing defaults from $group_master_url\n";
	&init_replica_vars_from_url ($group_master_url);
	&init_replica_master ();
    }
    else
    {
	die ("Failed to get master URL for group configuration");
    }
}

# try to verify if user setup its environment
if ($As_Client) { &verify_settings ();}

print <<EOM;

   This script prompts you for many details.  If you make a mistake,
   just ignore it for now and continue to answer the remaining 
   questions.  You will be given an oportunity to confirm and edit
   your answers.

EOM

$inpt{"YorN"} = "<CR>";
&ask_ans("Hit carriage return to continue", "YorN");

# check any running program that we are about to create new one.
# if exist, prompt user to stop them.
if ($As_Client) { &check_running_broker ();}
&check_running_floodd ();
&check_running_mirrord ();
if ($As_Client) { &check_running_glimpse ();}

&init_broker_vars ();

if ($As_Client) {
  &get_input_for_broker ();
  &installing_broker ();

  # parameters for calling BrokerRestart
  $broker_restart = &get_restart_param ();
}
else {
  $broker_restart = "";
}

# initialize the replica parameters
if ($group_master_url) {
    &init_replica_master ();
} elsif ($configure_locally) {
    &init_replica_vars ();
} else {
    &init_replica_from_url ();
}

# the first time user input data
$first_input = 1;
while (1) {
  &get_input_for_replica ();
  &replica_print_info();

  $inpt{"YorN"} = "yes";
  &ask_ans("Is this information correct?", "YorN");
  last if ($inpt{"YorN"} =~ /^y/io);
  print "Please go through the prompts again, and change any values that are incorrect\n";
  $first_input = 0;
}

&installing_replica ();

exit 0;
# << Program ended here >>
# -------------------------------------------------------------------

# try to verify if user follow the instruction to set up its environment
sub verify_settings {
  local ($tmp, $i, $broker_lib_path, $cgi);
  local (@my_path);
  local ($error_flag) = 0;

  # check $HARVEST_HOME 
  if ($ENV{'HARVEST_HOME'} eq "") {
    &warning ("It appears that you did not setenv \$HARVEST_HOME correctly.");
    return;
  }

  # check $HARVEST_HOME/lib/broker in path 
  $broker_lib_path = "$ENV{'HARVEST_HOME'}/lib/broker";
  #$broker_lib_path =~ tr+\/+\\/+;
  @my_path = split (/:/, $ENV{'PATH'});
  $error_flag = 1;
  for ($i = 0; $i < scalar(@my_path); ++$i) {
    if ($my_path[$i] =~ /^[\b]*$broker_lib_path[\b]*$/) {
	$error_flag = 0;
	last;
    }
  }
  if ($error_flag > 0) {
    &warning ("It appears you did not set \$HARVEST_HOME/lib/broker in your path correctly?");
  }

  # check $HARVEST_HOME directory 
  unless (-d $ENV{'HARVEST_HOME'}) {
    &warning ("Did you restore harvest binary distribution on $ENV{'HARVEST_HOME'}?");
    return;
  }

  # check $HARVEST_HOME/cgi-bin/BrokerQuery.pl.cgi 
  $cgi = "$ENV{'HARVEST_HOME'}/cgi-bin/BrokerQuery.pl.cgi";
  if (-f $cgi) {
    open (cgi_file,"$cgi") || die "Can't read $cgi\n";
    while (<cgi_file>) {
      if ($_ =~ /^\$ENV\{\'HARVEST_HOME\'\}[\s]*=[\s]*(\S*)\;/) {
        # remove " if any
	$tmp = $1;
	$tmp =~ s/\"//g;
        unless ($tmp eq "$ENV{'HARVEST_HOME'}") {
          print "\nThis line occurs in $cgi\n$_";
          &warning ("It appears that  $ENV{'HARVEST_HOME'}/cgi-bin/BrokerQuery.pl.cgi does not reference HARVEST_HOME correctly.");
        }
        last;
      }
    }
    close (cgi_file);
  }
  else {
    &warning ("Can't find $cgi?");
  }


}

sub warning {
  local ($in);

  print "WARNING: $_[0]\n";
  print "Press return key to continue or ctl-c to abort.\n\n";
  $in = <STDIN>;
}

# -------------------------------------------------------------------
# To run CreateBroker, we must purge out the first 3 lines
# and the exit, otherwise we won't be able to return from CreateBroker.
# a new tempory file new_broker.xxx is created for this purpose,
# then execute it by 'do new_broker.xxx' and remove it after running.

sub exec_CreateBroker {
  local ($broker) = "$inpt{'harvest_dir'}/bin/CreateBroker";
  local ($new_broker) = "$inpt{'harvest_dir'}/bin/new_broker.xxx";

  open (SCRIPT,"$broker") || die "open $broker fail!\n";
  open (aa,">$new_broker") || die "Write $new_broker fail!\n";
  # purge out first 3 lines
  <SCRIPT>;
  <SCRIPT>;
  <SCRIPT>;

  while (<SCRIPT>) {
    # purge out comments
    if ($_ =~ /^[\b]*#.*/) {$_ = ""; };
    # remove exit line
    if ($_ =~ /.*exit.*/) { $_ = "";  };
    # break out those code for 'add a collection point'
    if ($_ =~ /add a collection point/) { $_ = "last;"; }
    # This is *DISGUSTING*
	if ($_ =~ /^[ \t]*\$vals\{\"Broker-Name\"\}[ \t]*=[ \t]*/)
	{
	    $_ = "\$vals{\"Broker-Name\"} =\"$inpt{'group_description'}\";\n";
	}

	if ($_ =~ /^[ \t]*\$vals\{\"Broker-Short-Name\"\}[ \t]*=[ \t]*/)
	{
	    $_ = "\$vals{\"Broker-Short-Name\"} =\"$inpt{'group_name'}\";\n";
	}

	if ($_ =~ /^[ \t]*\$vals\{\"Broker-Port\"\}[ \t]*=[ \t]*/)
	{
	    $_ = "\$vals{\"Broker-Port\"} =\"$inpt{'broker_port'}\";\n";
	}
 
    print aa $_;
  }
  close (aa);

  do $new_broker;
  if ($@ ne "") { print "ERROR: $@ \n";}
  `rm -f $new_broker`;
}
# -------------------------------------------------------------------

# check if there is already a running broker there
sub check_running_broker {
  local ($ps, $pids);

  # check if any broker is running
  $ps = `ps wwx | awk \'\$5 ~ /^.*broker\$/\'`;
  if ($ps ne "") {
    print "There is a running broker...\n$ps";
    $pids = `echo "$ps" | awk \'{print \$1}\'`;
    $pids =~ tr/\n/ /;
    $inpt{"YorN"} = "yes";
    &ask_ans("Do you want to kill this broker?", "YorN");
    if ($inpt{"YorN"} =~ /^y/io) {
      &exec_cmd ("kill -9 $pids");
    }
  }
}

# check if there is already a running floodd there
sub check_running_floodd {
  local ($ps, $pids);

  # check if any floodd is running
  $ps = `ps wwx | awk \'\$5 ~ /^.*floodd\$/\'`;
  if ($ps ne "") {
    print "There is a running floodd...\n$ps";
    $pids = `echo "$ps" | awk \'{print \$1}\'`;
    $pids =~ tr/\n/ /;
    $inpt{"YorN"} = "yes";
    &ask_ans("Do you want to kill this flood-deamon?", "YorN");
    if ($inpt{"YorN"} =~ /^y/io) {
      &exec_cmd ("kill -9 $pids");
    }
  }
}

# check if there is already a running mirrord there
sub check_running_mirrord {
  local ($ps, $pids,$ps2);

  # check if any mirrord is running
  $ps = `ps wwx | awk \'\$5 ~ /^.*mirrord\$/\'`;
  $ps2 = `ps wwx | awk \'\$5 ~ /^perl\$/ && \$6 ~ /^.*mirrord\$/\'`;
  $ps = $ps . $ps2;
  if ($ps ne "") {
    print "There is a running mirrord...\n$ps";
    $pids = `echo "$ps" | awk \'{print \$1}\'`;
    $pids =~ tr/\n/ /;
    $inpt{"YorN"} = "yes";
    &ask_ans("Do you want to kill this mirrord-deamon?", "YorN");
    if ($inpt{"YorN"} =~ /^y/io) {
      &exec_cmd ("kill -9 $pids");
    }
  }
}

# check if there is already running glimpse-server there
sub check_running_glimpse {
  local ($ps, $pids,$ps2);
 
  # check if any glimpserver is running
  $ps = `ps wwx | awk \'\$5 ~ /^.*glimpseserver\$/\'`;
  if ($ps ne "") {
    print "There is a running glimpseserver...\n$ps";
    $pids = `echo "$ps" | awk \'{print \$1}\'`;
    $pids =~ tr/\n/ /;
    $inpt{"YorN"} = "yes";
    &ask_ans("Do you want to kill this running glimpseserver?", "YorN");
    if ($inpt{"YorN"} =~ /^y/io) {
      &exec_cmd ("kill -9 $pids");
    }
  }
}

# ----------------- BROKER ------------------------------

sub init_broker_vars {

  # environment variable must be setup before running
  # or else harvest defaults to /usr/local/harvest
  if ($ENV{'HARVEST_HOME'} ne "") {
    $inpt{"harvest_dir"} = $ENV{'HARVEST_HOME'};
  }
  else {
      $inpt{"harvest_dir"} = "/usr/local/harvest";
  }

  unless (-d $inpt{"harvest_dir"}) {
    die "HARVEST_HOME: $inpt{'harvest_dir'} missing!\n";
  }
}

sub get_input_for_broker {
}

sub installing_broker {

  # public the harvest disrectory
  if ($inpt{"harvest_dir"} ne "") {
  print <<EOM;
-------------------------------------------------------------------
  Making your \$HARVEST_HOME world-readable, in case your httpd and
  broker are running as different users.
-------------------------------------------------------------------
EOM
;
    &exec_cmd ("chmod -R a+rX $inpt{'harvest_dir'}");
  }

  print <<EOM;

  Below, you will be asked to give 'a one-word name for your Broker'.
  This script will create the sub-directory 
  \$HARVEST_HOME/brokers/the-name-you-gave.
  If this directory exists, move it elsewhere now.

EOM
;
  $inpt{"YorN"} = "Press any key to continue";
  &ask_ans("Running CreateBroker to create your replicated broker", "YorN");

  &exec_CreateBroker ();
  $inpt{'group_name'} = $vals{'Broker-Short-Name'};
  $inpt{'group_description'} = $vals{'Broker-Name'};
  $inpt{'broker_dir'} = "$inpt{'harvest_dir'}/brokers/$inpt{'group_name'}";
  $inpt{'broker_port'} = $vals{'Broker-Port'};

  print "group_name: $inpt{'group_name'}\n";
  print "group_description: $inpt{'group_description'}\n";
  print "broker_port: $inpt{'broker_port'}\n";
  print "===== Broker installed =====\n";
  print <<EOM;
-------------------------------------------------------------------
   You can start broker now or later by
     $inpt{'broker_dir'}/RunBroker
-------------------------------------------------------------------
EOM
;
  $inpt{"YorN"} = "yes";
  &ask_ans("Start broker now (although the data will take time to arrive)?", "YorN");
  if ($inpt{'YorN'} =~ /^y/io) {
    print ">>Running new broker $inpt{'broker_dir'}/RunBroker\n";
    &exec_cmd ("$inpt{'broker_dir'}/RunBroker");
  }
}

sub get_restart_param {
  local ($restart_para);

  # build parameters for BrokerRestart
  $restart_para = "";
  if ($vals{'Broker-Password'} ne "") {
    $restart_para =  "-password $vals{'Broker-Password'} ";
  }
  $restart_para = "$restart_para $vals{'Broker-Host'} $vals{'Broker-Port'} ";

  return ($restart_para);
}

# ------------------ REPLICA ----------------------------------------

sub init_replica_vars {

  # get ftp root directory, if it isn't set, give out warning
  # and set default to /usr/local/ftp/
  $ftp_directory = &absolute_path ("~ftp");
  print "FTP directory: $ftp_directory\n";
  if ($ftp_directory eq "") {
    $ftp_directory = "/usr/local/ftp/";
    print "Warning: \~ftp is not found, default to $ftp_directory\n";
    $inpt{'dummy'} = "Control-C to abort";
    &ask_ans ("Press any key to continue ","dummy");
    print "\n";
    delete $inpt{'dummy'};
  }

  $inpt{'replica_email'} = "$this_person\@$this_host_full";


  # restore mirrord source from distribution file.
  $inpt{"untar_mirrord"} = "yes";

#  $inpt{"mirrord_src"} = $home . "/mirrord.tar.gz";
  $inpt{"mirrord_home"} = $home . "/mirrord-dist";
  $inpt{"replica_dir"} = "$inpt{'harvest_dir'}/replicas";
  $inpt{'longitude'} = "0";
  $inpt{'lattitude'} = "0";

  if ($As_Client) {
    $inpt{'my_host'} = $this_host_full;
    $inpt{'master_site'} = "harvest.cs.colorado.edu";
  } else {
    $inpt{'master_site'} = $this_host_full;
  }

  $inpt{'group_name'} = "www-home-pages";
  $inpt{'ftp_anonymous'} = "pub/$USER/www-home-pages";
  if ($As_Client) {
    $inpt{'myDataPort'} = "4106";
    $inpt{'myClientPort'} = "4105";
  }
  $inpt{'masterDataPort'} = "4106";
  $inpt{'masterClientPort'} = "4105";
  $inpt{'mirrord_port'} = "4100";
}

sub init_replica_master {

  &init_replica_vars ();
  $inpt{'group_name'} = &return_field_value ($parameters, "GroupName:");
  $inpt{'group_description'} = &return_field_value ($parameters, "Description:");
  $inpt{'ftp_anonymous'} = "pub/$USER/$inpt{'group_name'}";
  $inpt{'master_site'}  = &return_field_value ($parameters, "MasterSite:");
  if ($As_Client) {
    $inpt{'myDataPort'}   = &return_field_value ($parameters, "FlooddDataPort:");
    $inpt{'myClientPort'} = &return_field_value ($parameters, "FlooddClientPort:");
  }
  $inpt{'masterDataPort'} = &return_field_value ($parameters, "FlooddDataPort:")
;
  $inpt{'masterClientPort'} = &return_field_value ($parameters, "FlooddClientPort:");
  $inpt{'mirrord_port'} =  &return_field_value ($parameters, "MirrordPort");
  $inpt{'broker_port'} =  &return_field_value ($parameters, "BrokerPort");

}

sub init_replica_from_url {

  local ($gp) = $inpt{'group_name'};
  &init_replica_vars ();
  $inpt{'group_name'} = $gp;
  $inpt{'ftp_anonymous'} = "pub/$USER/$gp";

  $inpt{'master_site'} = &parser_host ($parameters,$gp,'mirrord-html');
  $inpt{'masterDataPort'} = &parser_port ($parameters,$gp,'floodd-data');
  $inpt{'masterClientPort'} = &parser_port ($parameters,$gp,'floodd-html');
  $inpt{'mirrord_port'} = &parser_port ($parameters,$gp,'mirrord-html');
}

sub parse_parameter 
{
    local ($parameters, $group, $field) = @_;
    

}
# parser the line like this
# www-home-pages  mirrord-html http://harvest.cs.colorado.edu:4000

sub parser_host 
{
  $_ = &parser_url_value (@_);
  local ($protocol, $host, $port) = /(.*):\/\/([a-zA-Z0-9\.\-\/]+):(.*)/;
  return ($host);
}

sub parser_port
{
  $_ = &parser_url_value (@_);
  local ($protocol, $host, $port) = /(.*):\/\/([a-zA-Z0-9\.\-\/]+):(.*)/;
  return ($port);
}

sub parser_url_value
{
    local ($parameters, $group_name, $field) = @_;
    local (@lines) = split (/\n/, $parameters);
    local ($line, $ret_val);

    foreach $line (@lines) {
       local ($group, $html, $url) = split (/[ \t]+/,$line);
       if ($group eq $group_name && $html eq $field) {
	  $ret_val = $url;
	  last;
       }
    }

    return $ret_val;
}



sub get_input_for_replica {

  # if user wants to restore source from .tar.gz then ask full path name
  # otherwise ask user for the directory of source
  print <<EOM;

   We are now ready to build the mirror-d replication tool.
   It will be compiled in ~/mirrord-dist.

EOM

# CreateReplica is bundled to mirrord.tar.gz
#
#  &ask_ans ("Do you want to compile mirrord.tar.gz from source?",
#	"untar_mirrord");
#
#  if ($inpt{"untar_mirrord"} =~ /^y/io) {
#      do {
#	  &ask_ans ("Enter full path for mirrord.tar.gz (\'~\' accepted)\n",
#		    "mirrord_src"); # 
#	  $inpt{"mirrord_src"} = &absolute_path ($inpt{"mirrord_src"});
#	  unless (-f $inpt{"mirrord_src"}) { # 
#	      print "Error: Cannot find file $inpt{'mirrord_src'}\n";
#	  }			# 
#      }  while ( ! -f $inpt{"mirrord_src"});
#    delete $inpt{"mirrord_home"};
#  }
#  else {
    do {
	&ask_ans ("Enter directory of mirrord source (\'~\' accepted)\n",
		  "mirrord_home");
	$inpt{"mirrord_home"} = &absolute_path ($inpt{"mirrord_home"});
	unless (-d $inpt{"mirrord_home"}) {
	    print "Error: Cannot find directory $inpt{'mirrord_home'}\n";
	}
    }  while ( ! -d $inpt{"mirrord_home"});
#    delete $inpt{"mirrord_src"};
#  }

  &ask_ans ("Enter group name for this replica", "group_name");
  if ($configure_locally || ! $first_input) {
    &ask_ans ("Enter a one line description of the group", "group_description");
  }
  &ask_ans ("Enter replica working directory (\'~\' accepted)\n",
		"replica_dir");
  $inpt{"replica_dir"} = &absolute_path ($inpt{"replica_dir"});
  # if that director isn't existing, prompt user to create
  if (-d $inpt{'replica_dir'} ) {
     print <<EOM;
-------------------------------------------------------------------
  The directory $inpt{'replica_dir'} EXISTS,
  It will be OVERWRITTEN or specify a different directory.
-------------------------------------------------------------------
EOM
;
  }

  &ask_ans("Enter replica maintainer email address",
           "replica_email");

  if ($As_Client) {
    &ask_ans ("Enter your domain name", "my_host");
  }

  if ($configure_locally || ! $first_input) {
    &ask_ans ("Enter master site domain name", "master_site");
    &ask_ans ("Enter mirrord port", "mirrord_port");
    $inpt{'masterClientPort'} = $inpt{'mirrord_port'} + 5;
    $inpt{'masterDataPort'} = $inpt{'mirrord_port'} + 6;

    &ask_ans ("Enter master floodd-client port", "masterClientPort");
    &ask_ans ("Enter master floodd-data port", "masterDataPort");

    &ask_ans ("Enter the broker port", "broker_port");
  }
  if ($As_Client) {
    &ask_ans ("Enter your replica floodd-data port", "myDataPort");
    &ask_ans ("Enter your replica floodd-client port", "myClientPort");
  }

  $inpt{'ftp_anonymous'} = "pub/$USER/$inpt{'group_name'}";

  &ask_ans ("Enter your replica directory as seen from anonymous ftp\n",
	    "ftp_anonymous");
  # remove it if 1st character is '/'
  if ($inpt{'ftp_anonymous'} =~ /^\/(.*)/) {
       $inpt{'ftp_anonymous'} = $1;
  }

  $inpt{'ftp_local'} = "$ftp_directory/$inpt{'ftp_anonymous'}";
  &ask_ans ("Confirm your FTP directory local to file system\n",
	    "ftp_local");
  $inpt{"ftp_local"} = &absolute_path ($inpt{"ftp_local"});

  unless (-d $inpt{"ftp_local"}) {
    print "WARNING: $inpt{'ftp_local'} DOES NOT EXIST! GO CREATE IT NOW\n";
    print "Press any key to continue...\n";
    $in = <STDIN>;
  }

  print <<EOM;
-------------------------------------------------------------------
   Next you will be asked for location's lattitude and longitude. 
   You can check them by `telnet martini.eecs.umich.edu 3000'     
   or just press enters.					  
-------------------------------------------------------------------
EOM
;
  $inpt{"YorN"} = "no";
  &ask_ans("Do you want to \'telnet martini.eecs.umich.edu 3000\'", "YorN");
  if ($inpt{"YorN"} =~ /^y/io) {
    &exec_cmd_no_err_chk ("telnet martini.eecs.umich.edu 3000");
  }
  &ask_ans ("Enter your lattitude", "lattitude");
  &ask_ans ("Enter your longitude", "longitude");

}

sub installing_replica {

  # executable file name  called by mirrord to restart broker
  if ($As_Client) {
    $update_exec = "$inpt{'replica_dir'}/$inpt{'group_name'}/restart_broker";
  }

  chdir ($home);
# CreateReplica is bundled to mirrord.tar.gz
#
#  if ($inpt{"untar_mirrord"} =~ /^y/io) {
#    print ">>Getting directory name of mirrord source\n";
#    print "gzip -cd $inpt{'mirrord_src'} | tar -tf - | head -1\n";
#    $inpt{"mirrord_home"} = `gzip -cd $inpt{'mirrord_src'} | tar -tf - | head -1\n`;
#    chop ($inpt{"mirrord_home"});
#    $inpt{"mirrod_home"} = "$home/$inpt{'mirrord_home'}";
#
#    # restore mirrord source dir to your root
#    print ">>Restoring mirrord source to your home directory\n";
#    &exec_cmd ("gzip -cd $inpt{'mirrord_src'} | (umask 022;tar -xf -)");
#  }

#   &exec_cmd ("touch $inpt{'mirrord_home'}/scripts/\*\.in");

  print ">>Configuring mirrord/floodd to $inpt{'replica_dir'}\n";
  chdir ($inpt{"mirrord_home"}) || die "Fail to chdir $inpt{'mirrord_home'}\n";
  print "Changing directory to $inpt{'mirrord_home'}\n";
  &exec_cmd ("configure --prefix=$inpt{'replica_dir'}");
  &exec_cmd ("make");
  &exec_cmd ("make install");

# Make sure the group directory exists.
  $a_dir = "$inpt{'replica_dir'}/$inpt{'group_name'}";
  mkdir ($a_dir, 0755) unless ( -d $a_dir);

  chdir ("$a_dir") || die "Fail to chdir $a_dir";
  print "Changing directory to $a_dir\n";
  print "Creating replica configuration file replica.conf\n";
  &create_replica_conf ("replica.conf");
  print "New replica.conf created\n";

  if ($As_Client) {
    print ">>Setting up Replica for $inpt{'my_host'}";
    &exec_cmd ("$inpt{'replica_dir'}/bin/fd-config -s $inpt{'my_host'} -c replica.conf  > floodd-config");
  } else {
    print ">>Setting up Replica for $inpt{'master_site'}";
    &exec_cmd ("$inpt{'replica_dir'}/bin/fd-config -s $inpt{'master_site'} -c replica.conf  > floodd-config");
    &create_new_version ("new-version");
  }

  &create_run_replica ("RunReplica");
  $root_dir = "$inpt{'replica_dir'}/$inpt{'group_name'}";
  chdir ("$root_dir") || die "Fail to chdir $root_dir\n";
  &create_mirrord_conf ("mirrord.conf");
  print "New mirrord.conf created.\n";
  &create_replica_params ("replica.params");
  print "New replica.params created.\n";

  # public directory
  chmod 0755, "$root_dir";
  # public the configuration files
  chmod 0644, 'mirrord.conf', 'replica.conf', 'replica.params', 'floodd-config';
  &exec_cmd ("cp $inpt{'mirrord_home'}/mirror/socket.ph $inpt{'replica_dir'}/lib/perl/");


  if (! $As_Client) {
    print ">>Copying VERSION file to ftp directory\n";
    &exec_cmd ("rm -f $inpt{'ftp_local'}/VERSION");
    &exec_cmd ("sed -e s/MASTER-SITE/$inpt{'master_site'}/ -e s/REPLICA-NAME/$inpt{'group_name'}/ $home/mirrord-dist/examples/VERSION.ex.in > $inpt{'ftp_local'}/VERSION");
    &exec_cmd ("chmod 644 $inpt{'ftp_local'}/VERSION");
  }

  $root_dir = "$inpt{'replica_dir'}/$inpt{'group_name'}";
  chdir ("$root_dir") || die "Fail to chdir $root_dir\n";
  # start floodd
  $inpt{"YorN"} = "yes";
  &ask_ans("Do you want to start flood-daemon (yes you do) ?", "YorN");
  if ($inpt{"YorN"} =~ /^y/io) {
    `$inpt{'replica_dir'}/bin/floodd`;
  }

  if ($As_Client) { $md_cmd = "../bin/mirrord &";}
  else { $md_cmd = "../bin/mirrord -m &"; }

  print <<EOM;
---------------------------------------------------------
   You might wish to wait for an hour or so before your 
   start mirrord. It will not hurt anything if you start
   mirrord right away, but the topology generated at	
   this time will not be very good since the flood-d	
   tool will not have had time to build up good 	
   estimates of the available bandwidth between replicas
   I.e. you might find your replica mirroring off of a	
   very suboptimal neighbor.				
   To start mirrord:					
     1. cd $inpt{'replica_dir'}/$inpt{'group_name'}
     2. $md_cmd
---------------------------------------------------------
EOM
;

  # start mirrord
  $inpt{"YorN"} = "yes";
  &ask_ans("Do you want to start mirror-daemon (yes you do) ?", "YorN");
  if ($inpt{"YorN"} =~ /^y/io) {
    if ($As_Client) {
      `perl $inpt{'replica_dir'}/bin/mirrord > /dev/null &`;
    } else {
      `perl $inpt{'replica_dir'}/bin/mirrord -m > /dev/null &`;
    }
  }

  chdir ($home);

  print<<EOM;
---------------------------------------------------------
   Once mirrord is installed, you can safely delete	
   mirrord source directory				
---------------------------------------------------------
EOM
;
  $inpt{"YorN"} = "no";
  &ask_ans("Do you want to remove mirror source (up to you) ?", "YorN");
  if ($inpt{"YorN"} =~ /^y/io) {
    &exec_cmd ("rm -rf $inpt{'mirrord_home'}");
  }
  
  if ($As_Client) {
    print <<EOM;
---------------------------------------------------------
   Creating a executable file 
	$update_exec
   It is executed by mirrord to restart broker when 
   replicated files are transfered and ready for indexing.
---------------------------------------------------------
EOM
;
    &create_update_exec ($update_exec);

    # if replica already got files then let's trigger indexing
    &trigger_indexing ();
  }


  if ($As_Client) {
  print <<EOM;
---------------------------------------------------------
   To check your running replica & broker,			
   You may run Mosaic and open the floodd or mirrord URL:	
   http://$inpt{'my_host'}:$inpt{'myClientPort'}
   http://$inpt{'my_host'}:$inpt{'mirrord_port'}
   The new Broker's home page is:                      
   http://$vals{'HTTP-Host'}/Harvest/brokers/$vals{'Broker-Short-Name'}/query.html
 							
   Thank you for using mirrord replicating services.	
---------------------------------------------------------
EOM
;
# ' Fake out font-lock-mode
  }
  else {
  print <<EOM;
---------------------------------------------------------
   To check your running replica,			
   You may run Mosaic and open the floodd or mirrord URL:	
   http://$inpt{'master_site'}:$inpt{'masterClientPort'}
   http://$inpt{'master_site'}:$inpt{'mirrord_port'}
 							
   Thank you for using mirrord replicating services.	
---------------------------------------------------------
EOM
;
  }
}

# -------------------------------------------------------------------

sub replica_print_info {
  print<<EOM;

  ----------------------------------------------------------------------
EOM
;
  foreach $key (sort keys(%inpt)) {
    next if ($key eq "YorN");
    printf "%21s: ", $key;
    print $inpt{$key};
    print "\n";
  }

  print<<EOM;

  ----------------------------------------------------------------------
EOM
;
}

# asking user to input value, press enter to accept default one.
sub ask_ans {
	local($prompt, $tag) = @_;

	$default_value = $inpt{$tag};
	print $prompt, " [$default_value]: ";
	$in = <STDIN>;
	chop($in);
	$inpt{$tag} = $in if ($in !~ /^\s*$/io);
}

# return an absolute path if a name begins with "~"
sub absolute_path {
  local ($pwdir);

  ($abs_path) = @_;
  if ( $abs_path =~ /^~(\w*)(\/\S+)?/ ) { # name begins with ~
     $user = $1;
     $file_path= $2;
     if ($user eq "") {
       return ("$ENV{'HOME'}$file_path");
     }
     else {
	 $userdir = (getpwnam($user))[7];
	 return ("$userdir$file_path");
     }
  }
  elsif ($abs_path =~ /^([\.]+)(\/\S+)?/) { # relative path
    $pwdir = `pwd`;
    chop ($pwdir);
    if ($1 eq ".") {
      return ("$pwdir$2");
    }
    if ($1 eq "..") {
      return ("$pwdir/$abs_path");
    }
  }
  else {	# normal one, just bypass.
    return ("$abs_path");
  }
}

sub  check_exec_err {
  if ($? != 0) {
    print "Execution error!\n";
    $inpt{"YorN"} = "yes";
    &ask_ans("Do you want to abort?", "YorN");
    if ($inpt{"YorN"} =~ /^y/io) {
      exit ($? >> 8);
    }
  }
}

sub exec_cmd {
  local ($cmds) = @_;

  print "$cmds\n";
  system ("$cmds");
  &check_exec_err ();
}

sub exec_cmd_no_err_chk {
  local ($cmds) = @_;

  print "$cmds\n";
  system ("$cmds");
}

# ===============================================================

sub create_replica_conf {
  local ($fname) = @_;

  #ugly hack for master site
  if (! $As_Client) {
    $inpt{'my_host'} = $inpt{'master_site'};
    $inpt{'myDataPort'} = $inpt{'masterDataPort'};
    $inpt{'myClientPort'} = $inpt{'masterClientPort'};
  }

  open (CONFIGFILE,">$fname") || die "fail to create $fname!\n";
  select (CONFIGFILE);
print <<EOM;
#
# A sample configuration file to be processed by fd-config.
###########
# STEP 0: #
###########
# Read this short intro, and then follow the other steps (hint: look
# for thing in all CAPS).
#
# With some simple editing, you should be able to join an exisitng group.
# Since we are joining a group, it is assumed that we are not the master.
# You will need to find the port numbers the master is using as well as
# address.  Hopefully that is all you need to do.
#
# Suggests steps are marked.

# Who this sample run is to be generated for.  This should be able to
# be overridden using a command line flag.

###########
# STEP 0.5: #
###########
# Edit this appropriately

Host $inpt{'my_host'}


############################################################################
#			    DEFAULTS AREA.				   #
############################################################################


# By setting parameters here, before you define any replicas, you
# can set defaults for all of the replica.
#
# When editing path names, if a path name does not begin with a '/'
# the value of the "Directory" parameter is prepended to it when it is
# processed.

# Edit the following to change the default settings.
# YOUR ROOTDIRECTORY should not be `${HOME}/mirrord'.  The RootDirectory should
# be by itself.  The replica with have its own directory with its
# own bin, lib, and data.
#
RootDirectory		$inpt{'replica_dir'}/$inpt{'group_name'}
#BinDirectory		\${RootDirectory}/bin
#LibDirectory		\${RootDirectory}/lib
#DataDirectory		\${RootDirectory}/data
BinDirectory		$inpt{'replica_dir'}/bin
LibDirectory		$inpt{'replica_dir'}/lib
DataDirectory		$inpt{'replica_dir'}/data

# Defaults for site parameters.  Hopefully you won't need to change these.
#
DataPort		$inpt{'myDataPort'}
ClientPort		$inpt{'myClientPort'}

#
# Defaults for group parameters
# You might want to check with the master to see
# what these values should be set to.
Connectivity		3	# number of neighbors for the topology
EstimatesPeriod 	600	# send B/W and RTT estimates every 10 minutes
JoinPeriod		900	# send join message every 15 minutes
PingPeriod		300	# estimate RTT every 5 minutes
BandwidthPeriod 	900	# estimate RTT every 15 minutes
UpdatePeriod		1800	# Send out topology updates every 1/2 hour
TopologyGenerator	\${BinDirectory}/tpcal

#
# Defaults for local parameters
#

DataStorageMax		524288		# Maximum data storage allowed (512K).
LogPurgePeriod		600		   # 10 minutes

#
# Not used yet.
# DebugLevel		 0
# DebugFlag		-g

############################################################################
#		       REPLICA DEFINITION AREA				   #
############################################################################

###########
# STEP 1: #
###########

# Define the master site..  By default this will be set to the current host.
# We need to minimally define the curren thost to be in the gruop.
#
# Edit these values to reflect the appropriate values for the master
<Replica		$inpt{'master_site'}>
<Site>
# Uncomment these if you want to change something for this site only.
DataPort		$inpt{'masterDataPort'}
ClientPort		$inpt{'masterClientPort'}
</Site>
<Local>
</Local>
</Replica>

EOM
;

# only client needs this part of configuration
if ($As_Client) {
print <<EOM;
###########
# STEP 2: #
###########

#
# Now edit the local values for your local host
#
<Replica		$inpt{'my_host'}>
# DataDirectory 	\${RootDirectory}/$inpt{'group_name'}
<Site>
SiteLongitude		$inpt{'longitude'}
SiteLattitude		    $inpt{'lattitude'}
<Local>
AuxillaryInfo		"Mirror Daemon <A HREF=http://$inpt{'my_host'}:$inpt{'mirrord_port'}/>$inpt{'my_host'}</A>"
</Replica>

EOM
;
}
# end of cleint only configuration

print <<EOM;
# Now we want to define a group
# We now need to specify the group members.  This does not have to include
# all the members, but it must include at least the local site and
# on other site.

############################################################################
#			GROUP DEFINITION AREA				   #
############################################################################

###########
# STEP 3: #
###########

<Group				$inpt{'group_name'}>

###########
# STEP 4: #
###########

# Edit the initial group members.  We don't need to know about all
# members at the start, just enough to get us started.
# You can use `\\'s to continue lines
EOM
;
if ($As_Client) {
print <<EOM;
Members 			$inpt{'master_site'} \\
				$inpt{'my_host'}
EOM
;
} else {
print <<EOM;
Members 			$inpt{'master_site'} 
EOM
;
}

print <<EOM;
# Define the group master
Master				$inpt{'master_site'}

TopologyGenerator		\${BinDirectory}/tpcal
</Group>


EOM
;
  close (CONFIGFILE);
  select (STDOUT);
}

# ===============================================================

sub create_mirrord_conf {
  local ($fname) = @_;

  open (CONFIGFILE,">$fname") || die "fail to create $fname!\n";
  select (CONFIGFILE);
print  <<EOM;
# Configuration file for mirrord

#
# Edit the entries as needed to configure your local mirrord
#

<HOST>
$inpt{'my_host'}
</HOST>

<PORT>
$inpt{'mirrord_port'}
</PORT>

<LOCAL-DIRECTORY>
$inpt{'ftp_local'}
</LOCAL-DIRECTORY>

# This is the above directory as seen from anonymous ftp
<FTP-DIRECTORY>
$inpt{'ftp_anonymous'}
</FTP-DIRECTORY>

# Specify the user name by which other replicas will get your data
# This should usually be 'ftp' unless you want to pass passwords
# around in the clear.
<USER>
ftp
</USER>

# Where to keep basic admin and log files

<ADMIN-DIRECTORY>
$inpt{'replica_dir'}/$inpt{'group_name'}
</ADMIN-DIRECTORY>

<MIRROR-PROG>
$inpt{'replica_dir'}/lib/perl/mirror.pl
</MIRROR-PROG>

# Run run mirror with debugging flags and skip the mirrord.defaults file.
<MIRROR-ARGS>
-N -d -d -d
</MIRROR-ARGS>

# This should be our local floodd daemon.  We need to talk to the flood
# daemon to get a list of of our neighbors.
#
<FLOOD>
$inpt{'my_host'}:$inpt{'myClientPort'}
</FLOOD>

# We will need to obtain a 'VERSION' file to get the version number of the
# archive and the mirror configuration spec.
# This is the path name as it is visible on the local file system.
<VERSION-FILE>
$inpt{'ftp_local'}/VERSION
</VERSION-FILE>

# Visible to ftp
<FTP-VERSION-FILE>
$inpt{'ftp_anonymous'}/VERSION
</FTP-VERSION-FILE>

# Update command, called when data is ready for reindexing
<UPDATE-COMMAND>
$update_exec
</UPDATE-COMMAND>

<MAINTAINER>
$inpt{'replica_email'}
</MAINTAINER>


EOM
;
  close (CONFIGFILE);
  select (STDOUT);
}

sub create_replica_params {
  local ($fname) = @_;

  open (CONFIGFILE,">$fname") || die "fail to create $fname!\n";
  select (CONFIGFILE);
print <<EOM;
<GroupName>
$inpt{'group_name'}
</GroupName>
<Description>
$inpt{'group_description'}
</Description>
<GroupMaster>
$inpt{'master_site'}
</GroupMaster>
<DataPort>
$inpt{'myDataPort'}
</DataPort>
<ClientPort>
$inpt{'myClientPort'}
</ClientPort>
<MirrordPort>
$inpt{'mirrord_port'}
</MirrordPort>
# Ports for use by the harvest broker.
<BrokerPort>
$inpt{'broker_port'}
</BrokerPort>

EOM
;
  close (CONFIGFILE);
  select (STDOUT);
}



# ===============================================================
sub create_run_replica {
  local ($fname) = @_;

  open (CONFIGFILE,">$fname") || die "fail to create $fname!\n";
  select (CONFIGFILE);
  print <<EOM;
#!/bin/sh
EOM
    ;
if (!$As_Client)
{
    print <<EOM;
# Run the broker
$inpt{'broker_dir'}/RunBroker
EOM
    ;
}

print <<EOM
# Now run the mirroring stuff 
cd $inpt{'replica_dir'}/$inpt{'group_name'}
# Run the Broker
cd $inpt{'replica_dir'}/bin/floodd
../bin/mirrord 2>&1 > LOG &
EOM
;
  close (CONFIGFILE);
  select (STDOUT);
}

sub create_mk_socket_ph {
  local ($fname) = @_;
  open (TMPFILE,">$fname") || die "fail to create $fname!\n";
  select (TMPFILE);
  print <<EOM
/* Generate a minimal socket.ph.  Hopefully this will work on just about
 * anything.
 * Perl sucks.
 * Stolen from the harvest  (http://harvest.cs.colorado.edu) distribution.
 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>


main ()
{
  printf ("if (!defined &_sys_socket_h) {\\n");
  printf ("    eval 'sub _sys_socket_h {1;}';\\n");
  printf ("    eval 'sub SOCK_STREAM {%d;}';\\n",  SOCK_STREAM);
  printf ("    eval 'sub SOCK_DGRAM {%d;}';\\n",   SOCK_DGRAM);
  printf ("    eval 'sub SOCK_RAW {%d;}';\\n",     SOCK_RAW);
  printf ("    eval 'sub SOL_SOCKET {%d;}';\\n",     SOL_SOCKET);
  printf ("    eval 'sub SO_REUSEADDR {%d;}';\\n",     SO_REUSEADDR);

  printf ("    eval 'sub AF_UNIX {%d;}';\\n",      AF_UNIX);
  printf ("    eval 'sub AF_INET {%d;}';\\n",      AF_INET);
  printf ("    eval 'sub PF_UNIX {%d;}';\\n",      PF_UNIX);
  printf ("    eval 'sub PF_INET {%d;}';\\n",      PF_INET);
  printf ("}\\n");
  printf ("1;\\n");
 
  exit (0);

}
EOM
;
close (TMPFILE);
select (STDOUT);

}

sub create_new_version {
  local ($fname) = @_;

  open (CONFIGFILE,">$fname") || die "fail to create $fname!\n";
  select (CONFIGFILE);
  print <<EOM;
#!/bin/sh
# Create a new version
  PERLLIB=$inpt{'replica_dir'}/lib/perl
  export PERLLIB
  $inpt{'replica_dir'}/bin/new-version -p $inpt{'mirrord_port'}
EOM
;
  close (CONFIGFILE);
  chmod 0755, "$fname";
  select (STDOUT);
}

sub create_update_exec {
  local ($fh);
  local ($fname) = @_;
  local ($log_file) = "$fname.log";

# This script is created by CreateReplica.
# mirrord executes this script when files are transfered and
# ready for indexing.
# 1.This script will make soft links from broker to replica, if
#   it is not linked yet.
# 2.This script will start broker if it is not running.
# 3.Finally, it executes BrokerRestart to command broker to
#   perform indexing.

  open (CONFIGFILE,">$fname") || die "fail to create $fname!\n";
  select (CONFIGFILE);
print <<EOM;
: # *-*-perl-*-* 
    eval 'exec perl -S \$0 "\$@"'
    if \$running_under_some_shell;


open (logger,">>$log_file");
&logging ("started");

# if Registry file isn't linked then build link to replica
\$src = "$inpt{'ftp_local'}/admin/Registry";
\$dest = "$inpt{'broker_dir'}/admin/Registry";
unless (-l \$dest) {
  # make sure the source exist
  if (-f \$src) {
    &run_cmd("rm -f \$dest");
    &run_cmd("ln -s \$src \$dest");
    &run_cmd("chmod +w \$src");
  }
}

# build link for objects if not built yet.
\$src = "$inpt{'ftp_local'}/objects";
\$dest = "$inpt{'broker_dir'}/objects";
unless (-l \$dest) {
  # make sure the source exist
  if (-d \$src) {
    &run_cmd("rm -rf \$dest");
    &run_cmd("ln -s \$src \$dest");
  }
}

# check if any broker is running, if not, start it
\$ps = &run_cmd("ps x | awk \'\\\$5 ~ /^.*broker\\\$/\'");
if ("\$ps" eq "") {
  &run_cmd("$inpt{'broker_dir'}/RunBroker");

  # broker need time to read Registry and build data structure
  # wait about 5 min before calling BrokerRestart
  &logging ("Sleep 300 seconds waiting broker on line");
  sleep (300);
}

# call BrokerRestart
&run_cmd("$inpt{'harvest_dir'}/lib/broker/BrokerRestart $broker_restart &");

&logging ("Done");
close (logger);
exit (0);

sub logging {
  local (\$the_time) = `date +'%m/%d %H:%M:%S'`;
  chop (\$the_time);

  print logger "\$the_time\\t\$_[0]\\n";
}

sub run_cmd {
  local (\$cmd) = \@_;
  local (\$result) = `\$cmd`;

  if (\$? != 0) {
    &logging ("\$cmd\\nError:\$result");
  }
  else {
    &logging ("\$cmd\\n");
  }
  return (\$result);
}

EOM
;
  close (CONFIGFILE);
  select (STDOUT);
  `chmod a+x $fname`;
}

# if replica has files ready then trigger broker fro indexing
sub trigger_indexing {
  local ($ps);
  
  $src1 = "$inpt{'ftp_local'}/admin/Registry";
  $dest1 = "$inpt{'broker_dir'}/admin/Registry";
  $src2 = "$inpt{'ftp_local'}/objects";
  $dest2 = "$inpt{'broker_dir'}/objects";

  # if files are there then continue otherwise return
  if (-f $src1 && -d $src2) {
    print <<EOM;
-------------------------------------------------------------------
  The ftp directory already has files there. If you answer 'yes' to 
  the following prompt, it will 
  1. make soft links from broker to ftp directroy.
  2. start broker, if it is not running.
  3. run BrokerRestart to command broker for re-indexing files.
-------------------------------------------------------------------
EOM
;

   $inpt{"YorN"} = "yes";
   &ask_ans("Do you want to execute above steps?", "YorN");
    unless ($inpt{"YorN"} =~ /^y/io) { return; }
  }
  else {
    return;
  }

  unless (-l $dest1 || -l $dest2) {
    # make sure the source exist
    if (-f $src1 && -d $src2) {
      &exec_cmd("rm -f $dest1");
      &exec_cmd("ln -s $src1 $dest1");
      &exec_cmd("chmod +w $src1");

      &exec_cmd("rm -rf $dest2");
      &exec_cmd("ln -s $src2 $dest2");
    }
  }

  # if files aready there try to start broker and trigger indexing
  if (-l $dest1 && -l $dest2) {
    # check if any broker is running, if not, start it
    $ps = `ps x | awk \'\$5 ~ /^.*broker\$/\'`;
    if ("$ps" eq "") {
      print ">>Starting broker\n";
      &exec_cmd("$inpt{'broker_dir'}/RunBroker");
      print ">>Sleep 300 seconds waiting for broker on line\n";
      sleep (300);
    }
    # call BrokerRestart
    print ">>Command broker to perform indexing files\n";
    &exec_cmd("$inpt{'harvest_dir'}/lib/broker/BrokerRestart $broker_restart &");
  }
}
 






# 
# Networking code.  Fetch configuration paramters from the net.
#


sub init_replica_vars_from_url {
    local ($url) = @_;

    $_= &return_url ($url) || die ("Could not fetch $url\n");

    # clean the junk out of the url
    s/<[A-Za-z0-9\-=:\"\'\/ ]+>//g;

    $parameters = $_;
    if ($DEBUG_URL) {
      print "PARAMS: $parameters\n";
    }
}
#
# Get a default url that points to known groups.
#
sub get_default_url {
    local ($url) = @_;

    print "Querying the list of brokers from $url\n";
    $_= &return_url ($url) || die ("Could not fetch $url\n");

    # clean the junk out of the url
    s/<[A-Za-z0-9\-=:\"\'\/\. ]+>//g;

    $parameters = $_;

    local (@lines) = split (/\n/, $parameters);
    local (@url_list) = grep (/ParameterURL:|Description:/, @lines);

    $parameters = "";
    foreach $group (@url_list)
    {
  	print "$group\n";
        $parameters = $parameters . "$group\n";
    }

    local ($first_group) = split (/ /,$url_list[0]);
    $inpt{'group_name'} = $first_group;
    &ask_ans ("Please enter the group you would like to join:",
		"group_name");

    #check if user specifies a good name
    foreach $group (@url_list) {
      local ($gp, $field, $rest) = split(/[ \t]+/,$group);
      if ($gp eq $inpt{'group_name'} && $field eq "ParameterURL:") 
      { 
	  $group_master_url = $rest;
	  print "ParameterURL: $rest\n";
	  return; 
      }
    }
    &warning ("$inpt{'group_name'} is not existing!");
}

sub
return_field_value 
{
    local ($parameters, $field) = @_;
    local (@lines) = split (/\n/, $parameters);

    local ($_) =     grep (/$field/, @lines);

    local ($value) = /$field[: ]*(.*)/;
    return $value;
}

sub
read_response
{
    local ($SOCKET) = @_;
    local ($ret_value);
    local ($stuff);
    local ($/) = -1;
    while ($stuff = <$SOCKET>)
    {
	$ret_value .= $stuff;
    }
    return $ret_value;
}


#
# return a simple http: url
#
sub
return_url
{
    local ($_) = @_;
    local ($ret_value);
    local ($protocol, $host, $rest) = /(.*):\/\/([a-zA-Z0-9\.\-:]+)(\/.*)/;

    if ($DEBUG_URL) {
      print "URL: $url\n";
      print "HOST: $host\n";
      print "REST: $rest\n";
    }
    local ($file, $message) = &connect_to_site ($host);
    die ("Could not connect to $site: $message\n") if ($message);
    # More stupid perl magic
    select ($file); $| = 1; select (STDOUT);

    print "Retrieving...\n";

    print $file "GET $rest\n";

    $ret_value = &read_response ($file);
    if ($DEBUG_URL) { print "returned: $ret_value\n";}
    return $ret_value;
}


#
# Establish a tcp connection to a named site.  The site can be of the form
# domainname[:portnumber].
#
sub
connect_to_site
{
    local ($site) = @_;
    local ($remote_host, $port) = split (/:/, $site);
# some definitions for sockets.
    local ($sockaddr) = 'S n a4 x8';

    if ($DEBUG_URL) {
	print "AF_INET = $AF_INET\n";
	print "SOCK_STREAM = $SOCK_STREAM\n";
    }

    if ($remote_host eq '')
    {
	return ('', "No Hostname specified");
    }
 
    if ($port eq '')
    {
	$port = 80;
    }
    local ($SOCKET) = ++$connect_number;

    local ($name, $aliases, $proto) = getprotobyname ('tcp');

    if ($DEBUG_URL) {
      print "Proto = $proto\n";
    }


    local ($name, $aliases, $port) = getservbyname ($port, 'tcp')
	unless $port =~ /^\d+$/;;

    local ($name, $aliases, $type, $len, $local_inet) =
	gethostbyname ($local_host);

    local ($name, $aliases, $type, $len, $remote_inet) = 
	gethostbyname ($remote_host);

    local ($local_addr) = pack ($sockaddr, &AF_INET, 0, $local_inet);
    local ($remote_addr) = pack ($sockaddr, &AF_INET, $port, $remote_inet);

    if ($DEBUG_URL) {
	printf "AF_INET %d SOCK_STREAM %d\n", &AF_INET, &SOCK_STREAM;
    }

    socket ($SOCKET, &AF_INET, &SOCK_STREAM, $proto) ||
	return ('', "Could not create socket: $!\n");

    setsockopt($SOCKET, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1));

    local ($result) = bind ($SOCKET, $local_addr);
    if (!$result)
    {
	close ($SOCKET),
	return ('', "Could not bind socket: $!");
    }

    local ($result) = connect ($SOCKET, $remote_addr);
    if (! $result)
    {
	close ($SOCKET);
	return ('', "Could not connect to $remote_host:$port: $!\n");
    }
    return ($SOCKET, '');
}
 
#
# ===============================================================
#
#  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;
}


;# getopts.pl - a better getopt.pl

;# Usage:
;#      do Getopts('a:bc');  # -a takes arg. -b & -c not. Sets opt_* as a
;#                           #  side effect.

sub Getopts {
    local($argumentative) = @_;
    local(@args,$_,$first,$rest);
    local($errs) = 0;
    local($[) = 0;

    @args = split( / */, $argumentative );
    while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) {
	($first,$rest) = ($1,$2);
	$pos = index($argumentative,$first);
	if($pos >= $[) {
	    if($args[$pos+1] eq ':') {
		shift(@ARGV);
		if($rest eq '') {
		    ++$errs unless @ARGV;
		    $rest = shift(@ARGV);
		}
		eval "\$opt_$first = \$rest;";
	    }
	    else {
		eval "\$opt_$first = 1";
		if($rest eq '') {
		    shift(@ARGV);
		}
		else {
		    $ARGV[0] = "-$rest";
		}
	    }
	}
	else {
	    print STDERR "Unknown option: $first\n";
	    ++$errs;
	    if($rest ne '') {
		$ARGV[0] = "-$rest";
	    }
	    else {
		shift(@ARGV);
	    }
	}
    }
    $errs == 0;
}

