#!/moira/bin/perl -Tw

# $Id: ca.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 = 47836460;

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

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

# First, let's do people with NFS homedirs, since it's not hard.
$sth = $dbh->prepare("SELECT n.nfsphys_id, n.dir, m.name ".
		     "FROM nfsphys n, machine m ".
		     "WHERE m.mach_id = n.mach_id ".
		     "ORDER BY n.nfsphys_id") || exit $MR_DBMS_ERR;

$sth->execute || exit $MR_DBMS_ERR;

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

while (($id, $dir, $machname) = $sth->fetchrow_array) {
    next if ($id == 0);
    $foo = $dbh->prepare("SELECT u.login, u.fullname ".
			 "FROM users u, filesys f ".
			 "WHERE f.label = u.login AND u.status = 1 ".
			 "AND f.phys_id = " . $dbh->quote($id));
    $first = 1;
    $foo->execute || exit $MR_DBMS_ERR;
    while (($login, $fullname) = $foo->fetchrow_array) {
	if ($first) {
	    $first = 0;
	    $row = "*$machname:$dir\n";
	    $row =~ s/\0//g;
	    print OUT $row;
	}
	$row = "$login,$fullname\n";
	$row =~ s/\0//g;
	print OUT $row;
    }
}

#Now, let's do all the AFS homedirs.  This will take a while longer.
$sth = $dbh->prepare("SELECT UNIQUE u.login, u.fullname, f.name ".
		     "FROM users u, filesys f ".
		     "WHERE f.label = u.login AND u.status = 1 ".
		     "AND f.type = 'AFS' ".
		     "ORDER BY u.login") || exit $MR_DBMS_ERR;

$sth->execute || exit $MR_DBMS_ERR;

$last = "";
while (($login, $name, $dir) = $sth->fetchrow_array) {
    $dir =~ /(\/.*)\//;
    $path = $1;
    if ($path ne $last) {
	$last = $path;
	$row = "*AFS:$path\n";
	$row =~ s/\0//g;
	print OUT $row;
    }
    $row = "$login,$name\n";
    $row =~ s/\0//g;
    print OUT $row;
}

close(OUT);
$dbh->disconnect;

exit 0;
