#! /usr/bin/perl

use strict ;
use warnings ;

my $prog = substr $0, rindex ( $0, '/' ) + 1 ;
my $Usage = <<USAGE ;
Usage: $prog [-v] [-q] [-d] [-f] args
option v : be verbose
option q : be quiet
option d : show debug info
option f : action ; otherwise dry-run
USAGE
sub Usage { die "$_[0]$Usage" ; }
sub Error { die "[error] $prog: $_[0]\n" ; }
sub Warn  { warn "[warn] $prog: $_[0]\n" ; }

# usage: &GetOptions(ARG,ARG,..) defines $opt_ID as 1 or user spec'ed value
# usage: &GetOptions(\%opt,ARG,ARG,..) defines $opt{ID} as 1 or user value
# ARG = 'ID' | 'ID=SPC' | 'ID:SPC' for no-arg, required-arg or optional-arg
# ID  = perl identifier
# SPC = i|f|s for integer, fixedpoint real or string argument

use Getopt::Long ;
Getopt::Long::config ( 'no_ignore_case' ) ;
my %opt = () ; Usage '' unless GetOptions
  ( \%opt, qw(v q d f) ) ;
Usage "Arg count\n" unless @ARGV ;

sub get_bad_pds
  { my $ctrl = shift ;
    my @CMD  = ( qw(/local/bin/storcli), $ctrl, 'show' ) ;
    my $CMD  = "@CMD" ;
    my $pds  = undef ;
    open CMD, '-|', @CMD or Error "can't popen $CMD ($!)" ;
    while ( <CMD> )
      { print "loop 1 $_" if $opt{d} ;
        chomp ;
        if ( /Physical Drives = (\d+)/ )
          { $pds = $1 ; last ; }
      }
    Error "no count for 'Physical Drives'" unless defined $pds ;
    while ( <CMD> )
      { print "loop 2 $_" if $opt{d} ;
        last if /^EID:Slt\s+DID\s+State\s+DG/ ;
      }
    my $sink = <CMD> ;
    my $cnt  = 0 ;
    while ( <CMD> )
      { print "loop 3 $_" if $opt{d} ;
        chomp ;
        last if /^-------------------/ ;
        $cnt ++ if ( ( split ' ' ) [ 2 ] eq 'Onln' ) ;
      }
    close CMD ;
    ( $cnt > $pds ? undef : $pds - $cnt ) ;
  }

my $res = 0 ;
for my $arg ( @ARGV )
  { my $bads = get_bad_pds ( $arg ) ;
    print "$arg : bad pds $bads\n" if $opt{v} ;
    $res += $bads ;
  }

printf "%s\n", $res ;
