#!/usr/bin/perl -w
use strict;

my $conf = "/etc/webmin/update.conf";
my $acl = '/etc/webmin/webmin.acl';

my ($op, $modname) = @ARGV;

#
#  Do help operation
#
if (defined($op) && $op eq 'help')
{
  system('/usr/bin/perldoc', $0) or die "help: $!\n";
  exit;
}

#
# If add or remove must also have a modulename
#
unless (defined($modname))
{
  die "Not enough operands\n";
}

#
# Read ACL file
#
my %access;
open (ACL, $acl) or die "$acl: $!\n";
foreach (<ACL>)
{
  chomp;
  next if /^$/;
  my ($key, $value) = split /:/;
  $access{$key} = $value;
}
close ACL;

 open (CONF, $conf) or die "$conf: $!\n";
 my @lines = <CONF>;
 close CONF;

 my @users = ();
 map { push @users, split; } @lines;

#
# Do add or remove operation
#
if ($op eq 'add')
{
  foreach my $user (@users)
  {
    if (exists($access{$user}))
    {
      my @mods = split /\s+/, $access{$user};
      unless (scalar grep {/^$modname$/} @mods)
      {
        push @mods, $modname;
        $access{$user} = join ' ', @mods;
      }
    }
  }
}
elsif ($op eq 'remove')
{
  foreach my $user (@users)
  {
    if (exists($access{$user}))
    {
      my @mods = split /\s+/, $access{$user};
      $access{$user} = join ' ', grep {!/^$modname$/} @mods;
    }
  }
}
else
{
  die "Invalid operation\n";
}

#
# make backup and write out new ACL file
#
rename ($acl, "$acl.bak") or die "rename: $!\n";
open (ACL, ">$acl") or die "new $acl: $!\n";
map { print ACL "$_: $access{$_}\n"; } (keys %access);
close ACL;


__END__


=pod
 
=head1 NAME
 
update-webmin -- Adds or removes a module from the webmin ACL
 
=head1 SYNOPSIS
 
B<update-webmin> add modulename

B<update-webmin> remove modulename

B<update-webmin> help
 
=head1 DESCRIPTION
 
This script should be run by webmin modules to add or remove themselves from 
the access control list.  It behaves differently based on the operation 
requested. 

=head2 add

A file F</etc/webmin/update.conf> is read which contains a list of users who 
should initially be allowed to access the module. This file has no fixed 
format, the only requirement is that user names be seperated by whitespace.
Further access control can be done by the administrator through the B<webmin>
user configuration applet.  A module should call this in its' postinst script. 

=head2 remove

The module is removed from all users ACLs.  A module should call this in its' 
prerm script.

=head2 help

Displays this manual page.
 
=head1 AUTHOR
 
Jaldhar H. Vyas E<lt>jaldhar@@debian.orgE<gt>
 
=head1 LICENSE
 
This code is free software under the Crowley Public License ("Do what
thou wilt shall be the whole of the license")
 
=head1 VERSION
 
1.1 -- May 15, 2004
 
=cut
