#!/afs/athena/contrib/perl/perl

require 'open3.pl';

$lists = '/afs/sipb.mit.edu/user/marc/lists/moira-lists';

&open3('MRIN','MROUT','','mrtest');

open(LISTS,$lists);
while(<LISTS>) {
    next if /^#/ || /^\s*$/;
    /^([^\s]+)/;
    $list = $1;

    $lists{$list}++;
    push(@lists,$list);
}
close(LISTS);

print "Start:\n";

print MRIN "connect\nauth\n";

for $list (@lists) {

# get list info

#    print "query glin $list\n";
    print MRIN "query glin $list\n";
    $ans = <MROUT>; <MROUT>;
    $ans =~ s/^(moira:  )*//;
    if ($ans =~ /^moira/) {
	$error{"glin $list"} = $ans;
    } else {
	print $ans;
	$info{$list} = $ans;
    }

# get owned lists

#    print "query gaus LIST $list\n";
    print MRIN "query gaus LIST $list\n";
    while(<MROUT>) {
	s/^(moira:  )*//;
	if (/^moira/ && !/No records in database match query/) {
	    $error{"gaus $list"} = $_;
	}
	last if /(\d+) tuple/;
	chop;
	/^LIST, / && !$lists{$'} &&
	    ($added .= $'."\n" , $lists{$'}++, push(@lists,$'));
    }

# get lists which this list is a member of

#    print "query glom LIST $list\n";
#    print MRIN "query glom LIST $list\n";
#    while(<MROUT>) {
#	s/^(moira:  )*//;
#	if (/^moira/ && !/No records in database match query/) {
#	    $error{"glom $list"} = $_;
#	}
#	last if /(\d+) tuple/;
#	/^([^,]+),/ && !$lists{$1} &&
#	    ($added .= $1."\n" , $lists{$1}++, push(@lists,$1));
#    }
#
#    <MROUT> if $1 eq 0;
}
print MRIN "quit\n";

close(MROUT);
close(MRIN);

print "Done.\n";

print "\nErrors:\n";
foreach (sort keys(%error)) {
    print $_,": ",$error{$_};
}

print "\nAdded lists:\n",$added;

print "\nACL's not in list:\n";
foreach (values(%info)) {
    split(/, /);
    print $_[8]," (",$_[0],")\n" if (!defined($info{$_[8]}));
}


print "\nHierarchy of lists:\n";
foreach (values(%info)) {
    split(/, /);
    $sublist{$_[8]} .= $_[0].$; if ($_[0] ne $_[8]);
    $acl{$_[0]} = $_[8];
}

foreach (sort keys(%acl)) {
    &printsubs($_,0) if ($acl{$_} eq $_);
}

sub printsubs {
    local($list,$level) = @_;

    print substr(sprintf("%-27s %s",("    " x $level).$list,
			 (split(/,\s*/,$info{$list}))[9]),
		 0,79),"\n";
    local(@subs) = split(/$;/,$sublist{$list});
    foreach (sort @subs) {
	&printsubs($_,$level+1);
    }
}
