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

chomp(my @drives = `fdisk -l | grep -Po '/dev/(s|h|v)d[a-z]+' | uniq`);
my %smart;
my $count;

foreach my $drive (@drives) { 
	open(my $cat,'-|',"/opt/zabbix/sbin/raidcheck/bin/smartctl -a $drive");
	while(<$cat>) {
		if (/[0-9]+\s+([a-zA-Z\_]+)\s+0x[0-9a-zA-Z]+\s+([0-9]{3})\s+[0-9]{3}\s+[0-9]{3}\s+[a-zA-Z\-\_]+\s+[a-zA-Z]+\s+\-\s+([0-9]+).*$/) {
			my($c1,$c2,$c3) = ($1,$2,$3);
			$smart{$drive}->{$c1}->{column4}=$c2;
			$smart{$drive}->{$c1}->{last}=$c3;
		}
	close $cat;
}
chomp(my @megadrives = `/opt/zabbix/sbin/raidcheck/bin/MegaCli64 -PDList -aALL |grep 'Device Id' | awk '{print \$3}'`);
foreach my $megadrive (@megadrives) {
	open(my $cat,'-|',"/opt/zabbix/sbin/raidcheck/bin/smartctl -a -d sat+megaraid,$megadrive /dev/sda");
	while(<$cat>) {
		if (/[0-9]+\s+([a-zA-Z\_]+)\s+0x[0-9a-zA-Z]+\s+([0-9]{3})\s+[0-9]{3}\s+[0-9]{3}\s+[a-zA-Z\-\_]+\s+[a-zA-Z]+\s+\-\s+([0-9]+).*$/) {
			my($c1,$c2,$c3) = ($1,$2,$3);
			$smart{$megadrive}->{$c1}->{column4}=$c2;
			$smart{$megadrive}->{$c1}->{last}=$c3;
		}
	}
	close $cat;
}
foreach my $match (keys %smart) {
	if ($smart{$match}->{SSD_Life_Left}) {
		if ($smart{$match}->{SSD_Life_Left}->{column4} <= 15) {
			$count++;
		}
	} else {
		if (($smart{$match}->{Temperature_Celsius}->{last} == 0) && ($smart{$match}->{Temperature_Celsius}->{column4} <= 15)) {
			$count++;
		}
	}	
}

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