#!/usr/bin/perl

# rpmtc  (rpm transitive closure)
# This script queries the rpm database to extract what dependencies a
# package has and classify them.

@args = @ARGV;
$iarg = @args;
$name = $args[--$iarg];
$start_flag=1;
$detail_flag=0;

if (-e ".pathway") {
  unlink ".pathway";
}


while ($iarg>0) {
  $arg = $args[--$iarg];
  $flag = $args[--$iarg];

  if ($flag eq "-path") {
    `ln -s "$arg" ".pathway"`;
  }
  if ($arg eq "-detail") {
    $detail_flag=1;
    $iarg++;
  }
}

#exit 0;
#print "detail flag is now ";
#print $detail_flag."\n";

my %todolist, %donelist;

# start with the list of direct dependencies
@result = `rpmdep-pipe $name 1`;
#print "perl rpmdep-pipe $name = @result\n";

$start_flag=0;
$cnt = @result;

if ($cnt==0) {
  print "Can't find package $name.\n";
  exit 0;
}

chomp(@result);

if ($result[0] =~ /no dependency/) {
  print @result;
  print "\n";
  exit 0;
}

foreach $resitem (@result) {
  $todolist{$resitem} = 1;
}

# add new packages to todo list if they don't exist in donelist
do {
  #	print "Iteration ---------------\n";
  foreach $todo (keys(%todolist)) {
    $donelist{$todo} = 1;
    @result = `rpmdep-pipe $todo 0`;
    chomp(@result);
    #		print "package deps for $todo = @result\n";
    foreach $resitem (@result) {
      $found = 0;
      foreach $done (keys(%donelist)) {
	#				print "does $resitem = $done ?\n";
	if ($resitem eq $done) { $found = 1; } 
      }
      if ( !$found ) { $todolist{$resitem} = 1; }
      #			print "found = $found\n";
    }
		}
  # remove completed tasks from todo list
  foreach $todo (keys(%todolist)) {
    foreach $done (keys(%donelist)) {
      if ($todo eq $done) {
	delete $todolist{$todo};
      }
    }
  }
  
  #print "todolist: ", keys(%todolist),"\n";
  #print "donelist: ", keys(%donelist),"\n";
} until %todolist == () ;
#print "\n";
foreach $dep (sort keys(%donelist)) {
  if ($detail_flag==0) {
    if ($dep =~ /([^-]*)-/) {
      print $1." \n";
    }
  }
  else {
    print $dep." \n";
  }    
}
print "\n";

unlink ".pathway";
