#!/usr/local/bin/perl -w-- # -*- perl -*-
#
# $Id: active_users,v 1.2 1994/09/10 17:58:31 qjb Exp $
# $Source: /home/qjb/scripts/RCS/active_users,v $
# $Author: qjb $
#
# Author: E. Jay Berkenbilt
#
# Generate a list of users who have checked mail sometime in the last
# $maxdays (defined below) days.
#

# This code, from the perl manual page, forces this to be run by perl from 
# perl, sh, or csh.  It must be first.
eval '(exit $?0)' && eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'
& eval 'exec /usr/local/bin/perl -S $0 $argv:q'
    if 0;

$whoami = ($0 =~ m,([^/]*)$,) ? $1 : $0;

# Settable parameters
$maildir = "/var/spool/mail";
$exclude_list = "/usr/local/etc/active_exclude_list";
$maxdays = 14;
$domain = "ERA.COM";
$namewidth = 35;

$exclude = ();
if (open(EXCLUDE, "<$exclude_list"))
{
    while (<EXCLUDE>)
    {
	chop;
	s/#.*//;
	next if (m/^\s*$/);
	$exclude{$_} = 1;
    }
    close(EXCLUDE);
}

$usernames = ((scalar(@ARGV) == 1) && ($ARGV[0] eq "-usernames"));
$sep = "\001";
$threshold = time - $maxdays * 24 * 3600;
opendir(DIR, $maildir) || die "$whoami: can't read directory $maildir: $!\n";
@entries = readdir(DIR);
closedir(DIR);
# Kill . and ..
shift(@entries);
shift(@entries);
@trash = ();
$trash = "";
@active = ();

foreach $f (@entries)
{
    next if (defined($exclude{$f}));
    ($trash, $trash, $trash, $trash, $uid, $trash, $trash, $trash, $atime,
     @trash) = stat("$maildir/$f");
    push (@active, $f) if (($atime > $threshold) &&
			   (&whois($uid) eq $f) &&
			   (&valid($f)));
}

if ($usernames)
{
    @active = sort { $a cmp $b } @active;
    for (@active)
    {
	print $_, "\n";
    }
}
else
{
    @names = ();
    for (@active)
    {
	push(@names, &generate_name($_));
    }
    
    @names = sort { $a cmp $b } @names;
    
    for (@names)
    {
	s/.*$sep//;
	print;
    }
}


sub whois {
    (getpwuid($_[0]))[0];
}

sub valid {
    (getpwnam($_[0]))[0] ne "*";
}

sub generate_name {
    local($name) = (@_);
    local($lname, $rest, $entry, $nspaces);
    ($trash, $trash, $trash, $trash, $trash, $trash, $gcos, @trash) =
	getpwnam($name);
    $gcos =~ m/^(.*) ([^ ]+)$/;
    $lname = $2;
    $rest = $1;
    $entry = "$lname, $rest ";
    $nspaces = $namewidth - (length($entry));
    while (($nspaces % 2) != 0)
    {
	$nspaces--;
	$entry .= " ";
    }
    $entry .= ("- " x ($nspaces / 2));
    $entry .= $name . "@" . $domain . "\n";
    $lname . $sep . $entry;
}
