#!/usr/bin/env perl

# Find all matches per platform for an expression
# $Id: nmi_search_classads.pl,v 1.1 2008-08-04 19:46:57 bgietzel Exp $ 

use Getopt::Long;
use Cwd;
use Time::Local;
use strict;
use warnings;

use vars qw/ $opt_search_string /;
GetOptions('search_string=s'  => \$opt_search_string,
);

  if  ( !defined( $opt_search_string) ) {
    print "Usage: --search_string=<>\n"; 
    exit;
  }
  
  my $cmd = "condor_status -l | egrep '($opt_search_string|nmi_platform|Machine )' | uniq";

  my $filename = "/tmp/report.lab";
  system("$cmd > $filename");

  my $curr_plat;
  my $platform;
  my $curr_machine;
  my $found = 0;
  my %matches = ();
  my $match;
  my $size;

  open ( REPORT, "<$filename") || die "can't open report: $?\n";
 
  while (<REPORT>) {
    chomp;
    my ($key, $val) = split (/=/, $_);
    chomp($key);
    chop($key);
    if ( $key =~ /LastUpdate/ || $key =~ /INDEX/ || $key =~ /FIELDS/ || $key =~ /Mult/ || $key =~ /ClientMachine/) {
      next;
    }
    $val = strip_quotes($val);

    # Keep the current machine
    if ($key eq "Machine") {
      $found = 1;
      if (defined($curr_machine) && $curr_machine ne $val ) {
        $size = keys( %matches );
        if ( $size gt 0 ) {
          print "---------------------------------------------------------------\n";
          print "PLATFORM : $platform\n";
          foreach $match (keys %matches) {
            print "$match\n"; 
          }
          %matches = ();
        } 
        #print "Machine is $curr_machine\n";
      }
      $curr_machine = $val;
    } elsif ($key eq "nmi_platform" && $found == 1 ) {
        $platform = $curr_plat;
        $curr_plat = $val;
        $found = 0;
    } else {
        $matches{$key} = "$val";
    }
  }
  close REPORT;
  # print the search results for the last machine
  $size = keys( %matches );
  if ( $size gt 0 ) {
    print "---------------------------------------------------------------\n";
    print "PLATFORM : $platform\n";
    foreach $match (keys %matches) {
      print "$match\n";
    }
    %matches = ();
  }

sub strip_quotes {
  my $val = shift;
  $val =~ s/"//g;
  return $val;
}


