#!/s/std/bin/perl

# $Id: facultylist.pl,v 1.14 2008/12/16 21:57:33 koczan Exp $

# facultylist.pl dumps out info for the faculty webpage

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

# let's try getting column maxlengths and the format via a query
# I don't get the uwphone length because it messes with the format
my $col_length_query = $dbh->prepare("select max(char_length(login)) as loginlen, max(char_length(lastname)) as lastnamelen, max(char_length(firstname)) as firstnamelen, max(char_length(uwoffice)) as uwofficelen, max(char_length(uwbuilding)) as uwbuildinglen from people where faculty != 0 or vfaculty != 0 or (status like '%J%' and login is not null)");
$col_length_query->execute;
my @lengths = $col_length_query->fetchrow_array;
my $format = (join "|", (map ( $_ = "%-".$_."s", @lengths ))) . "|%s";

# get the data (stupid regex ordering)
my $faculty_query = $dbh->prepare("select login, lastname, firstname, uwoffice, uwbuilding, uwphone from people where faculty != 0 or vfaculty != 0 or (status like '%J%' and login is not null) order by substring(lastname from '[A-Z].*\$'), lower(firstname)");

$faculty_query->execute;
while (my $row = $faculty_query->fetchrow_arrayref) {
  my @fac = map { $_ = defined $_ ? $_ : "" } @$row; # stupid undefs
  printf "$format\n", @fac;
}
print "\n";

# Footer
# no footer

# clean up
$col_length_query->finish;
$faculty_query->finish;
$dbh->disconnect;
