#!/usr/bin/perl -w

eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
    if 0; # not running under some shell

#
# This is the update daemon for rrdbrowse
# run this every 5 minutes from cron
#
# $Id: rbupdate,v 1.8 2003/04/28 21:01:18 tommy Exp $
#

$|=1;	# flush output

use strict;
use RRD::Config;
use RRD::Info;
use DirHandle;
use Time::HiRes qw(usleep gettimeofday);
use Getopt::Std;

use vars qw(%opts);

my $maxchld = 3; 	# hardcoded default
my $numchld = 0;

$SIG{CHLD} = sub { wait(); $numchld--; };

getopts("ph", \%opts);
die <<HELP if $opts{h};
Usage: $0 [-p]

This is the RRDBrowse update daemon. You should run this from
cron every 5 minutes. Use -p to display performance statistics.
HELP

if ( defined $config{processes} ) { $maxchld = $config{processes}; }
$maxchld = 1 if $opts{p};

Traverse ($config{nfopath});

sub UpdateNFO {
    my ($nfo) = @_;

    my $info = new RRD::Info($nfo);
    $info->CheckPaths;

    print ("Starting $nfo.. ") if $opts{p};
    my $time = gettimeofday() if $opts{p};
    $info->Update;
    my $diff = gettimeofday() - $time if $opts{p};
    printf ("%.3f s\n",$diff) if $opts{p};
    exit(0);
}

sub Spawn {
    my ($nfo) = @_;

    my $pid = fork();
    die "There is no spoon to fork" unless defined($pid);
    $numchld++;

    if ($pid==0) { UpdateNFO($nfo); }

    while ( $numchld >= $maxchld ) { usleep(1000); }
}

sub Traverse {
    my ($dir) = shift;
  
    my $dh = new DirHandle($dir)  || die $!; 
    while(my $f = $dh->read) {
      next if ($f =~ m/^\.|^\.\./ );
      Traverse("$dir/$f") if ( -d "$dir/$f" );
      next if ($f !~ m/\.nfo$/ );

      Spawn("$dir/$f");
    }
    $dh->close;
}

