#!/usr/bin/perl
#
# inclist - incorporate mailing list aliases into /etc/aliases
#
# Usage: inclist directory-of-subscriber-files alias-file-name lockfilename
#
# This script reads in an aliases file until the end or until it reaches
# a line which reads "### GENERATED BY INCLIST - DO NOT MODIFY BELOW THIS"
# It then inserts that line and an entry for each mailing list which
# has a file of subscribers in the directory specified. The subscriber
# files are owned by the mailing list owner and named for the list,
# so we just insert these aliases:
#  filename: :include:/directory/filename
#  owner-filename: file's owner
#  filename-request: file's owner
# We make a backup of /etc/aliases before we start to /etc/aliases.bak
# We don't do anything at all if the lock file exists.
#
# This script is intended to be called from root's crontab, and to 
# run as root.
#
# By Alan Schwartz, 1996

$ENV{'PATH'} = "/bin:/usr/bin:/usr/ucb:/sbin:/usr/sbin";
$ENV{'IFS'} = "";

# Program to run after changing /etc/aliases:
$newaliases = "/usr/ucb/newaliases";

$bound="### GENERATED BY INCLIST - DO NOT MODIFY BELOW THIS LINE";

die "Usage: inclist <directory-of-list-files> </etc/aliases> <lockfilename>\n"
  unless $#ARGV == 2;
exit 0 if -r $ARGV[2];
$listdir = $ARGV[0];
$aliases = $ARGV[1];

# Make sure we've got complete pathnames
die "Please use full pathnames as arguments to inclist.\n" 
  if ($listdir !~ m#^/# || $aliases !~ m#^/#);

# Make sure the directory and the file exist
die "$listdir does not exist.\n" unless -d $listdir;
die "$aliases is unreadable.\n" unless -r $aliases;

# Open the list directory and get a list of all the files
die "Unable to open $listdir\n" unless opendir(DIR,$listdir);
@files = grep(m#^[A-Za-z]#,readdir(DIR));
closedir(DIR);

# For each file, get its owner's name
foreach (@files) {
  $owners{$_} = &getowner("$listdir/$_");
}

# Make a backup of the aliases file
system 'cp',$aliases,"$aliases.bak";

# Process the aliases file
$tmpfile = "/tmp/inclist.$$";
die "Unable to open $aliases\n" unless open(ALIASES,$aliases);
die "Unable to create $tmpfile\n" unless open(TMP,">$tmpfile");
while (<ALIASES>) {
  last if /$bound/;
  print TMP;
}
print TMP $bound,"\n\n";
foreach $list (sort keys %owners) {
  print TMP "$list: :include:$listdir/$list\n";
  print TMP "owner-$list: $owners{$list}\n";
  print TMP "$list-request: $owners{$list}\n";
  print TMP "\n";
}
close(TMP);

# Replace aliases file with the new one
#system 'mv',$tmpfile,$aliases

# Run newaliases if appropriate
exec $newaliases if $newaliases;

exit 0;

# Given a full path to a file, return the name of its owner
sub getowner {
  local($the_file) = $_[0];
  local(@stat,@info);
  @stat = stat($the_file);
  @info = getpwuid($stat[4]);
  return $info[0];
}
