#!/usr/local/bin/perl
# tree.cgi
# Display the package tree

require './software-lib.pl';
&header($text{'index_tree'}, "");
print "<hr>\n";

$spacer = "&nbsp;"x3;

# work out the package heirarchy..
$n = &list_packages();
for($i=0; $i<$n; $i++) {
	push(@pack, $packages{$i,'name'});
	push(@vers, $packages{$i,'version'});
	push(@class, $packages{$i,'class'});
	push(@desc, $packages{$i,'desc'});
	}
@order = sort { lc($pack[$a]) cmp lc($pack[$b]) } (0 .. $n-1);
$heir{""} = "";
foreach $c (sort { $a cmp $b } &unique(@class)) {
	if (!$c) { next; }
	@w = split(/\//, $c);
	$p = join('/', @w[0..$#w-1]);
	if (!defined($heir{$p})) {
		$pp = join('/', @w[0..$#w-2]);
		$heir{$pp} .= "$p\0";
		}
	$heir{$p} .= "$c\0";
	$hasclasses++;
	}

# get the current open list
open(HEIROPEN, "$module_config_directory/heiropen");
while(<HEIROPEN>) {
	chop;
	$heiropen{$_}++;
	}
close(HEIROPEN);
$heiropen{""}++;

# traverse the heirarchy
print "<table width=100%>\n";
&traverse("", 0);
print "</table>\n";
if ($hasclasses) {
	print "<a href=closeall.cgi>$text{'index_close'}</a> $spacer\n";
	print "<a href=openall.cgi>$text{'index_open'}</a><p>\n";
	}

print "<hr>\n";
&footer("", $text{'index_return'});

sub traverse
{
local($s, $act, $i);
print "<tr> <td>", $spacer x $_[1];
if ($_[0]) {
	print "<a name=\"$_[0]\"></a>\n";
	$act = $heiropen{$_[0]} ? "close" : "open";
	print "<a href=\"$act.cgi?what=",&urlize($_[0]),"\">";
	$_[0] =~ /([^\/]+)$/;
	print "<img border=0 src=images/$act.gif></a>&nbsp; $1</td>\n",
	}
else { print "<img src=images/close.gif> <i>$text{'index_all'}</i></td>\n"; }
print "<td><br></td> </tr>\n";
if ($heiropen{$_[0]}) {
	# print sub-folders followed by packages
	foreach $i (@order) {
		if ($class[$i] eq $_[0]) {
			print "<tr> <td>", $spacer x ($_[1]+1);
			print "<img border=0 src=images/pack.gif></a>&nbsp;\n";
			print "<a href=\"edit_pack.cgi?package=",
			      &urlize($pack[$i]),"&version=",
			      &urlize($vers[$i]),"\">",&html_escape($pack[$i].
			      ($vers[$i] ? " $vers[$i]" : "")),"</a></td>\n";
			print "<td>",&html_escape($desc[$i]),"</td>\n";
			print "</tr>\n";
			}
		}
	foreach $s (&unique(split(/\0+/, $heir{$_[0]}))) {
		&traverse($s, $_[1]+1);
		}
	}
}

