#!/usr/bin/perl -w
# -*- perl -*-
# vim: ft=perl

=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

Unknown license

=head1 MAGIC MARKERS

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

=cut

use strict;
use Munin::Common::Defaults;

my $statefile = "$Munin::Common::Defaults::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 {
    my $ret = system('yum --version >/dev/null 2>/dev/null');
    if ($ret == 0) {
	print "yes\n";
	exit 0;
    }
    else {
	print "no\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();
}
