=head1 NAME

  CFX5::Parallel::Reqs::mpd_hosts - mpd.hosts generator for CFX-5 parallel

=cut

package CFX5::Parallel::Reqs::mpd_hosts;

use CFX5::Parallel::Reqs::Base;
push @ISA, qw(CFX5::Parallel::Reqs::Base);

use CFX5::Config qw(%Config);
use CFX5::Output qw(:all);

use CFX5::PkgLoader qw(cfx5_require);

use strict;

=head2 F<mpd.hosts> file functions

The calls in this section allow the reading and writing of various
host definition files.

=head3 write_mpdhosts_file

I<Internal>

  $self->write_mpdhosts_file($file, @hosts);
  $self->write_mpdhosts_file($file, @count_host);

Writes a set of records to a file in the normal mpd.hosts format.  The input
list is a list of CFX5::Parallel::Host objects.

=cut

sub write_mpdhosts_file {
  my $self=shift;
  my $file=shift;

  my @hosts=@_;

  return '' unless CFX5::FileTests::datafile_w($file, "CFX-5 hosts file $file");

  local *HSTFILE;

  unless (open HSTFILE, ">$file") {
    _error("Unable to open CFX-5 hosts file $file for writing: $!");
    return '';
  }

  for my $hr (@hosts) {
    my ($h);
    if (ref($hr) eq 'ARRAY') {
      # [count,host]
      $h=$hr->[1];
    } else {
      $h=$hr;
    }
    print HSTFILE $h->pvmname(),"\n";
  }

  unless (close HSTFILE) {
    _error("Error writing to CFX-5 hosts file $file: $!");
    return '';
  }

  1;
}

=head3 write_mpdhosts

  $ppe->write_mpdhosts($file);

Creates a 'mpd.hosts' file, containing the hosts included in the run.  Any
errors will be signalled with _error.

=cut

sub write_mpdhosts {
  my $self=shift;
  my $file=shift;

  my @hl=$self->ppe()->hosts();

  return $self->write_mpdhosts_file($file, @hl);
}

=head4 setup

=cut

sub setup {
  my $self=shift;
  my $workdir=shift;

  # we always remove and re-write
  $workdir->remove_file('mpd.hosts') if $workdir->have_file('mpd.hosts');
  my $file=$workdir->creatable_file('mpd.hosts');
  unless ($self->write_mpdhosts($file)) {
    _error("Error writing mpdhosts file: $!");
    return undef;
  }
  return $file;
}


1;
