#!/usr/local/bin/perl
# save_vserv.cgi
# Save virtual server options such as the port and address

require './apache-lib.pl';
&ReadParse();
$access{'vaddr'} || &error($text{'vserv_ecannot'});
$conf = &get_config();
$vconf = $conf->[$in{'virt'}];

if ($in{'delete'}) {
	# Delete a virtual server
	$vname = &virt_acl_name($vconf);
	&lock_file($vconf->{'file'});
	$lref = &read_file_lines($vconf->{'file'});
	if ($vconf->{'line'} && $lref->[$vconf->{'line'}-1] !~ /\S/) {
		# Remove one blank line before vserv
		$vconf->{'line'}--;
		}
	splice(@$lref, $vconf->{'line'},
	       $vconf->{'eline'} - $vconf->{'line'} + 1);
	&flush_file_lines();
	&unlock_file($vconf->{'file'});

	# Remove from acls
	&read_acl(undef, \%wusers);
	foreach $u (keys %wusers) {
		%uaccess = &get_module_acl($u);
		$uaccess{'virts'} = join(' ', grep { $_ ne $vname }
					      split(/\s+/, $uaccess{'virts'}));
		&save_module_acl(\%uaccess, $u) if ($uaccess{'virts'} ne '*');
		}
	&webmin_log("virt", "delete", &virtual_name($vconf, 1));
	&redirect("");
	}
else {
	# Update virtual server and directives
	&error_setup($text{'vserv_err'});

	# Check address
	if (defined($in{'addrs'})) {
		local @addrs = split(/\s+/, $in{'addrs'});
		@addrs || &error($text{'vserv_eaddrs'});
		foreach $a (@addrs) {
			$a =~ s/:(\d+)$//;
			$a eq '*' || $a eq '_default_' ||
			gethostbyname($a) || &check_ipaddress($a) ||
				&error(&text('vserv_eaddr2', $a));
			}
		$addr = join(" ", @addrs);
		}
	else {
		if ($in{'addr_def'}) {
			if ($httpd_modules{'core'} >= 1.2)
				{ $addr = "_default_"; }
			else { $addr = "*"; }
			}
		elsif ($in{'addr'} !~ /\S/) { &error($text{'vserv_eaddr1'}); }
		elsif (!gethostbyname($in{'addr'}) &&
		       !&check_ipaddress($in{'addr'}))
			{ &error(&text('vserv_eaddr2', $in{'addr'})); }
		else { $addr = $in{'addr'}; }
		}

	# Check port
	if ($in{'port_mode'} == 0) { $port = ""; }
	elsif ($in{'port_mode'} == 1) { $port = ":*"; }
	elsif ($in{'port'} !~ /^\d+$/) {
		&error(&text('vserv_eport', $in{'port'}));
		}
	else { $port = ":$in{'port'}"; }

	# Check document root
	if (!$in{'root_def'}) {
		(-d $in{'root'}) ||
			&error(&text('vserv_eroot', $in{'root'}));
		$root = $in{'root'};
		}

	# Check server name
	if (!$in{'name_def'}) {
		$in{'name'} =~ /^\S+$/ ||
			&error(&text('vserv_ename', $in{'name'}));
		$name = $in{'name'};
		}

	# Update <VirtualHost> directive
	&lock_file($vconf->{'file'});
	$lref = &read_file_lines($vconf->{'file'});
	$lref->[$vconf->{'line'}] = "<VirtualHost $addr$port>";

	# Update DocumentRoot and ServerName
	&save_directive("DocumentRoot", $root ? [ $root ] : [ ],
			$vconf->{'members'}, $conf);
	&save_directive("ServerName", $name ? [ $name ] : [ ],
			$vconf->{'members'}, $conf);

	# write out file
	&flush_file_lines();
	&unlock_file($vconf->{'file'});
	&webmin_log("virt", "save", &virtual_name($vconf, 1), \%in);
	&redirect("virt_index.cgi?virt=$in{'virt'}");
	}

