#!/usr/bin/perl -w
# $Id: bkp-dot.in.in,v 1.3 2003/12/17 01:17:24 x99laine Exp $
# Copyright (c) 2003 Jeremy Lain

use strict;
use lib '/usr/share/bkp';

use Getopt::Std;
use Bkp;

# package 
my $package = "bkp-dot";

# config and options
my (%opts,%hosts,%colors);

### functions ###

sub syntax {
   print "[ This is $package (bkp v0.5.2), a plotting utility ]\n\n",
        "Syntax:\n",
        "  $package <action> [options]\n\n",
	" Actions:\n",
        "  -h           - this help message\n",
        "  -f <file>    - process config file <file>\n",
        "  -b <batch>   - process batch file <batch>, which has this format:\n\n",
        "                 host1=/path/to/first_conf_file\n",
        "                 host2=/path/to/other_conf_file\n",
        "                 ...\n",
        " Options:\n",
        "  -o <output>  - send output to <ouput> rather than the standard output\n",
}

### main ###

sub init {
  if ( not getopts('hf:b:o:', \%opts) or $opts{'h'}) {
    &syntax();
    exit(1);
  }

  my(%batch,$host);
  if ($opts{'b'}) {
    # batch file
    my $config = new Config::General( -file =>$opts{'b'},
                                      -AllowMultiOptions =>"yes",
                                      -LowerCaseNames =>"yes",);
    %batch = $config->getall;
  } else {
    #  single config file
    $host = `hostname`;
    chomp($host);
    $batch{$host} = $opts{'f'} ? $opts{'f'} : $Bkp::confile;
  }

  # read config files
  my @pal = qw(blue red green black purple grey orange lightblue lightred);
  my $pl = @pal;
  my $i = 0;
  foreach $host(keys %batch) { 
    %{$hosts{$host}} = Bkp::read_conf($batch{$host});
    $colors{$host} = $pal[$i % $pl];
    $i++;
  }
}


sub main {
  &init;
 
  my $count = scalar(keys %hosts);
  my $i = 0;
  print "digraph bkp {\n".
        "ratio=0.67;\n".
        "size=\"11,7.5\";\n".
        "rotate=90;\n";
 
  foreach my$host(keys %hosts) {
    my %conf = %{$hosts{$host}};

    # add node for current host
    print "\n$host [color=".$colors{$host}.",fontcolor=".$colors{$host}."];\n\n";

    # connect nodes
    foreach my $remote (@{$conf{'all'}{'remotes'}}) {
      my %robj = %{$conf{'remotes'}{$remote}};
      my $label = (join " ", @{$robj{'sections'}}).
                  ($robj{'class'} ? "\\n($robj{'class'})" : "");
      print "$remote->$host"."[label=\"$label\"";
      print ",fontcolor=".$colors{$remote}.",color=".$colors{$remote}
        if ($colors{$remote});
      print "];\n";
    }
    $i++;  
  }
  
  print "\n}\n";
 
}


&main;
