#!/usr/bin/perl -w
####################################################
# This script collects a list of nodes from pbsnodes
# and adds them to the shosts.equiv file if they are new.
# C 2003 by Emanuele Leonardi (modified from edg-pbs-knownhosts)

use strict ;
use Fcntl;
use Socket;

####################################################
# Location of the configuration file
my $configfile = '/etc/edg-pbs-shostsequiv.conf' ;

my $specified ;   # List of manually specified nodes
my $pbsbin ;      # Location of pbsnodes command
my $shostsequiv ; # Full path of shosts.equiv file

####################################################
# Read the configuration file.
open(CONFIG,"<$configfile") || die "Could not open $configfile: $!\n" ;
while(<CONFIG>) {
  $specified   = $1  if (/^\s*NODES\s*=\s*(.*)$/)  ;
  $pbsbin      = $1  if (/^\s*PBSBIN\s*=\s*(\S+)\s*$/)  ;
  $shostsequiv = $1  if (/^\s*SHOSTSEQUIV\s*=\s*(\S+)\s*$/) ;
}
close(CONFIG) ;
die "PBSBIN not specified in $configfile" unless $pbsbin;
die "SHOSTSEQUIV not specified in $configfile" unless $shostsequiv;

####################################################
# Create an array of nodes.
my $pbsn = $pbsbin.'/pbsnodes -a' ;
open(PBSNODES,"$pbsn|") || die "Could note open $pbsn pipe: $!\n" ;
my @nodes ;
while(<PBSNODES>) {
   push(@nodes,$1) if (/^(\S+)\s*$/)
}
close(PBSNODES) ;
foreach (split(/\s+/,$specified)) {
  push(@nodes,$_) ;
}


###################################################
# Parse the current known host files and build a hash.
my %known ;
if ( -f $shostsequiv ) {
  open(KNOWN,"<$shostsequiv") || die "Could not open $shostsequiv\n" ;
  while(<KNOWN>) {
      chomp;
      next if ( /^\s*$/ || /^\s*#/ );
      $known{$1} = "true" if( /^\s*(\S*)\s*$/ )  ;
  }
  close(KNOWN) ;
}
##################################################
# Now work through each of the nodes that have
# been requested and see if any are new.
my @new ;
foreach ( @nodes ) {
  push(@new,$_) unless ( $known{$_} )  ;
}
#################################################
# Now add all the new nodes to the known hosts
# file.
sysopen(KNOWN, $shostsequiv, O_WRONLY|O_CREAT|O_APPEND) ||die  $!;
foreach(@new) {
    print KNOWN "$_\n" ;
}
close(KNOWN) ;
