#!/s/std/bin/perl

# $Id: uids.pl,v 1.1.1.1 2011/01/24 22:21:39 koczan Exp $

# uids.pl dumps out name and uid information for account and passwd files

use strict;
use warnings;

use DBI;
use CSL::Pg;
use CSL::DBs;

my $dbh = DBI->connect($CSL::DBs::csdb)
  or die "Could not connect to CSDB: $!";
$dbh->do("set search_path to csdb");

# If they gave a file, redirect STDOUT to there.
my $outfile = shift @ARGV;
if ($outfile) {
  open STDOUT, '>', $outfile
    or die "$0: Could not open $outfile for writing: $!";
}

# Header
# no header this time

# get the data now
#my $uids_query = $dbh->prepare("select p.login, p.uid, p.lastname, p.firstname from people p, aliases a where p.login is not null and p.uid is not null and p.login = a.alias and a.emaillist is not null order by uid");
my $uids_query = $dbh->prepare("select p.login, p.uid, p.lastname, p.firstname, lower(i.netid) as netid from people p inner join aliases a on p.login is not null and p.uid is not null and p.login = a.alias and a.emaillist is not null left join id_crosswalk_uwmsn i on i.univid = p.univid;");

# the format things like login limits, but we can change it if need be
my $format = "%-10s %-6s %-10s %s";
$uids_query->execute;
while (my $row = $uids_query->fetchrow_hashref) {
  # name-wankery for compatibility
  my $name = "";
  $name .= ($row->{lastname} eq "") ? " " : $row->{lastname};
  $name .= ",$row->{firstname}" if (defined $row->{firstname});
  my $netid = $row->{netid} || "!";
  printf "$format\n", $row->{login}, $row->{uid}, $netid, $name;
}
print "\n";

# Footer
# no footer this time

# clean up
$uids_query->finish;
$dbh->disconnect;
