#!@@PERL@@ -w
# -*- perl -*-
# vim: ft=perl : sw=4 : ts=4 : et

=head1 NAME

yum - Plugin for monitoring pending package upgrades with yum

=head1 USAGE

This plugin needs to be called with the 'update' argument
from cron to work as intended.

=head1 AUTHOR

Copyright 2006 Dagfinn Ilmari Mannsåker <ilmari@lonres.com>

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

 #%# family=auto
 #%# capabilities=autoconf

=cut

use strict;

my $statefile = "$ENV{MUNIN_PLUGSTATE}/yum.state";

sub update {
    if (-l $statefile) {
    die "$statefile is a symlink, not touching.\n";
    }

    open my $state, '>', $statefile
    or die "Can't open $statefile for writing: $!\n";

    open my $yum, '-|', 'yum list updates'
    or die "Can't run 'yum list updates': $!";

    # Skip header crap
    while (<$yum>) {
    last if /^Updated/;
    }

    while (<$yum>) {
    next unless /^(\S+)\.\S+\s+\S+\s+\S+/;
    print $state "$1\n";
    }

    close $yum or die "Error running 'yum list updates': $!\n";
    close $state or die "Error writing $statefile: $!\n";
}

sub autoconf {
    if (system('yum --version >/dev/null 2>/dev/null') != 0) {
        print "no (Could not run yum)\n";
    }
    elsif (! -r $statefile) {
        print "no (Could not find statefile.  Please read 'munindoc yum')\n";
    }
    else {
        print "yes\n";
    }
    exit 0;
}

sub config {
    print "graph_title Pending packages\n";
    print "graph no\n";
    print "pending.label pending\n";
    print "pending.warning 0:0\n";
}

sub report {
    my @packages;

    open my $state, '<', $statefile
    or die "Can't open $statefile for reading: $!
Please read 'munindoc yum' to understand why if the file does not exist.\n";

    chomp(@packages = <$state>);
    close $state;

    print 'pending.value ', scalar(@packages), "\n";
    print 'pending.extinfo ', join(' ', @packages), "\n"
    if @packages;
}

if ($ARGV[0]) {
    my $arg = $ARGV[0];
    my %funcs = (
        update   => \&update,
        config   => \&config,
        autoconf => \&autoconf,
    );

    if (exists $funcs{$arg}) {
    $funcs{$arg}->();
    } else {
    die "Unknown argument '$arg'\n";
    }
} else {
    report();
}
