#!/bin/sh
eval 'exec perl -x -S $0 ${1+"$@"}'
#! perl

use warnings;
use strict;

BEGIN { unshift @INC , "."; }

use RRDutils qw( :DEFAULT :Web );

die "\nUsage RRDnode host\n\n" unless @ARGV;

sub nodeTarget($$$$$) {
   my ( $html , $host , $target , $single , $hash ) = @_ ;

   my @hosts = getHosts $target ;
# snmptables under revision
#   my %names = map { (ref($_) eq 'ARRAY') ? (@$_)[0] : $_ => $_ } @hosts ;
   my %names = map { $_ => $_ } @hosts ;
   return unless $names{$host};

   $target =~ s+^.*\.++ ;

#IMPROVE: Include a 'principal graph' tag on the conffile
   my $graph = $$single[0] ;
   my $period = (split /,/ , $$hash{$graph}{'periods'})[0];

# snmptables under revision
#      if ( $names{$host} ne $host ) {
# WHY THIS STRANGE TABLE DETECTION ??
#            my ( $host , @indexes ) = @{$names{$host}} ;
#            for my $idx ( @indexes ) {
# FIXME: The mkdir should not be necessary, as only one file is created
#               mkdir "$graphdir/$host/$target" ; # needed if idx is not concat
#               mkdir "$graphdir/$host/$target.$idx";
#               my $imgname = $getNAME{'src'}( "$target.$idx" , $graph , $period );
#               if ( $$single[1] ) {
#                  print $html htmlAnchor( $imgname , "$target.$idx" );
#               } else {
#                  print $html htmlAnchor( $imgname , "$target.$idx" , $graph );
#                  }
#               }
#      } else {
# FIXME: The mkdir should not be necessary, as only one file is created
#         mkdir "$graphdir/$host/$target";
         my $imgname = $getNAME{'src'}( $target , $graph , $period );
         if ( $$single[1] ) {
            print $html htmlAnchor( $imgname , $target );
         } else {
            print $html htmlAnchor( $imgname , $target , $graph );
            }
#         }
   }

my $host = shift ;

opendir( DIR , $confdir ) ;
my @confs = grep { /^[^.]/ } readdir(DIR) ;
closedir( DIR );

# Better using $getNAME{'html'}
my $html = openWeb( "$host/index" , "Index for $host" );

for my $conf ( @confs ) {
   chomp $conf;

   my %graphs = getGraphs $conf ;
   unless ( %graphs ) {
      warn "No graph defined at $conf\n";
      next;
      }

   changeDefs $conf ;

   my @single ;
   for my $graph ( keys %graphs ) {
      push @single , $graph unless $graphs{$graph}{'type'} eq 'PH' ;
      }

   my @tags = getTags $conf;
   my @targets = ( $conf , map { "$conf.$_"} @tags );

   for my $target ( @targets ) {
      nodeTarget( $html , $host , $target , \@single , \%graphs );
      }
   }

closeWeb($html);

