#!/usr/bin/perl
#
# Check tftp server
#
# this needs tftp installed, and modprobe nf_conntrack_tftp
#
# $Header: /home/doke/work/nagios/RCS/check_tftp,v 1.2 2016/05/04 17:57:20 doke Exp $


use strict;
use warnings;
use Getopt::Long;

use vars qw( $host $verbose $help @crits @warns @unknowns @oks @ignores );

$ENV{PATH}='/usr/bin';

$verbose = 0;
$help = 0;


sub usage {
    my( $rc ) = @_;
    print "Usage: $0 [-vh] -H <host>
    -v    verbose
    -h    help
";
    exit $rc;
    }

Getopt::Long::Configure ("bundling");
GetOptions(
    'H=s' => \$host,
    'v+' => \$verbose,
    'h' => \$help,
    );
usage( 0 ) if ( $help );
usage( 1 ) if ( ! $host );

check_tftp( $host );

my $rc = 0;
my $sep = '';
if ( $#crits >= 0 ) {
    $rc = 2;
    print "CRITICAL ", join( ", ", @crits );
    $sep = '; ';
    }
if ( $#warns >= 0 ) {
    $rc = 1 if ( $rc == 0 );
    print $sep, "Warning ", join( ", ", @warns );
    $sep = '; ';
    }
if ( $#unknowns >= 0 ) {
    $rc = -1 if ( $rc == 0 );
    print $sep, "Unknown ", join( ", ", @unknowns );
    $sep = '; ';
    }
if ( $rc == 0 ) {
    print "Ok ", join( ", ", @oks );
    $sep = '; ';
    }
if ( $#ignores >= 0 ) {
    print $sep, "Ignoring ", join( ", ", @ignores );
    }

print "\n";
exit $rc;


##################



sub check_tftp { 
    my( $host ) = @_;
    my( $cmd, $got );

    $cmd = "tftp -v '$host' -c get /nagios/tftp_test_file /tmp/tftp_test_file";
    $verbose && print "+ $cmd\n";
    if ( ! open( pH, '-|', $cmd ) ) {
	push @unknowns, "can't run $cmd: $!";
	return;
	}
    $got = '';
    while( <pH> ) {
	chomp;
	$verbose && print "< $_\n";
	if ( m%^Received \d+ bytes%i ) {
	    $got = $_;
	    push @oks, $got;
	    }
	}
    if ( ! $got ) { 
	push @crits, "can't tftp get /nagios/tftp_test_file";
	}
    }  # check_tftp

