# cluster-useradmin-lib.pl
# common functions for managing users across a cluster

do '../web-lib.pl';
&init_config();
&foreign_require("servers", "servers-lib.pl");
%useradmin_text = &load_language("useradmin");
%text = ( %useradmin_text, %text );
%uconfig = &foreign_config("useradmin");

# list_useradmin_hosts()
# Returns a list of all hosts whose users are being managed by this module
sub list_useradmin_hosts
{
local $hdir = "$module_config_directory/hosts";
opendir(DIR, $hdir);
foreach $h (readdir(DIR)) {
	next if ($h eq "." || $h eq ".." || !-d "$hdir/$h");
	local %host = ( 'id', $h );
	opendir(UDIR, "$hdir/$h");
	foreach $f (readdir(UDIR)) {
		if ($f =~ /^(\S+)\.user$/) {
			local %user;
			&read_file("$hdir/$h/$f", \%user);
			push(@{$host{'users'}}, \%user);
			}
		elsif ($f =~ /^(\S+)\.group$/) {
			local %group;
			&read_file("$hdir/$h/$f", \%group);
			push(@{$host{'groups'}}, \%group);
			}
		}
	closedir(UDIR);
	push(@rv, \%host);
	}
closedir(DIR);
return @rv;
}

# save_useradmin_host(&host)
sub save_useradmin_host
{
local $hdir = "$module_config_directory/hosts";
local %oldfile;
mkdir($hdir, 0700);
if (-d "$hdir/$_[0]->{'id'}") {
	opendir(DIR, "$hdir/$_[0]->{'id'}");
	map { $oldfile{$_}++ } readdir(DIR);
	closedir(DIR);
	}
else {
	mkdir("$hdir/$_[0]->{'id'}", 0700);
	}
foreach $u (@{$_[0]->{'users'}}) {
	&write_file("$hdir/$_[0]->{'id'}/$u->{'user'}.user", $u);
	delete($oldfile{"$u->{'user'}.user"});
	}
foreach $g (@{$_[0]->{'groups'}}) {
	&write_file("$hdir/$_[0]->{'id'}/$g->{'group'}.group", $g);
	delete($oldfile{"$g->{'group'}.group"});
	}
unlink(map { "$hdir/$_[0]->{'id'}/$_" } keys %oldfile);
}

# delete_useradmin_host(&host)
sub delete_useradmin_host
{
system("rm -rf '$module_config_directory/hosts/$_[0]->{'id'}'");
}



# list_servers()
# Returns a list of all servers from the webmin servers module that can be
# managed, plus this server
sub list_servers
{
local @servers = &foreign_call("servers", "list_servers");
return ( { 'id' => 0, 'desc' => $text{'this_server'}, 'type' => 'unknown' },
	 grep { $_->{'user'} } @servers );
}

# auto_home_dir(base, username)
# Returns an automatically generated home directory, and creates needed
# parent dirs
sub auto_home_dir
{
if ($uconfig{'home_style'} == 0) {
	return $_[0]."/".$_[1];
	}
elsif ($uconfig{'home_style'} == 1) {
	return $_[0]."/".substr($_[1], 0, 1)."/".$_[1];
	}
elsif ($uconfig{'home_style'} == 2) {
	return $_[0]."/".substr($_[1], 0, 1)."/".
	       substr($_[1], 0, 2)."/".$_[1];
	}
elsif ($uconfig{'home_style'} == 3) {
	return $_[0]."/".substr($_[1], 0, 1)."/".
	       substr($_[1], 1, 1)."/".$_[1];
	}
}

# server_name(&server)
sub server_name
{
return $_[0]->{'desc'} ? $_[0]->{'desc'} : $_[0]->{'host'};
}

1;

