#!/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",	# Micron
		"SSD_Life_Left",		# Kingston/SandForce
		"Wear_Leveling_Count",		# Samsung
		"Media_Wearout_Indicator",	# Intel
		);
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`);
foreach my $drive (@drives) {
        open(my $cat,'-|',"$smartctl_bin -a $drive");
        while(<$cat>) {
                $smart{$drive}->{$1}->{column4} = $2 if (/$pattern/);
        }
        close $cat;
}


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

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

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);
