# net-lib.pl
# Common local networking functions

do '../web-lib.pl';
&init_config();
%access = &get_module_acl();

if (-r "$module_root_directory/$gconfig{'os_type'}-$gconfig{'os_version'}-lib.pl") {
	do "$gconfig{'os_type'}-$gconfig{'os_version'}-lib.pl";
	}
else {
	do "$gconfig{'os_type'}-lib.pl";
	}

# list_hosts()
# Parse hosts from /etc/hosts into a data structure
sub list_hosts
{
local @rv;
local $lnum = 0;
open(HOSTS, $config{'hosts_file'});
while(<HOSTS>) {
	s/\r|\n//g;
	s/#.*$//g;
	s/\s+$//g;
	if (/(\d+\.\d+\.\d+\.\d+)\s+(.*)$/) {
		push(@rv, { 'address' => $1,
			    'hosts' => [ split(/\s+/, $2) ],
			    'line', $lnum,
			    'index', scalar(@rv) });
		}
	$lnum++;
	}
close(HOSTS);
return @rv;
}

# create_host(&host)
# Add a new host to /etc/hosts
sub create_host
{
open(HOSTS, ">>$config{'hosts_file'}");
print HOSTS $_[0]->{'address'},"\t",join(" ",@{$_[0]->{'hosts'}}),"\n";
close(HOSTS);
}

# modify_host(&host)
# Update the address and hosts of a line in /etc/hosts
sub modify_host
{
&replace_file_line($config{'hosts_file'},
		   $_[0]->{'line'},
		   $_[0]->{'address'}."\t".join(" ",@{$_[0]->{'hosts'}})."\n");
}

# delete_host(&host)
# Delete a host from /etc/hosts
sub delete_host
{
&replace_file_line($config{'hosts_file'}, $_[0]->{'line'});
}

# parse_hex(hex)
# Convert an address like ff000000 into 255.0.0.0
sub parse_hex
{
$_[0] =~ /(..)(..)(..)(..)$/;
return join(".", (hex($1), hex($2), hex($3), hex($4)));
}

# interfaces_chooser_button(field, multiple, [form])
# Returns HTML for a javascript button for choosing an interface or interfaces
sub interfaces_chooser_button
{
  local $form = @_ > 2 ? $_[2] : 0;
  local $w = $_[1] ? 500 : 300;
  return "<input type=button onClick='ifield = document.forms[$form].$_[0]; chooser = window.open(\"$gconfig{'webprefix'}/net/interface_chooser.cgi?multi=$_[1]&interface=\"+escape(ifield.value), \"chooser\", \"toolbar=no,menubar=no,scrollbars=yes,width=$w,height=200\"); chooser.ifield = ifield' value=\"...\">\n";
}

1;

