=head1 NAME

CFX5::Parallel::PvmHosts - PVMhosts file manipulation

=head1 SYNOPSIS

This package contains routines for reading and writing PVMhosts files.

=cut

package CFX5::Parallel::PvmHosts;

use strict;

use vars qw($CVSVersion);
$CVSVersion='$Id$ ';

use CFX5::Parallel::Host;

=head2 CLASS METHODS

=head3 write

  CFX5::Parallel::PvmHosts->write($file, $ccldb, @hosts);

Writes a PVMhosts file for the provided list of hosts, which should be
host names.

=cut

sub write {
  my $self=shift;

  my $file=shift;
  my $ccldb=shift;
  my @hosts=@_;

  return '' unless CFX5::FileTests::datafile_w($file, "PVM hosts file $file");

  local *FILE;

  unless (open FILE, ">$file") {
    _error("Unable to open PVM hosts file $file: $!");
    return '';
  }

  print FILE "# PVM hosts file automatically generated from CFX-5 host database\n";

  for my $hr (@hosts) {
    # what sort of element is this one?  This case probably won't be
    # triggered, but I leave it here just in case.  The ARRAY form is
    # the output from some of the methods in CFX5::Parallel which need
    # to count partitions.
    my ($h);
    if (ref($hr) and ref($hr) eq 'ARRAY') {
      # [count,host]
      $h=$hr->[1];
    } elsif (ref $hr) {
      $h = $hr;
    } else {
      $h = CFX5::Parallel::Host->new($ccldb, $hr);
    }

    # suppress DNS lookups via this object, as if the host doesn't
    # exist, failure can take a while.  This will make checks against
    # the local host fail unless we already know the local host's
    # identity, which is likely (?).
    $h->suppress_dns(1);

    my $args;

    my $e=$h->pvmd_path();
    if (defined $e and defined (my $p=$h->fill_in_exec($e))) {
      $args .= " dx=$p";
    }
    if (defined $h->username()) {
      $args .= " lo=" . $h->username();
    }
    if ($args) {
      print FILE "&" , $h->pvmname(), $args, "\n";
    } else {
      print FILE "# ", $h->pvmname(), ": insufficient information in default configuration\n";
    }
  }

  unless (close FILE) {
    _error("Error writing to PVM hosts file $file: $!");
    return '';
  }

  1;
}


1;
