#!/usr/local/bin/perl -w-- # -*- perl -*-
#
# $Id: discuss-update,v 1.8 1995/07/19 15:53:52 ejb Exp $
# $Source: /home/ejb/scripts/RCS/discuss-update,v $
# $Author: ejb $
#

# 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;

$debug = 0;

&usage if (scalar(@ARGV) < 2);

($group, @files) = (@ARGV);
$discuss_realm = "ERA.COM";
$zephyr_realm = "ERA.COM";

$members = `ypmatch $group group.byname` ||
    die "$whoami: can't get members of group $group\n";
$members =~ s/[\s\n]*//g;
$members =~ s/^.*:([^:]+)$/$1/;
@members = split(',', $members);
for (@members)
{
    $_ .= "@" . $discuss_realm;
    $memberlist{$_} = 1;
}

if ($debug)
{
    print "Members of group $group:\n";
    for (@members)
    {
	print "  $_\n";
    }
}

foreach $file (@files)
{
    (-r $file) || do { print STDERR "$whoami: can't read $file: $!\n"; next; };

    $oldfile = "$file.old";
    rename($file, $oldfile) ||
	die "$whoami: can't rename $file to $oldfile: $!\n";
    open(OLD, "<$oldfile") || die "$whoami: can't read $oldfile\n";
    $n = <OLD>;
    @acl = ();
    while (<OLD>)
    {
	chop;
	next unless m/$discuss_realm$/;
	push(@acl, $_);
    }
    close(OLD);

    @extras = ();
    @chairs = ();
    @others = ();
    foreach $i (@acl)
    {
	$i =~ m/^([^:]*):(.*)$/;
	local($bits, $user) = ($1, $2);
	$access{$user} = $i;
      case:
	{
	    (defined($memberlist{$user})) ||
		do { push(@extras, $user); last case; };
	    ($bits =~ m/c/) && do { push(@chairs, $user); last case; };
	    push(@others, $user);
	    $normal_access = $bits;
	};
    }

    if ($debug)
    {	
	print "From file $file:\n";
	print "extras: \n";
	for (@extras)
	{
	    print $access{$_}, "\n";
	}
	print "chairs: \n";
	for (@chairs)
	{
	    print $access{$_}, "\n";
	}
	print "others: \n";
	for (@others)
	{
	    print $access{$_}, "\n";
	}
    }

    $output = "";
    $n = 0;
    for (@chairs, @others)
    {
	&append_output($access{$_});
    }
    for (@members)
    {
	if (! defined($access{$_}))
	{
	    &append_output("$normal_access:$_");
	}
    }
    for (@extras)
    {
	&append_output($access{$_});
    }

    open(NEW, ">$file") || die "$whoami: can't rewrite $file: $!\n";
    print NEW "$n\n$output";
    close(NEW);
    umask(0);
    system("chown discuss $file >/dev/null 2>&1");
    chmod(0600, $file);
}

sub append_output
{
    local($t) = @_;
    $output .= $t . "\n";
    $n++;
    if ($discuss_realm ne $zephyr_realm)
    {
	$t =~ s/$discuss_realm$/$zephyr_realm/;
	$output .= $t . "\n";
	$n++;
    }
}

sub usage {
    print STDERR "Usage: $whoami group file [ file ... ]\n";
    print STDERR "  file must be a discuss acl.  Update it so that it " .
	"contains members\n";
    print STDERR "  of `group'.\n";
    exit(1);	
}
