#!/usr/bin/perl -w


use Shell qw(caget);

use strict;

sub doCaget($)
{
   # print "trying connections...\n";
   my $PV = shift;
   my $caGetCommand = "-t $PV"; 
   my $value = caget($caGetCommand);
   chomp $value;
   if ($value eq "")
      { $value = "not found"; }
   $value = sprintf("%16s", $value);
   return $value;
}

sub getIOCIsRunning($)
{
   my $ioc = shift;
   print "ioc = $ioc\n";
   my @cmd_output = `ssh lcls-daemon1 -l laci ps -ef | grep "/usr/local/bin/perl -S -w siocStart.pl /usr/local/lcls/epics/iocCommon/$ioc" | grep -c -v grep`;
   print "proc count for $ioc is: $cmd_output[0]\n";
   chomp $cmd_output[0];
   return $cmd_output[0];
}

sub iocParams($$)
{
	my $fil = shift;
	my $siocReport = shift;
        my @lines;
	
        if (defined $fil)
           {
           print "input from *$fil*\n";
	   if (!open(INP, $fil)) 
              {
  	      print "*** $fil: failed to read \n";
	      return;
              }
	   @lines = <INP>;
	   close INP;
           }

        if (!open(OUT, ">" . $siocReport)) 
           {
  	   print "*** $siocReport: failed to open for write\n";
	   return;
           }
        print OUT "SOFT IOC PARAMETERS\n\n";
        print OUT "IOC               Connection count           Client count   IOC Running\n";

	foreach my $line (@lines) 
           {
           if ($line =~ /sioc/)
              {
              chomp $line;
              # strip leading, trailing blanks
              $line =~ s/^\s+//;
              $line =~ s/\s+$//;

              my $iocRpt = sprintf("%-17s", $line);
              print OUT $iocRpt;

              my $iocPVName = $line;
              $iocPVName =~ s/-/:/g;

              my $pvName = uc $iocPVName . ":CA_CONN_CNT";
              my $conn_cnt_val = doCaget($pvName);
              print OUT "$conn_cnt_val       ";
              $pvName = uc $iocPVName . ":CA_CLNT_CNT";
              my $clnt_cnt_val = doCaget($pvName);
              print OUT "$clnt_cnt_val   ";

              my $iocRunning = getIOCIsRunning($line);
              print OUT "    $iocRunning\n";
              }
           }
}


##################################################

# code start

##################################################

#getIOCIsRunning("sioc-sys0-al00");
#getIOCIsRunning("sioc-sys0-abc");
#exit;

if ($#ARGV < 0)
   {
   print "Please enter 2 files:\n";
   print " 1. input file = list of soft ioc names\n";
   print " 2. output file = report filename\n";
   print "e.g.\n";
   print "  siocParams.pl softIOCNames.lst softIOCParamReport\n\n";
   exit;
   }

my $iocList= $ARGV[0];
my $reportName;
if ($#ARGV < 1)
  {
  print "Reporting to:\n";
  print "  softIOCParamReport.lst\n";
  $reportName = "softIOCParamReport.lst";
  }
else
  { $reportName = $ARGV[1]; }

print "params for soft IOCs\n";

iocParams($iocList, $reportName);

print "done\nOUTPUT IS IN $reportName\n";
