#!/usr/bin/perl

use ovhmlib;

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

&ReadParse();

&error ("Le module de gestion d'apache n'est pas utilisable") unless &foreign_check("apache");
&foreign_require("apache","apache-lib.pl");

$domaine=$in{domaine};
&error ("Quel domaine ?") if (!$domaine);

$alias=$in{alias};
&error ("Quel alias ?") if (!$alias);

&error ("Domaine non valide") if ($alias !~ /^[0-9a-zA-Z]+(-[0-9a-zA-Z]+)*(\.[0-9a-zA-Z]+)+$/);

use DB_File;
tie %LIST,'DB_File',"/etc/ovhm.db";

# domaine déjà utilisé ?
&error ("Ce domaine à déjà été installé") if ($LIST{$alias});

# domaine déjà utilisé comme alias ?
foreach my $key (sort keys %LIST){
        my $val = $LIST{$key};
        if ($val eq "$alias") {
                $temp = $key;
                $temp =~ s/_alias_$alias//;
                &error ("Ce domaine ($val) est utilisé en alias de : $temp");
        }
}

# création de l'alias :

# bind
ovhmlib::bind_ajouter($alias, "non");

# apache

$conf = &foreign_call("apache","get_config");
@virt = &foreign_call("apache","find_directive_struct","VirtualHost", $conf);
foreach $v (@virt) {
	$vm = $v->{'members'};
	$sname = &foreign_call("apache","find_directive","ServerName", $vm);
	if ($sname eq "www.$domaine") {
		$id = &indexof($v, @$conf);
		last;
	}
}
$vconf = $conf->[$id];
&lock_file($vconf->{'file'});
$lref = &read_file_lines($vconf->{'file'});
splice(@$lref, $vconf->{'line'}+1, 0, "ServerAlias $alias", "ServerAlias www.$alias");
&flush_file_lines();
&unlock_file($vconf->{'file'});

# qmail
$cmd = "/home/vpopmail/bin/vaddaliasdomain $alias $domaine";
system ("$cmd");


$str = $domaine . "_alias_" . $alias;
$LIST{$str} = $alias;
untie(%LIST);

&redirect("alias.cgi?domaine=$domaine");
