#!/usr/bin/perl
use Getopt::Long;

# misc variables
my (@output, @checks, $file, %requested, %found);


# parameters
my @checks = @ARGV;

# check @checks and extract values
process_checks(@checks);

# check command work
check_command('/usr/local/sbin/tw_cli info');



foreach (`/usr/local/sbin/tw_cli info 2>&1`)
{
    if ( /^c(\d+)\s+/ ) { $found{$1} = {}; }

}

foreach $c (keys(%found))
{
    foreach (`/usr/local/sbin/tw_cli info c$c 2>&1`)
    {
        # u0    RAID-1    OK             -       -       -       931.312   ON     ON
        if ( /^u(\d+)\s+(\S+)\s+(\S+)\s+/ ) { $found{$c}{'units'}{$1} = $3; }

        # p0     OK               u0     931.51 GB   1953525168    9QJ6BLS9
        if ( /^p(\d+)\s+(\S+)\s+/ ) { $found{$c}{'ports'}{$1} = $2; }
    }
}


# check found against requested
foreach $c (keys(%found))
{
    foreach $u (keys(%{$found{$c}{'units'}}))
    {
        # check unit has a valid status
        if ( $found{$c}{'units'}{$u} !~ /^(OK|VERIFYING)$/) { print STDERR 'Controller #' . $c. ', Unit #' . $u . ' is in status: ' . $found{$c}{'units'}{$u} . "\n"; failraid(); }
    }

    foreach $p (keys(%{$found{$c}{'ports'}}))
    {
        # check port was requested
        if ( ! exists $requested{$c}{'ports'}{$p} )
        {
            if ( $found{$c}{'ports'}{$p} eq 'NOT-PRESENT' ) { next; }
            print STDERR 'Controller #' . $c. ', Port #' . $p . ' exists but was not requested ( add \'c' . $c . ':p' . $p . '\' )' . "\n";
            failraid();
        }

        # check port has a valid state
        if ( $found{$c}{'ports'}{$p} !~ /^(OK|VERIFYING)$/)
        {
            print STDERR 'Controller #' . $c. ', Port #' . $p . ' has status ' . $found{$c}{'ports'}{$p} . "\n";
            failraid();
        }
    }
}


# check requested against found
foreach $c (keys(%requested))
{
    foreach $p (keys(%{$requested{$c}{'ports'}}))
    {
        if ( ! exists $found{$c}{'ports'}{$p} )
        {
            print STDERR 'Controller #' . $c. ', Port #' . $p . ' was requested but was not found ( delete \'c' . $c . ':p' . $p . '\' )' . "\n";
            failraid();
        }
    }
}

# if we are here, all is ok
okraid();






sub check_command
{
    my ($cmd) = @_;

    # check if the command is valid
    if ( system($cmd . ' > /dev/null') != 0 )
    {
        print STDERR $cmd . ' has failed' . "\n";
        failraid();
    }
}


sub process_checks
{
    my $p;
    foreach (@_)
    {
        if ( /^c(\d+):p(\d+)$/ )
        {
            $requested{$1}{'ports'}{$2} = 0;
        }
        else
        {
            print STDERR 'Invalid syntax for parameter (' . $_ . '), examples of valid values: "c0:p0" "c1:p0" "c1:p7"' . "\n";
            failraid();
        }
    }
}


sub okraid
{
    print 'RAIDOK';
    exit(0);
}

sub failraid
{
    print 'FAIL';
    exit(0);
}
