#!/moira/bin/perl -Tw

# $Id: mailman.gen,v 1.1 2003-01-02 01:05:05 zacheiss Exp $

# The following exit codes are defined and MUST BE CONSISTENT with the
# error codes the library uses:
$MR_DBMS_ERR = 47836421;

$outdir = '/moira/dcm/mailman';
umask 022;

use DBI;

$dbh = DBI->connect("dbi:Oracle:moira", "moira", "moira") || exit $MR_DBMS_ERR;

$sth0 = $dbh->prepare("SELECT m.name FROM machine m, serverhosts sh " .
		     "WHERE m.mach_id = sh.mach_id AND " .
		     "sh.service = 'MAILMAN' AND sh.enable = 1");
$sth0->execute;

while (($hostname) = $sth0->fetchrow_array) {
    open(OUT, ">$outdir/$hostname");

    $sth1 = $dbh->prepare("SELECT l.name, l.memacl_type, l.memacl_id " .
			  "FROM list l, machine m WHERE ".
			  "l.mailman = 1 AND " .
			  "m.name = " . $dbh->quote($hostname) .
			  "AND m.mach_id = l.mailman_id AND l.active = 1" .
			  "AND l.memacl_type != 'KERBEROS'")
	|| exit $MR_DBMS_ERR;
    $sth1->execute;

    while (($listname, $memacl_type, $memacl_id) = $sth1->fetchrow_array) { 
	$row = "$listname:";
	$row =~ s/\0//g;
	print OUT $row;
	
	if ($memacl_type eq "USER") {
	    ($member) = $dbh->selectrow_array("SELECT login FROM users " .
					      "WHERE users_id = " .
					      $dbh->quote($memacl_id)) ||
					      exit $MR_DBMS_ERR;
	    $member = $member . "\@mit.edu";
	    $row = "$member";
	    print OUT $row;
	} else {
	    $sth2 = $dbh->prepare("SELECT UNIQUE i.member_type, i.member_id " .
				  "FROM imembers i, list l " .
				  "WHERE l.list_id = " . 
				  $dbh->quote($memacl_id) .
				  "AND i.list_id = l.list_id " .
				  "AND (i.member_type = 'USER' " .
				  "OR i.member_type = 'STRING')") || 
				  exit $MR_DBMS_ERR;
	    $sth2->execute;
	    $maybecomma = "";

	    while (($type, $id) = $sth2->fetchrow_array) {
		if ($type eq "USER") {
		    ($member) = $dbh->selectrow_array("SELECT login " .
						      "FROM users " .
						      "WHERE users_id = " . 
						      $dbh->quote($id)) ||
                                                      exit $MR_DBMS_ERR;
		    $member = $member . "\@mit.edu";
		}
		elsif ($type eq "STRING") {
		    ($member) = $dbh->selectrow_array("SELECT string " .
						      "FROM strings " .
						      "WHERE string_id = " .
						      $dbh->quote($id)) ||
                                                      exit $MR_DBMS_ERR;
		}
		$row = "$maybecomma$member";
		$row =~ s/\0//g;
		print OUT $row;
		$maybecomma = ",";
	    }
	}
	$row = "\n";
	$row =~ s/\0//g;
	print OUT $row;	
    }
    close(OUT);
}

$dbh->disconnect;

exit 0;
