#!/usr/bin/perl -w

$debug = "/dev/null";
open DEBUG, ">$debug" or die "Can't open $debug";
# Note:
# Debug messages are prepended with the "DEBUG: " pattern
# Therefore:
#     neb-grep -v GREP_PATTERN FILE_PATTERN | grep -v ^DEBUG
# is equivalent to:
#     neb-grep GREP_PATTERN FILE_PATTERN

#
# We need at least two arguments
#
if (@ARGV < 2) {
    $usage = "Usage: neb-grep [--verbose|-v] [--server <URL>] [GREP OPTIONS] <grep_pattern> <file_pattern>\n";
    $usage .= "  See grep man page for <grep_pattern> and [GREP OPTIONS]\n";
    $usage .= "  <file_pattern> is a SQL-like pattern (file_pattern search is based on neb-ls --path)\n";
    $usage .= "  http://nebulous.mhpcc.ipp.ifa.hawaii.edu/nebulous is default <URL> value\n";
    $usage .= "  [-v|--verbose] show details\n";
    $usage .= "\n";
    $usage .= "  Example(s):\n";
    $usage .= "    neb-grep \"my_die\" gpc1/ThreePi.nt/2010/08/24/o5432g0503o.212622/o5432g0503o.212622.ch.126887.%.log\n";
    $usage .= "    neb-grep -i \"MY_DIE\" gpc1/ThreePi.nt/2010/08/24/o5432g0503o.212622/o5432g0503o.212622.ch.126887.%.log\n";
    &bye(2, $usage);
}

# 
# Parse arguments 
#
$args = "";
while (@ARGV > 1) {
    if ($ARGV[0] =~ /--path/) {
	#Forget it since it's always added
	shift;
    } elsif ( $ARGV[0] =~ /--server/ ) {
	shift;
	$server = $ARGV[0];
	shift;
    } elsif ( ($ARGV[0] =~ /--verbose/) || ($ARGV[0] =~ /-v/) ){
	close DEBUG;
	$debug = "/dev/stdout";
	open DEBUG, ">$debug" or die "Can't open $debug";
	shift;
    } else {
	$args .= $ARGV[0]." ";
	shift;
    }
}
$file_pattern=$ARGV[0];
chop $args;
print DEBUG "DEBUG: file_pattern = [$file_pattern]\n";
print DEBUG "DEBUG: grep arguments = [$args]\n";

# Define server with the default value if needed
if (!(defined $server)) {
    $server = "http://nebulous.mhpcc.ipp.ifa.hawaii.edu/nebulous";
}

# Get the filenames from neb-ls command
print DEBUG "DEBUG: Executing command: neb-ls --path --server $server  --path $file_pattern 2>&1\n";
@nebitems = `neb-ls --path --server $server --path $file_pattern 2>&1`;

# Deal with non-matching file patterns
if ( (@nebitems == 0) || ($nebitems[0] =~ /no instances/) ) {
    &bye(1, "no instances");
}

# Deal with matching file patterns by running the "grep" command
for $filename (@nebitems) {
    chomp $filename;
    print DEBUG "DEBUG: Executing grep $args $filename\n";
    $output = `grep $args $filename`;
    print DEBUG "DEBUG: Output is [$output]\n";
    if (!($output =~ /^$/)) {
	print $filename, ": ", $output;
    }
}
&bye(0, "");

sub bye {
    my $status = shift;
    my $message = shift;
    close DEBUG;
    unless ($message =~ /^$/) {
	print STDERR $message,"\n";
    }
    exit $status;
}

