#!/opt/SUNWstade/bin/perl -I/opt/SUNWstade/lib
use System;
use Agent;
use Getopt::Std;
use Data::Dumper;
use strict;
use Thread;

System->set_home(System->home_dir());

my($renv, $devices, $hosts, $notifs, $Config) = PDM::ConfigFile->read();

System->set_renv($renv);

# ras_thread -k wwn -p pid
# ras_thread -k vendor.model.serial
sub usage {
   print "ras_thread -k type:key -p <pid> \n";
}
my %opts;
if (!getopts("l:p:k:o", \%opts)) {
    usage();
    exit(1);
}

my $debugLevel = $opts{l};
my $pid      = $opts{p};
my $key0      = $opts{k};
my $DIR      = System->get_home() . "/DATA/Thread";
mkdir $DIR,0777 if (!-d $DIR);

Debug->level($debugLevel);

my($type, $key) = split(/\:/, $key0);

my $out_file = "$DIR/$pid.$key";
my $pid_file = "$out_file.pid";

unlink $out_file;
open(OO, ">$pid_file"); print OO $$; close(OO);

my $report;

if ($type eq "host") {
  require  "Agent/HOST.pm";
  $report = Agent::HOST->INSTRUMENTATION({});
} else {
  my $device = $Config->deviceByKey($key);
  if (!$device) {
     $report->{"rc.error"} = "Error: Invalid device $key";
     $report->{"rc.key"}   = $device->{key};
  } else {
     $report = Thread->INSTRUMENTATION($device);
  }
}

$Data::Dumper::Indent = 1;

if ($opts{o}) {
   print Dumper($report);
} else {  
   open(OO, ">$out_file.tmp");
   print OO Dumper($report);
   close(OO);
   rename "$out_file.tmp", $out_file;
}

unlink $pid_file;
