#!/moira/bin/perl -Tw

# $Id: mailhosts.gen 3956 2010-01-05 20:56:56Z zacheiss $

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

$outfile = '/moira/dcm/mailhosts.out';

use DBI;

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

$sth = $dbh->prepare("SELECT login, potype, exchange_id, imap_id, pop_id FROM users WHERE " .
		     "status = 1 OR status = 2 OR status = 5 OR status = 6") || exit $MR_DBMS_ERR;
$sth->execute || exit $MR_DBMS_ERR;

$tnow = localtime;
umask 022;
open(OUT, ">$outfile") || exit $MR_OCONFIG;

print OUT "; MIT Network Host Table\n;\n";
print OUT "; \t\$" . "Author:" . " \$\n";
print OUT "; \t\$" . "Date:" . " \$\n";
print OUT "; \t\$" . "Revision:" . " \$\n";
print OUT "; Host table generated by Moira at $tnow\n;\n";

while (($login, $potype, $exchange_id, $imap_id, $pop_id) = $sth->fetchrow_array) {
    $login =~ tr/a-z/A-Z/;

    if ($exchange_id != 0) {
	$imap_filesystem = lc($login) . ".po";
	($mach_id) = $dbh->selectrow_array("SELECT mach_id FROM filesys " .
					   "WHERE label = " . $dbh->quote($imap_filesystem) .
					   "AND type = 'IMAP'");
	if (defined($mach_id)) {
	    $pop_id = $mach_id;
	} else {
	    ($mach_id) = $dbh->selectrow_array("SELECT mach_id FROM machine WHERE " .
					       "name = 'IMAP.EXCHANGE.MIT.EDU'");
	    if (defined($mach_id)) {
		$pop_id = $mach_id;
	    }
	}
    }

    if ($imap_id != 0) {
	($mach_id) = $dbh->selectrow_array("SELECT mach_id FROM filesys WHERE " .
					   "filsys_id = " . $dbh->quote($imap_id) .
					   " AND type = 'IMAP'");
	if (defined($mach_id)) {
	    $pop_id = $mach_id;
	}
    }

    ($hostname) = $dbh->selectrow_array("SELECT name FROM machine WHERE mach_id = " .
					$dbh->quote($pop_id));


    if ($pop_id != 0 && $potype ne "NONE") {

	if (16 - length($login) > 8) {
	$sp = "\t";
    }
    else {
	$sp = "";
    }
    $row = "$login$sp\tIN\tCNAME\t$hostname.\n";
    $row =~ s/\0//g;;
    print OUT $row;
}
}

close(OUT);
$dbh->disconnect;

exit 0;
