#!/usr/bin/perl -w
# HElog_smart: Write smartctl -a to file name built from Model.Serial.log HE: 18.2.2011
# Copyright c 2010 according to GPL v.2 by H.Ellenberger, CH-3360 Herzogenbuchsee.

use strict;
use POSIX qw(strftime);

my $log_dir = "/root/SMART";									# Files are created there

sub trm {															# Replace spaces, remove \n
	my $txt = shift; $txt =~ s/ /_/g; $txt =~ s/\n//g;
	return $txt
}

sub ck_one{															# Check one drive given by @_
	my $cmd = "smartctl -a @_";
	my @res = `$cmd`;
	my $stat = $?; $cmd="'$cmd' -> ";
	if ($stat) {print "$cmd ERROR= $stat\n"; return;}
	my $fnam;
	foreach (@res) {
		my $line = $_;												# Split lines returned by smartctl
		if ($line =~ s/Device Model:     //){
			$fnam = trm $line;									# Extract Model
		}elsif ($line =~ s/Serial Number:    //){
			$line = trm $line;									# Extract Serial no.
			$fnam = "$log_dir/$fnam.$line.log";				# Build path/name
		}
	}
	my $dat = strftime("%d.%m.%Y-%H:%M",localtime(time()));
	my $health = `smartctl -H @_`;							# Get health info
	$stat = $?;

	my $FIL; open($FIL, ">>", $fnam) or die "Error creating $fnam\n"; # Open result file and append
	print $FIL "**** $dat ***********************************************************\n";
	if ($stat) {
		print $FIL "Error $stat checking health of @_\n";
		$health = "DEFECTIVE";
	} else {
		if ($health =~ /PASSED/) {$health = "Health OK" }
		else {$health = "ERROR: $health"; }
	}
	print $FIL "$health\n";
	print $FIL @res;
	close $FIL;
	print "$cmd $health\n";											# Show progress
}

print "$0 v=18.2.2011 \n";
my @res = `ls -l /dev/disk/by-id/scsi-*`;						# Get only SCSI/SATA
my $stat = $?;
if ($stat){print "ERROR $stat: $!\n"; exit 1;}
foreach (@res){
	my $line = $_;
	if (! ($line =~ /part/)){										# Skip those of partitions
		if ($line =~ /([^->])-> ..\/..\/(.+)/ ) {				# Get drive only like 'sda'
			ck_one "/dev/$2";
		}
	}
}
print "Done.\n";
# --- eof ---
