#!/usr/bin/perl

# A replacement for the various stock versions of hddtemp that all
# seem to have big issues with different types of drives, or spin up
# drives that are in powersaving spun-down mode, etc.

# For those disks like some of my SAS drives where `smartctl
# --nocheck=standby` and `hdparm -C` actually spins up the disk,
# detect whether a disk is spun down with sdparm commands, and don't
# invoke smartctl if it is.  Otherwise, some of our other disks like
# our 16TB SATA drives on Dell Perc controllers give unreliable status to `sdparm
# --command=sense`, but `smartctl --nocheck=standby` does seem to
# reliably detect their spundown state anyway, so we continue to
# supply `--nocheck=standby` to cover this case.

# Much of this stolen from /etc/munin/plugins/hddtemp_smartctl

use strict;
use warnings;

$ENV{PATH}="$ENV{PATH}:/usr/sbin:/sbin";

my $last_exit=0;
foreach my $drive (@ARGV) {
  my $output=`/usr/local/bin/smart-intercept-spindown -A -i $drive`;
  $last_exit = $?>>8;
  if (!($output =~ /Standby condition/)) {
    my $model="";
    if ($output =~ /(Model Number|Device Model):\s*(.*)/) {
      $model="$2: ";
    }
    if ($output =~ /Current Drive Temperature:\s*(\d+)/) {
      print "$drive: $model$1°C\n";
    } elsif ($output =~ /^(194 Temperature_(Celsius|Internal).*)/m) {
      my @F = split /\s+/, $1;
      print "$drive: $model$F[9]°C\n";
    } elsif ($output =~ /^(231 Temperature_Celsius.*)/m) {
      my @F = split ' ', $1;
      print "$drive: $model$F[9]°C\n";
    } elsif ($output =~ /^(190 (Airflow_Temperature_Cel|Temperature_Case).*)/m) {
      my @F = split ' ', $1;
      print "$drive: $model$F[9]°C\n";
    } elsif ($output =~ /Temperature:\s*(\d+) Celsius/) {
      print "$drive: $model$1°C\n";
    } else {
      print "$drive: Smart not available\n";
    }
  } else {
    print "$drive: Sleeping.  Temperature not available\n";
  };
}

exit $last_exit;
