#!/usr/bin/perl

use strict;
use warnings;

use Time::HiRes qw/time/;
use FindBin;
use lib "$FindBin::Bin/../../lib";
use Wigo::Probe qw/:all/;

# Test if debian
if ( ! `which yum` )
{
    exit 13;
}

my $now = time;
my $new = {
    'last_update' => $now,
};

persist or persist({});
my $delta_update = $now - persist->{'last_update'} if persist->{'last_update'};

###
# Update
###

if ( !$delta_update or $delta_update > 30 * 60 )
{
    my $errorOnUpdate;
    my $fnret = `LANGUAGE=C yum clean expire-cache 2>&1`;
    if ( $? == 0)
    {
        chomp($fnret);

        foreach my $line ( split "\n" , $fnret )
        {
            if ( $line =~ /^Err(o|eu)r/ )
            {
                $errorOnUpdate = 1;
                push @{ detail->{'Yum-Clean'}->{'Errors'} } , $line;
            }
        }
        
        if ( $errorOnUpdate )
        {
            raise   200;
            message "An error happened when doing yum clean. ";
        }

        ###
        # Upgrade
        # Even if update fail, we want to test if there is no package to update anyway
        ###

        my $packagesToUpdate = {};
        $fnret = `LANGUAGE=C yum --quiet --security check-update 2>&1`;
        chomp $fnret;
        
        my $update = 0;
        my $securityUpdate = 0;
        foreach my $line ( split "\n" , $fnret )
        {
            if($line)
            {
                if ( $line =~ /^Err(o|eu)r|No|Could Not|Trying/)
                {
                    $errorOnUpdate = 1;
                    push @{ detail->{'Yum-List-Security-Updates'}->{'Errors'} } , $line;
                }
                elsif ( my ($name,$version,$repo) = $line =~ /^([a-z0-9._-]+)\s+([a-z0-9._:-]+)\s+([a-z_.-]+)\s*$/ )
                {
                    detail->{'Yum-List-Security-Updates'}->{$repo} ||= [];
                    push @{detail->{'Yum-List-Security-Updates'}->{$repo}}, $name;
                    $securityUpdate++;
                }
                else
                {
                    $errorOnUpdate = 1;
                    push @{ detail->{'Yum-List-Security-Updates'}->{'Errors'} } , $line;
                }
            }
        }

        message "No security packages availables";
        if ( $errorOnUpdate )
        {
            raise   200;
            message "An error happened when doing yum --security check-update. ";
        }

        $fnret = `LANGUAGE=C yum --quiet check-update 2>&1`;
        chomp $fnret;
        foreach my $line ( split "\n" , $fnret )
        {
            if($line)
            {
                if ( $line =~ /^Err(o|eu)r|No|Could Not|Trying/)
                {
                    $errorOnUpdate = 1;
                    push @{ detail->{'Yum-List-Updates'}->{'Errors'} } , $line;
                }
                elsif ( my ($name,$version,$repo) = $line =~ /^([a-z0-9._-]+)\s+([a-z0-9._:-]+)\s+([a-z_.-]+)\s*$/ )
                {
                    detail->{'Yum-List-Updates'}->{$repo} ||= [];
                    push @{detail->{'Yum-List-Updates'}->{$repo}}, $name;
                    $update++;
                }
                else
                {
                    $errorOnUpdate = 1;
                    push @{ detail->{'Yum-List-Updates'}->{'Errors'} } , $line;
                }
            }
        }

        if ( $errorOnUpdate )
        {
            raise   200;
            message "An error happened when doing yum check-update. ";
        }

        if ( $update )
        {
            raise 101;
            message "There is $update packages to update. ";
        }

        if( $securityUpdate )
        {
            raise 300 + ( $securityUpdate < 200 ? $securityUpdate : 199 );
            message "There is $securityUpdate security updates to do. ";
        }

        add_metric { 'Tags' => { 'metric' => 'to_update' },             'Value' => $update };
        add_metric { 'Tags' => { 'metric' => 'to_update_security' },    'Value' => $securityUpdate };
    }
    else
    {
        status 500;
        message "unable to get update list";
    }
}

my $packagesInstalled = `yum list installed | tail -n +3 | wc -l`;
if ( $? == 0 )
{
    chomp $packagesInstalled;
    add_metric { 'Tags' => { 'metric' => 'installed' },         'Value' => $packagesInstalled };
}

persist $new;
output 0;
