#!/bin/env perl -w
#
# $Id: depgraph 11860 2010-12-09 03:47:03Z skayser $
#
# Copyright 2006 Cory Omand <comand@blastwave.org>
# All rights reserved.  Use is subject to license terms.
#
# Redistribution and/or use, with or without modification, is
# permitted.  This software is without warranty of any kind.  The
# author(s) shall not be liable in the event that use of the
# software causes damage.
#
# depgraph - draw a 'dot' graph showing GAR package interdependencies
#

use strict;

my ($graph_all, $output_dot) = (0, 0);
foreach my $arg (@ARGV) {
    $graph_all  = 1 if $arg eq '-all';
    $output_dot = 1 if $arg eq '-dot';
}

my $dot   = "dot";
   $dot  .= " -Earrowhead=dot -Edot_radius=0.5 -Earrowtail=none";
   $dot  .= " -Nshape=diamond -Nfontsize=12";
   $dot  .= " -Tpng";

sub makeDigraph {
    my ($name, @makefiles) = @_;

    printf STDERR "  %12s ... ", $name;
    
    if (@makefiles) {
        my $device;
        if ($output_dot) {
            $device = \*STDOUT;
        } else {
            open DOT, "| $dot -o $name.png" or die "Failed to open PNG stream: $!";
            $device = \*DOT;
        }

        print $device "digraph sunx {\n";

        foreach my $makefile (@makefiles) {
            open FH, $makefile or die "Failed to open $makefile: $!\n";
            my @lines = <FH>;
            close FH;

            my ($garname, @deps);
            foreach (@lines) {
                if (/^NAME\s*=\s*(\S*)\s*$/) {
                    $garname = $1;
                    next;
                }
                if (/^(?:DEPENDS|LIBDEPS)\s*\+?=\s*(.+)$/) {
                    push @deps, split /\s+/, $1;
                    next;
                }
            }

            foreach (@deps) {
                my ($dummy, $depname) = split '/', $_;
                print $device qq{"$garname" -> "$depname"\n};
            }
        }
        print $device "}\n";
        close $device;

        print STDERR "ok\n";

    } else {
        print STDERR "nothing to do\n";
    }
}

print STDERR "\nCreating digraphs:\n\n";

if ($graph_all) {
    foreach my $subdir (`gfind -type d -mindepth 1 -maxdepth 1 -not -name meta`) {
	chomp $subdir; $subdir =~ s/^\.\///;
	makeDigraph "sunx_$subdir", `gfind $subdir -type f -mindepth 2 -maxdepth 2 -name Makefile`;
    }
}

makeDigraph "sunx_all", `gfind . -type f -mindepth 3 -maxdepth 3 -name Makefile | grep -v ./meta`;

print STDERR "\nComplete.\n\n";
