#!/bin/env perl

use strict;
use warnings;
use LATMOS::Accounts;
use Getopt::Long;
use Pod::Usage;
use LATMOS::Accounts::Utils;
use LATMOS::Accounts::Log;
use GraphViz;

=head1 NAME

    la-group -- Graph user/cells-department

=head1 SYNOPSIS

    la-group [options]

=cut

GetOptions(
    'c|config=s' => \my $config,
    'b|base=s'   => \my $base,
    'help'       => sub { pod2usage(0) },
) or pod2usage();

=head1 OPTIONS

=over 4

=item -c|--config configdir

Use this configuration directory instead the default one

=item -b|--base basename

Query this specific base instead default.

=back

=cut

my $LA = LATMOS::Accounts->new($config, noacl => 1);
my $labase = $LA->base($base);
$labase && $labase->load or die "Cannot load base";

my $g = GraphViz->new(
    layout => 'dot',
    overlap => 'false',
    rankdir => 1,
    width => 10, height => 8,
);

open(my $h, '>', 'graph.png') or die 'cannot open graph';

#foreach ($labase->list_objects('user')) {
#    $g->add_node($_);
#}

my %users;
my %cluster;

sub add_user {
    my ($user) = @_;
    $users{$user} and return;
    my $ou = $labase->get_object('user', $user) or return;
    my $dpmt = $ou->get_attributes('department');
    if ($dpmt) {
        $cluster{$dpmt} ||= {
            name => $dpmt,
        };
    }
    $g->add_node($user, ($dpmt ? (cluster => $cluster{$dpmt}) : ()));
    1;
}

$g->add_node('latmos');
foreach my $gr ($labase->list_objects('group')) {
    my $o = $labase->get_object('group', $gr);
    my $sutype = $o->get_c_field('sutype');
    ($sutype || '') =~ /^(dpmt|cell)$/ or next;
    $g->add_node($gr,fillcolor => ($sutype eq 'dpmt' ? 'red' : 'green'), style => 'filled');
    my $manager = $o->get_attributes('managedBy') || '';
    warn "MANAGER $manager";
    if ($manager) {
        add_user($manager);
        $g->add_edge('latmos', $gr);
        $g->add_edge($manager => $gr, weight => 3);
    }
    foreach ($o->get_attributes('member')) {
        $_ eq $manager and next;
        add_user($_);
        warn "$_ => $gr";
        $g->add_edge($gr => $_, weight => 1);
    }
}

print $h $g->as_png;
close($h);
