#!/usr/bin/perl

$|=1;
#=============================
#
#      SUB's


sub usage {
    print "
Make a dot file from debian dependancies

usage:
apt-dot -p <package name> [-o <dotfile>]
";
} 



#===== mieux que getopts
sub getArgs {
    my @args=@_;
    my $oldKey="";
    my %opts=();
    for $el (@args) {
	if ($el=~/^-/) {
	    $el=~s/-+//g;
	    $opts{$el}="";
	    $oldKey=$el;
	}
	else {
	    $opts{$oldKey}=$el;
	}
    }
    return %opts;
}
#=============================



#==========================
# MAIN


#------------------------
#                       |
#Gestion des entrées :
my %opts=();
%opts=getArgs(@ARGV);

if((exists $opts{h}) || (exists $opts{help})) {
    &usage();
    exit 0;
}

if (exists $opts{p}) {
    $pack=$opts{p};
} else {
    &usage();
    exit 0;
}

if (exists $opts{o}) {
    $output=$opts{o};
} else {
    $output="";
}

#                       |
#------------------------


#------------------------
#                       |
#Initialisation:

if ($output) {
    open(OUT,">$output");
    *STDOUT=*OUT;
}

my %hashPack;
$hashPack{$pack}=1;

print "digraph HTML {\n";
print "node [ shape=box ];\n";

sub getListDep {
	my $pack=shift;
	my @listPack;
	$pack=~s/\"//g;
	my @strDepends=`apt-cache depends $pack`;
	@strDepends=grep (/^.*Depends:/,@strDepends);
	for $key (@strDepends) { 
	    $key =~s/.*Depends: *//;
	    chomp $key;
	    push(@listPack,$key) if ($key);
	}
	return \@listPack;
}

$pursuing=1;

while ($pursuing) {
    for my $lpack (keys(%hashPack)) {
	next if ($lpack =~ /->/);
	$pursuing=0;
	print STDERR "=====================\n Dependance de $lpack : \n";
	my @listPack=@{getListDep($lpack)};
	
	for my $depPack (@listPack) {
	    if (exists $hashPack{"$depPack"}) {
		if (!exists $hashPack{"\"$depPack\" -> \"$lpack\""}) {
		    $hashPack{"\"$depPack\" -> \"$lpack\""}=1;
		}
	    } else {
		$hashPack{"$depPack"}=1;
		$hashPack{"\"$depPack\" -> \"$lpack\""}=1;
		$pursuing=1;
	    }
	}
    }
}

for $key (keys(%hashPack)) {
    if ($key !~ /->/) { $key='"'.$key.'"';}
    print "$key\n";
}
print "}\n";
close if ($output);



#=================================
#
#         End Main
#
#=================================




