#!/usr/bin/perl -w
#
# mrtg-eth0
# John Simpson <jms1@jms1.net> 2007-08-28
#
# gathers eth0 packet counts from the kernel and prints it in a format
# suitable for use by MRTG
#
# 2007-09-15 jms1 - fixed a bug where packet counts were not always being
#   read correctly from /proc/net/dev
#
###############################################################################
#
# Copyright (C) 2007 John Simpson.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################

require 5.003 ;
use strict ;

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

sub uptime()
{
	open ( I , "</proc/uptime" ) or die "/proc/uptime: $!\n" ;
	my $line = <I> ;
	close I ;

	$line =~ m|^(\d+)| ;
	my $s = $1 ;

	my $d = int ( $s / 86400 ) ; $s %= 86400 ;
	my $h = int ( $s /  3600 ) ; $s %=  3600 ;
	my $m = int ( $s /    60 ) ; $s %=    60 ;

	if ( $d > 0 ) { return sprintf ( "%d days %2d:%02d:%02d" , $d , $h , $m , $s ) ; }
	if ( $h > 0 ) { return sprintf ( "%d:%02d:%02d" , $h , $m , $s ) ; }
	if ( $m > 0 ) { return sprintf ( "%d:%02d" , $m , $s ) ; }
	return "$s seconds" ;
}

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

my $if = "eth0" ;

my $in = 0 ;
my $out = 0 ;
my $uptime = uptime() ;
my $system = `hostname -f` ;

open ( I , "</proc/net/dev" )
	or die "/proc/net/dev: $!\n" ;
while ( my $line = <I> )
{
	if ( $line =~ m|\s*$if\:\s*(.+)| )
	{
		my @w = split ( /\s+/ , $1 ) ;
		( $in , $out ) = ( $w[0] , $w[8] ) ;
		last ;
	}
}
close I ;

print "$in\n$out\n$uptime\n$system" ;