#!/usr/bin/perl
#
# check_thecus_temp.pl
# - A nagios plugin to monitor a THECUS NAS applicance temperatures
# 
# Usage:
#  check_thecus_temp.pl [--user <username>] [--password <password>] <host>
#  example: check_thecus_temp.pl --password 123password 192.168.0.100 
# 
# where
#  <host>			is the network address of the appliance
#  --user <username>		specifies the username for authentication (default: admin)
#  --password <pass>		specifies the password for authentication (default: admin)
# 
# Returns : (values are adjustable)
#  WARNING if values exceed 80C for CPU/SYS/SAS
#  CRITICAL if values exceed 85C for CPU/SYS/SAS
#  Ignores WARNING if CRITICAL is flagged
#  OK otherwise and prints additional temperatures of CPU, SAS backplane, System, HDD bay 1, HDD bay 2
# EXAMPLE OUTPUT
#
# OK: Thecus NAS running normally 
# CPU Temperature = 58 C 
# SAS Temperature = 67 C
# System Temperature = 44 C
# HDDBay Sensor 1 temperature = 44 C 
# HDDBay Sensor 2 temperature = 44 C  
#
# WARNING: As the applicance provides no real monitoring interface this plugin has to rely on
#  parsing the data out of the web-interface. That might cause errors when using different
#  firmware versions or even languages.
# 
# ======================
# Original Author credits
# =======================
# Author: Moritz Bechler <mbechler@eenterphace.org> for Schmieder IT Solutions (http://www.schmieder.de)
# License: MIT License
#
# Copyright (c) 2010 Moritz Bechler
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# =====================
# Adjusted for only temperature monitoring and working for
# Manufacturer:	Thecus
# Product No.:	N16000PRO
# Firmware Version:	2.04.06a 
#
use strict;
use FindBin;
use lib "$FindBin::Bin";
use Getopt::Long;
use LWP;
use LWP::UserAgent;
use Data::Dumper;
use HTTP::Cookies;


my $ua = new LWP::UserAgent;
$ua->agent('check_thecus Nagios plugin');
#$ua->cookie_jar(new HTTP::Cookies(file => '/tmp/cookies', ignore_discard => 1));
$ua->cookie_jar( { } );


my $user = 'admin';
my $pass = 'admin';
my $running = '';
my $stopped = '';

GetOptions("user=s" => \$user, "password=s" => \$pass, "running=s" => \$running, "stopped=s" => \$stopped);

my $host = shift;

if(!$host) {
	die "Usage: $0 [--user <username>] [--password <password>] [--running <Service1,Service2,...>] [--stopped <Service1,Service2,...>] <host>\n";
}

# Logging into the appliance, does not return if it fails
# my $res = $ua->post("http://$host/usr/login.html", [ 'username' => $user, 'pwd' => $pass ]);
my $res = $ua->post("http://$host/adm/login.php", [ 'username' => $user, 'pwd' => $pass ]);

if($res->is_error()) {
	print "CRITICAL: Thecus login failed (" . $res->status_line . ")\n";
	exit 2;
}

my $aboutRes = $ua->get("http://$host/adm/getform.html?name=about");

if(!$aboutRes->is_success()) {
	print "CRITICAL: Could not fetch status information (" . $aboutRes->status_line . ")\n";
	exit 2;
}

if(!$aboutRes =~ m/^\<html\>/s) {
	print "UNKNOWN: Could not log in to Thecus NAS";
	exit 3;
}

# Getting the system results from the appliance in raw text
my $sysStatRes = $ua->get("http://$host/adm/getmain.php?fun=monitor&action=update");



if(!$sysStatRes->is_success()) {
	print "CRITICAL: Could not fetch status information (" . $sysStatRes->status_line . ")\n";
	exit 2;
}
my $sysStatStr = $sysStatRes->content();

# ==== test section - print results in terminal ====
#  Uncomment this to see the entire Output on the Screen
# print "OUTPUT: $sysStatStr\n";
#

my @tmp = ();
my @lines = split "]", $sysStatStr;
my $CPU_TEMP = 0;
my $SAS_TEMP = 0;
my $SYS_TEMP = 0;
my $HDD_TEMP1 = 0;
my $HDD_TEMP2 = 0;
for my $line (@lines) {
	my @linetmp = split ",", $line;
	if(@linetmp == 2) {
		push @tmp, { key => $linetmp[0], value => $linetmp[1] };
# CPU_TEMP : current CPU temperature
	};
	if($linetmp[2] eq "\"CPU_TEMP\""){
	my @cput = split " ",$linetmp[3];
	$CPU_TEMP = int(substr($cput[0],1)); 
# SAS_TEMP : current SAS backplane temp
	}
	if($linetmp[2] eq "\"SAS_TEMP\""){
        my @cput = split " ",$linetmp[3];
        $SAS_TEMP = int(substr($cput[0],1));
# SYS_TEMP : current system temperature
        }   
        if($linetmp[2] eq "\"SYS_TEMP\""){
        my @cput = split " ",$linetmp[3];
        $SYS_TEMP = int(substr($cput[0],1));
# HDD_TEMP1 : HDD bay temp 1
        }   
        if($linetmp[2] eq "\"HDD_TEMP1\""){
        my @cput = split " ",$linetmp[3];
        $HDD_TEMP1 = int(substr($cput[0],1));
	}
# HDD_TEMP2 : HDD bay temp 2
        if($linetmp[2] eq "\"HDD_TEMP2\""){
        my @cput = split " ",$linetmp[3];
        $HDD_TEMP2 = int(substr($cput[0],1));
	}
}

# Define the values for temperatures here


#
# set error value to zero, so if it turns one, it will print the error
#
{
	my $error= 0;

#
# CPU temperature values here
	if($CPU_TEMP > 85)
                                {
                print "CRITICAL: High CPU Temperature | CPU Temperature = $CPU_TEMP \n";
                $error = 1;
        } else {
	
	if($CPU_TEMP >= 80)
                                {
                print "WARNING: High CPU Temperature | CPU Temperature = $CPU_TEMP \n";
                $error = 1;
                        }
	}
#
# system temperature values here
        if($SYS_TEMP > 85)

                                {
                print "CRITICAL: High SYS Temperature | SYS Temperature = $SYS_TEMP \n";
		$error = 1;
        } else {

	        if($SYS_TEMP >= 80)

                                {
                print "WARNING: High SYS Temperature | SYS Temperature = $SYS_TEMP \n";
                $error = 1;
                        }

#
## system temperature values here
        if($SAS_TEMP > 85)

                                {
                print "CRITICAL: High SYS Temperature | SYS Temperature = $SAS_TEMP \n";
                $error = 1;
        } else {

                if($SAS_TEMP >= 80)

                                {
                print "WARNING: High SYS Temperature | SYS Temperature = $SAS_TEMP \n";
                $error = 1;
                        }



# final error statement exit out and skip the status OK
	}

	if ($error eq 1) {
		exit 1;
	}
#
# If all of the above errors result to 0, print the OK status
#
	print "OK: Thecus NAS running normally \nCPU Temperature = $CPU_TEMP C \nSAS Temperature = $SAS_TEMP C\nSystem Temperature = $SYS_TEMP C\nHDDBay Sensor 1 temperature = $HDD_TEMP2 C \nHDDBay Sensor 2 temperature = $HDD_TEMP2 C \n";
	exit 0;
}}
