#! /usr/bin/perl

use strict ;
use warnings ;

my %OPTS =
  ( spares  => 'blockdevscan'
  , status  => 'rgdisplay'
  , members => 'rmstatus RGROUP1'
  ) ;
my $OPTS = join ',', sort keys %OPTS ;

my $prog = substr $0, rindex ( $0, '/' ) + 1 ;
my $Usage = <<USAGE ;
Usage: $prog [-v] [-q] [-d] [-f] clas
option v : be verbose
option q : be quiet
option d : show debug info
option f : action ; otherwise dry-run
argument class : one of [$OPTS]
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 == 2 ;

my $CLAS = shift ; $CLAS =~ s/^raid1_// ;
my $TARG = shift ;
my $OPT  = $OPTS { $CLAS } ;
my $val ;

Error "bad clas [$CLAS]" unless defined $OPT ;

my @CMD = ( qw(/usr/sbin/atto-cli/atraidcli_x64 -x), $OPT ) ;
printf "CMD [%s]\n", join ' ', map "'$_'", @CMD if $opt{v} ;

open CMD, '-|', @CMD or Error "can't popen [@CMD] ($!)" ;
my @lines = <CMD> ;
close CMD ;

printf "LINES :\n%s", join '', @lines if $opt{d} ;

if ( $CLAS eq 'members' )
  { $val = grep /^\s*\d+\s+ONLINE/, @lines ; }
elsif ( $CLAS eq 'spares' )
  { $val = grep /^\s*\d+\s+.*\*HOTSPARE\*/, @lines ; }
elsif ( $CLAS eq 'status' )
  { my $line = ( grep /^RGROUP1/, @lines ) [ 0 ] ;
    my $stat = ( split ' ', $line ) [ 7 ] ;
    $val = ( $stat and $stat eq 'ONLINE' ) ? 1 : 0 ;
  }

my $res = $TARG - $val ;

if ( $opt{v} )
  { printf "class  $CLAS\n" ;
    printf "target $TARG\n" ;
    printf "found  $val\n" ;
    printf "result $res\n" ;
  }
print "$res\n" ;
