# cluster-software-lib.pl
# common functions for installing packages across a cluster

do '../web-lib.pl';
&init_config();
require '../ui-lib.pl';
&foreign_require("servers", "servers-lib.pl");

# list_software_hosts()
# Returns a list of all hosts whose software is being managed by this module
sub list_software_hosts
{
local @rv;
local $hdir = "$module_config_directory/hosts";
opendir(DIR, $hdir);
foreach $h (readdir(DIR)) {
	next if ($h =~ /\.host$/ || $h eq '.' || $h eq '..');
	local %host = ( 'id', $h );
	opendir(PDIR, "$hdir/$h") || next;
	foreach $p (readdir(PDIR)) {
		next if ($p eq "." || $p eq "..");
		local %pkg;
		&read_file("$hdir/$h/$p", \%pkg);
		push(@{$host{'packages'}}, \%pkg);
		}
	closedir(PDIR);
	&read_file("$hdir/$h.host", \%host);
	push(@rv, \%host);
	}
closedir(DIR);
return @rv;
}

# save_software_host(&host)
# Add or update a managed host with it's package list
sub save_software_host
{
local $hdir = "$module_config_directory/hosts";
mkdir($hdir, 0700);
if (-d "$hdir/$_[0]->{'id'}") {
	opendir(DIR, "$hdir/$_[0]->{'id'}");
	foreach $f (readdir(DIR)) {
		unlink("$hdir/$_[0]->{'id'}/$f");
		}
	closedir(DIR);
	}
else {
	mkdir("$hdir/$_[0]->{'id'}", 0700);
	}
foreach $p (@{$_[0]->{'packages'}}) {
	&write_file("$hdir/$_[0]->{'id'}/$p->{'name'}", $p);
	}
local %h = %{$_[0]};
delete($h{'packages'});
&write_file("$hdir/$_[0]->{'id'}.host", \%h);
}

# delete_software_host(&host)
sub delete_software_host
{
unlink("$module_config_directory/hosts/$_[0]->{'id'}.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 = &servers::list_servers();
return ( &servers::this_server(), grep { $_->{'user'} } @servers );
}

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

1;

