#!/usr/bin/perl
#Pull SSD Life data from any drives with the value.
use strict;
use Sys::Hostname;

my %smart;
my $count = 0;
my $threshold = 10;
my %attrlist = ("Percent_Lifetime_Used"		=>	$threshold,	# Micron
		"SSD_Life_Left"			=>	$threshold,	# Kingston/SandForce
		"Wear_Leveling_Count"		=>	$threshold,	# Samsung
		"Media_Wearout_Indicator"	=>	$threshold,	# Intel
		);

my @skipdevices = ("3E128-TS2-530G00");					# Nytrocache

my $megacli_bin = '/usr/local/eig_zabbix/sbin/raidcheck/bin/MegaCli64';
my $smartctl_bin = '/usr/local/eig_zabbix/sbin/raidcheck/bin/smartctl';
my $pattern = '^\d+\s+(\S+)\s+0x\S+\s+(\d{3})\s+\d{3}\s+\d{3}\s+\S+\s+\S+\s+\S+\s+\d+.*$';

chomp(my @drives = `fdisk -l 2>/dev/null| grep -Po '/dev/(s|h|v)d[a-z]+' | uniq`);
DRIVE_LOOP: foreach my $drive (@drives) {
        open(my $cat,'-|',"$smartctl_bin -a $drive");
        while(<$cat>) {
                foreach my $skipdevice (@skipdevices){
                        if(/^Device Model:\s+$skipdevice/){
                                close $cat;
                                next DRIVE_LOOP;
                        }
                }
                $smart{$drive}->{$1}->{column4} = $2 if(/$pattern/);
        }
        close $cat;
}

chomp(my @megadrives = `$megacli_bin -PDList -aALL |grep 'Device Id' | awk '{print \$3}'`);
MEGADRIVE_LOOP: foreach my $megadrive (@megadrives) {
        open(my $cat,'-|',"$smartctl_bin -a -d sat+megaraid,$megadrive /dev/sda");
        while(<$cat>) {
		foreach my $skipdevice (@skipdevices){
			if(/^Device Model:\s+$skipdevice/){
				close $cat;
				next MEGADRIVE_LOOP;
			}
		}
                $smart{$megadrive}->{$1}->{column4} = $2 if(/$pattern/);
        }
        close $cat;
}

foreach my $match (keys %smart) {
	foreach my $attr (keys %attrlist) {
		$count++ if((exists($smart{$match}->{$attr})) && (($smart{$match}->{$attr}->{column4} <= $attrlist{$attr}) || $smart{$match}->{$attr}->{column4} > 100));
	}
}

if(! -d '/usr/local/eig_zabbix/tmp'){
        mkdir('/usr/local/eig_zabbix/tmp') or die('Error creating directory: /usr/local/eig_zabbix/tmp');
}

open(my $zabbix,'>>',"/usr/local/eig_zabbix/tmp/raid.tmp");
        print $zabbix hostname() . " raid[\"SSD_Life_Left\"] " . $count . "\n";
close($zabbix);
