#!/usr/local/bin/perl
#
# passwd2pine - translate passwd to pine addressbook
#
# Author: Paul J Murphy <pjm@dcs.ed.ac.uk>
#
# The fullname field will end up falling into one of the following cases:
#
#   Last, First		- A person
#   }group: fullname	- A non-person (determined by group or uid/gid < 1024)
#   ~user: fullname	- A non-person (determined by username or fullname)
#
# This allows the output to be sorted by fullname, with administrative
# accounts left to last (ie the real people come first).
#
# The comment field will contain the groupname of the user, followed by
#   anything from the gecos field which seems to be a comment and not part
#   of the name.

### Start of configurable stuff

$domain = "dcs.ed.ac.uk";

# Regular expression for groups which don't contain people
#   Case is significant.
#   The expression must match the entire groupname string.
$non_people_groups = "local|misc|aliens|cs_dept|\\d*";

# Regular expression for users which are not people
#   Case is significant.
#   The expression must match the entire username string.
$non_people_users = ".*\\d.*";

# Regular expression for words within a fullname which signify a non-person
#   Case is not significant.
#   The expression must match an entire word within the gecos fullname.
$non_people_names = "account|admin|user|system|crew|test|dummy|\
unit|department|student|project|.*\\d.*";

### End of configurable stuff

while(<>) {
    chop;
    ($user, $passwd, $uid, $gid, $gecos, $homedir, $shell) = split(/:/, $_, 7);
    unless ($gr_name = getgrgid($gid)) {
	$gr_name = $gid;
    }

    $nickname = $user;

    $fullname = $gecos;
    $fullname =~ s/,.*//g;	# Reduce gecos to fullname
    $fullname =~ s/[._]/ /g;	# Translate alternate name separators to space
    if ($uid < 1024 ||
	$gid < 1024 ||
	$gr_name =~ /^($non_people_groups)$/o) {
	$fullname = "}$gr_name: $fullname";
    } elsif ($user =~ /^($non_people_users)$/o ||
	     $fullname =~ /\b($non_people_names)\b/io) {
	$fullname = "~$user: $fullname";
    } elsif (($firstname, $lastname, $gecos_comment) =
	     ($fullname =~ /^(.*)[._ ]([^._ \d(][^._ \d]+)( *\(.*)?$/)) {
	$fullname = "$lastname, $firstname";
    }

    $address = "$user\@$domain";

#   $fcc = "";

    $comment = "$gr_name$gecos_comment";

    print "$nickname\t$fullname\t$address\t$fcc\t$comment\n";
}
