#!/usr/bin/perl -w
############################## check_weewar ######################
my $Version='0.03';
# Date :    Jul 01 2009
# Author  : tobyyy 
# Help :    http://www.nagios-portal.de User:tobyyy
# TODO : 
# - <state>finished</state> Check is missing 
##################################################################
#
# Help : ./check_weewar.pl -h

use strict;
use Getopt::Long;
use Log::Log4perl qw(:easy);
use LWP::Simple;
use XML::Simple;
use Data::Dumper;
################Options##########
my $o_help=		undef; 	# Hilfe
my $o_verb=		undef;	# verbose mode
my $o_version=		undef;	# print version
my $o_weewar_user_id=	undef;  # Weewar User ID
my $o_weewar_game_id=	undef;  # Weewar Game ID
my $o_warn_opt=		undef;  # warning options
my $o_crit_opt=		undef;  # critical options


################Vars#############
my %ERRORS=('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);
my $weewar_game_id     = "Unknown-id";
my $weewar_game_id_low = "Unknown-id";
my $weewar_game_name   = "Unknown-name";
my $game_pace          = "0";
my $game_since         = "0";
my $game_state         = "Uninitialized";
my $game_open          = "0";
my $game_to_play       = "0";
my $contentuser        = "Uninitialized";
my $turn_duration      = "0";
my $time_to_move       = "0";
my $time_to_move_first = "0";
my $time_to_move_loop  = "0";
my $time_to_move_out   = "0";
my $var_output         = "Uninitialized";
my $var_return         = "2";
my $user_current       = "Uninitialized";
my $user_exist         = "Uninitialized";

##################MAIN############
check_options();

getgames();

if ($time_to_move < 0 )             
{
   $var_output = "Critical: Move in Game http://weewar.com/game/$weewar_game_id_low -- Time Left: !!No time left!!";
   $var_return = "2";
}

elsif (($time_to_move < $o_crit_opt ) && ($time_to_move > 0 ) )
{
   $var_output = "Critical: Move in Game http://weewar.com/game/$weewar_game_id_low -- Time Left: $time_to_move_out";
   $var_return = "2";
}
elsif (($time_to_move > $o_crit_opt) &&($time_to_move <$o_warn_opt) )
{
   $var_output = "Warning: Time is low to move in http://weewar.com/game/$weewar_game_id_low -- Time Left: $time_to_move_out";
   $var_return = "1";
}
elsif ($time_to_move > $o_warn_opt) 
{
   $var_output = "OK: Enough time to move -  $time_to_move_out - lowest time http://weewar.com/game/$weewar_game_id_low ";
   $var_return = "0";
}
else
{
   #"Unknown";
   $var_return = "3";
}


if ($game_open == "0")  
{
   $var_output = "Warning: You are not participating in any game ";
   $var_return = "2";
}

if ($game_to_play == "0")
{
   $var_output = "OK: It is not your turn at any game";
   $var_return = "0";
}

if ($user_exist eq "no")
{
 $var_output = "Warning:  This User does not exist: $o_weewar_user_id ";
 $var_return = "2";
}


output();

###########################################
sub getgames {
###########################################

my $url = 'http://weewar.com/api1/user/';
$url = $url.$o_weewar_user_id; 

if ( $contentuser = get $url)
{

#find and move Games in a array
my $xml = new XML::Simple (KeyAttr=>'game');
my $data = $xml->XMLin($contentuser,forcearray => [ 'game' ]);
my $e ="";
my $f ="";

foreach $e (@{$data->{games}->{game}})
{
        $weewar_game_id= $e->{content};
        my $urlgame = 'http://weewar.com/api1/game/';
        $urlgame = $urlgame.$e->{content};
       
        my $contentgame = get $urlgame;
        die "Couldn't get $urlgame" unless defined $contentgame;
        
        $xml = new XML::Simple (KeyAttr=>'player');;
        $data = $xml->XMLin($contentgame);
        $game_since = $data->{since};
        $game_pace = $data->{pace};
        $game_open = $game_open +1; 
         
        $game_state = $data->{state};
        if ($game_state=~"running") 
        {
           foreach $f (@{$data->{players}->{player}})
           {
            $SIG{__WARN__} = \&warn2dev;

            if ($f->{content}=~$o_weewar_user_id)
            {
                $SIG{__WARN__} = \&warn2dev;
                
                if ($f->{current}=~"true")
                {
                   convertsince();
                   $game_to_play= $game_to_play + 1; 
                    
                }
            }
           }
        }
    
}
converttime();

}
else
{
 $user_exist="no";
}
}
###########################################
sub convertsince {
###########################################
my $game_duration_day="0" ;
my $game_duration_hour="0" ;
my $game_duration_minute="0" ;
my @split_since = split(/ /,$game_since);
my $array_number = @split_since;

if (($split_since[1] =~"days") || ($split_since[1] =~"day"))
{
   
   $turn_duration= ($split_since[0]*86400)+($split_since[2]*3600)+$split_since[4]; 
   $time_to_move_loop=$game_pace-$turn_duration;
   if (($time_to_move_loop<$time_to_move) || ($time_to_move_first=~"0"))
    {
      $time_to_move=$time_to_move_loop;
      $time_to_move_first="1";
      $weewar_game_id_low=$weewar_game_id;
    }
}
elsif (($split_since[1] =~"hours") || ($split_since[1] =~"hour"))
{

   $turn_duration= ($split_since[0]*3600)+($split_since[2]*60);
   $time_to_move_loop=$game_pace-$turn_duration;
   if (($time_to_move_loop<$time_to_move) || ($time_to_move_first=~"0"))
    {
      $time_to_move=$time_to_move_loop;
      $time_to_move_first="1";
      $weewar_game_id_low=$weewar_game_id;
    }

}  
elsif  (($split_since[1] =~"minutes") || ($split_since[1] =~"minute"))
{
   $time_to_move_loop=($game_pace)-($split_since[0]*60);
   if (($time_to_move_loop<$time_to_move) || ($time_to_move_first=~"0"))
    {
      $time_to_move=$time_to_move_loop;
      $time_to_move_first="1";
      $weewar_game_id_low=$weewar_game_id;
    }

} 

}
############################################
sub converttime{
############################################
my $days  = (gmtime $time_to_move)[7];
my $hours = (gmtime $time_to_move)[2];
my $minutes = (gmtime $time_to_move)[1];

$time_to_move_out= "$days d $hours h $minutes m";
}
############################################
sub warn2dev{
############################################
}
############################################
sub p_version 
############################################
{ 
print "check_weewar.pl : $Version\n";
}

############################################
sub print_usage
############################################
{
    print "Usage: $0 [-v] -u <weewar_id> -w<warn levels> -c<crit levels>\n";
}

############################################
sub isnnum
############################################
{ # Return true if arg is not a number
my $num = shift;
if
( $num =~ /^(\d+\.?\d*)|(^\.\d+)$/ ) 
{ return 0 ;}
return 1;
}
############################################
sub help
############################################
{
print "\ncheck_weewar_pl for Nagios -- version ",$Version,"\n";
print "tobyyy\n\n";
print_usage();
print <<EOT;
-v, --verbose
log in check_weewar.log extra debugging information(not for regular work!)
-h, --help
print this help message
-u 
insert here the weewar ID
-w, --warning=minutes (e.g 120)
warning level: there is time to make a move
-c, --critical=minutes (e.g 60)
critical level: there is very less time to make a move
-V, --version
prints version number
EOT
}
############################################
sub check_options
############################################
{
Getopt::Long::Configure ("bundling");
GetOptions(
'v'	=> \$o_verb,		'verbose'	=> \$o_verb,
'h'     => \$o_help,    	'help'        	=> \$o_help,
'V'	=> \$o_version,		'version'	=> \$o_version,
'u:s'   => \$o_weewar_user_id,  'weewarid:s'    => \$o_weewar_user_id,
'w:s'   => \$o_warn_opt,       	'warning:s'   	=> \$o_warn_opt,
'c:s'   => \$o_crit_opt,      	'critical:s'   	=> \$o_crit_opt,

);
if (defined ($o_help) ) { help(); exit $ERRORS{"UNKNOWN"}};
if (defined($o_version)) { p_version(); exit $ERRORS{"UNKNOWN"}};
if ( ! defined($o_weewar_user_id) || ! defined($o_warn_opt) || ! defined($o_crit_opt) ) # check input 
 	{ print_usage(); exit $ERRORS{"UNKNOWN"}}
if (defined ($o_verb) )   { Log::Log4perl->easy_init( { level   => $DEBUG,
                                file    => ">>check_weewar.log" } );}

}
					      

###########################################
sub output
###########################################
{

    if ($var_return == 0)
    {
          #"OK";
          print $var_output , "|Time to move=", $time_to_move , ";$o_warn_opt;$o_crit_opt;0;\n";
          exit $ERRORS{"OK"};

    }
    elsif ($var_return == 1)
    {
          # "Warning";
          print $var_output , "|Time to move=", $time_to_move, ";$o_warn_opt;$o_crit_opt;0;\n";
          exit $ERRORS{"WARNING"};

    }
    elsif ($var_return == 2)
    {
          # "Critical";
          print $var_output , "|Time to move=", $time_to_move, ";$o_warn_opt;$o_crit_opt;0;\n";
          exit $ERRORS{"CRITICAL"};

    }
    else
    {
          # "Unknown";
          print $var_output , "|Time to move=", $time_to_move, ";$o_warn_opt;$o_crit_opt;0;\n";
          exit $ERRORS{"UNKNOWN"};

    }
}
