#!/usr/bin/perl
#
# check_thecus_raid.pl
# - A nagios plugin to monitor a THECUS NAS applicance Raid Status
# 
# Usage:
#  check_thecus_temp.pl [--user <username>] [--password <password>] <host>
#  example: check_thecus_raid.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 when rebuilding
#  CRITICAL when degraded
#  Ignores CRITICAL when rebuilding
#  Otherwise it will print WARNING: Raid status is unknown or not healthy, showing current status
# EXAMPLE OUTPUT
# OK: Thecus NAS Raid Status is Healthy 
#
# 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 
#  Tested on N16000PRO. N12000 and N12000PRO
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=raid&action=getraidlist");



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";
#
#use Data::Dumper qw(Dumper);
my $str = $sysStatStr;
my $raidstatus = "";
my @lines = split /,/, $str;
#print Dumper \@lines;


my @linetmp = [];

my @tmp = ();
my $raid_status = 0; 
for my $line (@lines) {
 
        @linetmp = split /:/, $line;
	
        if(@linetmp == 2) {

                push @tmp, { key => $linetmp[0], value => $linetmp[1] };

	if($linetmp[0] eq "\"raid_status\"") {

#print " LINETMP1 KAKAKAKAKAKA: $linetmp[1]\n\n";
#my $raidstatus=@linetmp[1];

	my $raidstatus=@linetmp[1]; #make linetmp human readable
	$raidstatus=~ s/[^a-zA-Z0-9]//g; #remove special chars

#	print "Current Raid Status : $raidstatus\n"; #print the actual outcome of the status
# 	$raidstatus = "Rebuilding"; #line to test input statusses and check error outcome, uncomment 3 above

{       
 my $error= 0;
	
  if($raidstatus eq "Healthy")
                {                
                print "OK: Thecus NAS Raid Status is $raidstatus \n";
                $error = 1;
        } else {
        print "WARNING: Raid status is unknown or not healthy, current status = $raidstatus\n";

        if($raidstatus eq "Degraded")
                {                
                print "CRITICAL: RAID STATUS = $raidstatus \n";
                $error = 1;

        } else {

        if($raidstatus eq "Rebuilding")
                               {
                print "WARNING: RAID STATUS = $raidstatus \n";
                $error = 1;
        }

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

 	if ($error eq 1) {
 		exit 1;
		}
}}}}}};
