#!/usr/bin/perl

$infofile = shift || '/usr/local/npulse/data/infofile.txt';
$Usage = "Usage: $0 [infofile]\n  where 'infofile' is the name (full path) of the infofile.txt file.\n\n";
die $Usage unless -f $infofile;

%Template = ( ip => undef,
              icon => undef,
              os => undef,
              CustomerID_1 => undef,
              Location_2 => undef,
              Host_3 => undef,
              Phone_4 => undef,
              Pager_5 => undef,
              Email_6 => undef,
              Comments_7 => undef,
              Alias_8 => undef,
              Icon_9 => undef,
              GroupID_10 => undef,
              CustomID_11 => undef,
	      Notify_12 => undef
            );

open(F, "<$infofile") or die $Usage;
open(G, ">$infofile.tmp") or die "Unable to create an output infofile.\n$!";
print "Processing $infofile ...\n";
$count = 0;
while (<F>) {
  chomp;
  $line = $_; $count++;
  $line =~ s/^\s*//; $line =~ s/\s*$//;
  next unless $line;
  if ($line =~ /^ip => /) {
    %site = %Template;
    foreach (split(/\s*,\s*/, $line)) {
      ($key,$val) = split /\s*=>\s*/;
      $val =~ s/^"//; $val =~ s/"$//;
      if ($key =~ /^(?:ip|icon|os|CustomerID_1|Location_2|Host_3|Phone_4|Pager_5|Email_6|Comments_7|Alias_8|Icon_9|GroupID_10|CustomID_11|Notify_12)$/) {
        $site{$key} = $val;
      } else {
        print STDERR "Warning: removing non-standard key value: $key\n";
      }
    }
    $site{'os'} = "";
    $ip = $site{'ip'};
    if ($ip =~ /^[\d\.]+$/) {
      delete $site{'ip'};
      print G 'ip => "',$ip,'"';
      foreach (sort keys %site) {
        print G ', ',$_,' => "',$site{$_},'"';
      }
      print G "\n";
    } else {
      print STDERR "Warning: removing badly formed ip address: $ip\n";
    }
  } else {
    print STDERR "Warning: removing badly formed line starting with: ",substr($line,0,11),"\n";
  }
}
close(G);
close(F);
rename $infofile, "$infofile.bak";
rename "$infofile.tmp", $infofile;

print "\nFinished processing ",$count," lines.\n\n",
      "Next, restart nPulse and go to the Default:Basic page.\n",
      "nPulse will regenerate all of the Operating System values.\n",
      "This may take awhile for large networks.\n\n";
