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

use warnings;
use strict;

BEGIN { unshift @INC , "."; }

use RRDutils qw( :DEFAULT :Create );

die "\nUsage RRDcreator conf[,conf2,...] [host1 host2 ...]\n\n" unless @ARGV;

sub createTarget($$@) {
   my $target = shift ;
   my $cmdargs = shift ;

   my @hosts = @_ ;
   @hosts = getHosts $target unless @hosts ;
   unless ( @hosts ) {
      warn "No host to process for $target\n";
      return;
      }

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

   for my $host ( @hosts ) {
# snmptables under revision
      if ( ref($host) eq "ARRAY" ) {
         my ( $node , @indexes ) = @{$host};
         print "Creating $target.* for $node at $datadir\n";
         for my $idx ( @indexes ) {
# needed in case index is not concatenated
#            mkdir "$datadir/$node/$target" ;
#            mkdir "$graphdir/$node/$target" ;
            my $res = rrdCreate( $node , "$target.$idx" , @$cmdargs );
            print STDERR "ERROR : $res\n" if $res ;
            }
      } else {
         print "Creating $target for $host at $datadir\n";
         my $res = rrdCreate( $host , $target , @$cmdargs );
         print STDERR "ERROR : $res\n" if $res ;
         }
      }
   }

unless ( -d "$confdir" ) {
   die "Configuration directory '$confdir' does not exists\n";
   }

for my $target ( split /,/ , shift ) {

   my ( $conf , $tag ) = split /\./ , $target ;

   unless ( -f "$confdir/$conf" ) {
      warn "No '$conf' configuration file found\n";
      next;
      }

   my $step = getStep $conf ;
   my $start = getStart $conf ;

   changeDefs $conf ;
   mkdir $datadir ;
   mkdir $graphdir ;

   my @cmdargs = ( "--step" , "$step" ) ;
   push @cmdargs , "--start" , "$start" if $start ;

   my @DSs = getDSs $conf ;
   unless ( @DSs ) {
      warn "No data-sources defined at $conf\n";
      next;
      }

   my @RRAs = getRRAs $conf ;
   unless ( @RRAs ) {
      warn "No round-robin archive defined at $conf\n";
      next;
      }

   push @cmdargs , @DSs , @RRAs ;

   if ( $tag && $tag eq '*' ) {
      for ( getTags $conf ) {
         createTarget( "$conf.$_" , \@cmdargs , @ARGV );
         }
   } else {
      createTarget( $target , \@cmdargs , @ARGV );
      }

   }

