#!/usr/bin/perl

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

&ReadParse();

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

$serveur = &get_system_hostname();

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

use DB_File;
tie %LIST,'DB_File',"/etc/ovhm.db";
$login = $LIST{"$domaine"};
untie(%LIST);

$mdpsql1=$in{mdpsql1};
$mdpsql2=$in{mdpsql2};
if ($mdpsql1 or $mdpsql2) {
        &error ("Les 2 mots de passe sql ne sont pas identiques") if ($mdpsql1 ne $mdpsql2);
        &error ("Le mot de passe sql est trop court<br>Minimum 5 caractères") if ($mdpsql1 !~ /.{5}/);
}

foreign_call("mysql","execute_sql_logged","mysql", "create database $login");
foreign_call("mysql","execute_sql_logged","mysql", "GRANT ALL PRIVILEGES ON $login.* to $login\@localhost identified by '$mdpsql1'");
foreign_call("mysql","execute_sql_logged","mysql", "GRANT ALL PRIVILEGES ON $login.* to $login\@$serveur identified by '$mdpsql1'");

system "cd /home/$login/www/; tar xjf /usr/libexec/webmin/ovhm/phpMyAdmin-2.2.2-php.tar.bz2";
system "mv /home/$login/www/phpMyAdmin-2.2.2 /home/$login/www/phpmyadmin";
open CONFIG, "/home/$login/www/phpmyadmin/config.inc.php";
@config = <CONFIG>;
close CONFIG;
open CONFIG, ">/home/$login/www/phpmyadmin/config.inc.php";
foreach $c (@config) {
	$c =~ s/^(\$cfgServers\[1\]\[\'user\'\]\s+= )'root';/$1'$login\';/g;
	$c =~ s/^(\$cfgServers\[1\]\[\'password\'\]\s+= )'';/$1\'$mdpsql1\';/g;
        $c =~ s/^(\$cfgServers\[1\]\[\'only_db\'\]\s+= )'';/$1\'$login\';/g;
	print CONFIG $c;
}
close CONFIG;

open HTACCESS, ">/home/$login/www/phpmyadmin/.htaccess";
print HTACCESS <<EOF;
AuthUserFile /home/$login/www/phpmyadmin/.htpasswd
AuthGroupFile /dev/null
AuthName "Statistiques"
AuthType Basic
<Limit GET POST>
require valid-user
</Limit>
EOF
close HTACCESS;

system "/usr/local/apache/bin/htpasswd -n -b $login $mdpsql1 > /home/$login/www/phpmyadmin/.htpasswd";

system ("chown $login.users -R /home/$login/www/phpmyadmin");


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

