#!/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;

my $ncols = 2;
my $col = 0;

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

   my @hosts = getHosts $fulltarget ;
# snmptables under revision
#   my %names = map { (ref($_) eq 'ARRAY') ? (@$_)[0] : $_ => $_ } @hosts ;
   my @names;
   for ( map { $_ } @hosts ) {
      if ( ref($_) eq 'ARRAY' ) {
         push @names , map { "$fulltarget.$_" } splice @$_ , 1 if @$_[0] eq $host ;
      } else {
         $fulltarget =~ s+^.*\.++ ;
         push @names , $fulltarget if $_ eq $host ;
         }
      }

   for my $target ( @names ) {

      my $graph = $$single[0] ;
      $graph = $mainGraph if $mainGraph && $$hash{$mainGraph};
      my $period = (split /,/ , $$hash{$graph}{'periods'})[0];

      next if $mainGraph && $mainGraph eq "hidden";

# 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 );
      print $html "<tr>\n" unless $col % $ncols ;
      if ( $$single[1] ) {
         print $html htmlAnchor( $imgname , $target );
      } else {
         print $html htmlAnchor( $imgname , $target , $graph );
         }
      print $html "</tr>\n" if $col % $ncols == $ncols - 1 ;
      $col++;
#         }
      }
   }

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);

