#!/usr/local/bin/perl
# save_alias.cgi
# Create, update or delete an alias

require './virtual-server-lib.pl';
&ReadParse();
$d = &get_domain($in{'dom'});
&can_edit_domain($d) && &can_edit_aliases() || &error($text{'aliases_ecannot'});
@aliases = &list_domain_aliases($d);
if (!$in{'new'}) {
	($virt) = grep { $_->{'from'} eq $in{'old'} } @aliases;
	%oldvirt = %$virt;
	}
&error_setup($text{'alias_err'});

if ($in{'delete'}) {
	# Just delete the virtuser
	&delete_virtuser($virt);
	&webmin_log("delete", "alias", $virt->{'from'}, $virt);
	}
else {
	# Verify inputs
	if ($in{'new'}) {
		($mleft, $mreason, $mmax) = &count_feature("aliases");
		$mleft == 0 && &error($text{'alias_ealiaslimit'});
		}
	$in{'name_def'} || $in{'name'} =~ /^[A-Za-z0-9\.\-\_]+$/ ||
		&error($text{'alias_ename'});
	$name = $in{'name_def'} ? "" : $in{'name'};
	$virt->{'from'} = $name."\@".$d->{'dom'};
	@values = &parse_alias($in{'name_def'}, $in{'name'},
			       %oldvirt ? $oldvirt{'to'} : undef, "alias", $d);
	@values || &error($text{'alias_enone'});
	$virt->{'to'} = \@values;
	if ($can_alias_comments) {
		$virt->{'cmt'} = $in{'cmt'};
		}

	if ($in{'new'}) {
		# Check for a clash
		if (&check_clash($name, $d->{'dom'})) {
			&error($text{'alias_eclash'});
			}

		# Create the virtuser
		&create_virtuser($virt);
		&webmin_log("create", "alias", $virt->{'from'}, $virt);
		}
	else {
		if ($virt->{'from'} ne $in{'old'}) {
			# Has been renamed .. check for a clash
			if (&check_clash($name, $d->{'dom'})) {
				&error($text{'alias_eclash'});
				}
			}

		# Modify virtuser
		&modify_virtuser(\%oldvirt, $virt);
		&webmin_log("modify", "alias", $virt->{'from'}, $virt);
		}
	}
&redirect("list_aliases.cgi?dom=$in{'dom'}");


