#!/usr/bin/perl

########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####


# Error codes (DBI:1xxx, IO: 2xxx)
# IO:
# DBI: 38

use DBI;
use strict;

use lib_module_common;

use vars qw/$confixxInstallScript $createDB $psqldump $mysqldump/;

## /Pre-Main
$createDB = 0;
unless($confixxInstallScript){
  die "Can do 'createDB_install.pl' ONLY from install.pl\n";
}
&header2( &ltext('install_header_db') );
## Pre-Main


## Main
if ( $dbType eq 'mysql' ) {
  &CreateDBMysql;

} else {
  &CreateDBPostgres;
}

my $support_master_module = 0;
&CreateAdminDefaults;

&CreateEvents;

$createDB = 1;
## /Main


## Unterprogramme
sub CreateDBPostgres{
  my $file = $psqldump;
  print &ltext('install_db_psql_pw', $dbUser);
	$bin_psql ||= $bin{'psql'} || 'psql';
  system("$bin_psql -h $dbServer $dbDB -U $dbUser -f $file");
}


sub CreateDBMysql{
  my ($host, $return);

  if($dbServer eq 'localhost'){
		$dbMysqlHost ||= 'localhost';
  } else {
		$dbMysqlHost ||= $hostname;
  }


  my ($dbaddress, $dbh, $sthUser, $sthDb, $weiter, $exists);

  $dbaddress = &makeDSN($dbType,$dbServer,'mysql',$dbPort);

  $dbh = DBI->connect($dbaddress, $dbRootUser, $dbRootPw)
    or die( &ltext('db_connect', '#2018', $DBI::errstr) );

	$sthUser = $dbh->prepare("SELECT User FROM user WHERE User=? AND Host=?");
	$sthDb = $dbh->prepare( "SELECT Host, Db, User FROM db WHERE User=? AND ".
													"Host=? AND db='$dbDB'");

  if ( $dbRootUser ne $dbUser ) {
    $weiter = 1;
    while($weiter){
      $weiter = 0;

      $sthUser->execute( $dbUser, $dbMysqlHost );
      $exists = $sthUser->rows;
      unless( $exists ) {

        print &ltext('install_db_mysql_user_add', $dbUser);

        $dbh->do("INSERT INTO user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv,".
								 " Create_priv, Drop_priv, File_priv, Grant_priv, Alter_priv) ".
								 "VALUES ('$dbMysqlHost', '$dbUser', Password('$dbPw'), 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N')")
					or die("$DBI::errstr\n");
				$dbh->do("FLUSH PRIVILEGES") 
					or die("#2016: $DBI::errstr\n");
				
      }else{

				if(!$rpm_version_flag && &YesNoQuestion( &ltext('install_db_mysql_user_exists', $dbUser, $dbServer))){

					$dbUser = &Question( &ltext('install_question_mysqluser', $dbDB) , 'confixx');
					$dbPw = &PassQuestion( &ltext('install_question_mysqlpass', $dbUser, $dbServer), '');
					$weiter = 1;
					
				}else{
#
# change password
#
					$dbh->do("UPDATE user set Password = Password('$dbPw') WHERE User='$dbUser'") 
						or die("$DBI::errstr\n");
					$dbh->do("FLUSH PRIVILEGES") 
						or die("#2016: $DBI::errstr\n");

				}
      }
      $sthUser->finish;

      unless($weiter){
        print &ltext('install_db_mysql_db_perms', $dbDB);
	
				$sthDb->execute( $dbUser, $dbMysqlHost );
				unless ($sthDb->rows){
      	  $dbh->do("INSERT INTO db (Host, Db, User, Select_priv, Insert_priv, Update_priv,".
									 " Delete_priv,".
									 " Create_priv, Drop_priv, Grant_priv, Alter_priv)".
									 " VALUES ('$dbMysqlHost', '$dbDB', '$dbUser', 'Y', 'Y', 'Y',".
									 " 'Y', 'Y', 'Y', 'Y', 'Y')" )
						or die("$DBI::errstr\n");

					$dbh->do("FLUSH PRIVILEGES") 
						or die("#2016: $DBI::errstr\n");
				}
				$sthDb->finish;
      }
    }
  }

  print &ltext('install_db_db_create', $dbDB),"\n";

	$bin_mysql ||= $bin{'mysql'} || 'mysql';

	my $cmdPrefix = "$bin_mysql -v ";
	$cmdPrefix .= &makeCmdLine( { 'server' => $dbServer, 
																'port' => $dbPort,
																'user' => $dbUser,
																'password' => $dbPw}
														);
	
	my $cmd = "$cmdPrefix -e 'use $dbDB' 2>&1";

	my $out = `$cmd`;
	chomp $out;
  if ( $out ) {
		if ( $out =~ /\Q$dbUser\E\@([^\s'"]+)/ ) { ## Access denied
			$dbMysqlHost = $1;

      $sthUser->execute( $dbUser, $dbMysqlHost );
      unless( $sthUser->rows ) {
				$dbh->do("INSERT INTO user (Host, User, Password, Select_priv, Insert_priv,".
								 " Update_priv, Delete_priv,".
								 " Create_priv, Drop_priv, File_priv, Grant_priv, Alter_priv) ".
								 "VALUES ('$dbMysqlHost', '$dbUser', Password('$dbPw'), 'N', 'N',".
								 " 'N', 'N', 'N', 'N', 'N', 'N', 'N')") or 
									 die("#2016: $DBI::errstr\n");
			}
			$sthUser->finish;

			$sthDb->execute( $dbUser, $dbMysqlHost );
			unless ( $sthDb->rows ) {
				$dbh->do("INSERT INTO db (Host, Db, User, Select_priv, Insert_priv, Update_priv,".
								 " Delete_priv,".
								 " Create_priv, Drop_priv, Grant_priv, Alter_priv)".
								 " VALUES ('$dbMysqlHost', '$dbDB', '$dbUser', 'Y', 'Y', 'Y',".
								 " 'Y', 'Y', 'Y', 'Y', 'Y')" ) or 
									 die("#2016: $DBI::errstr\n");
			}
			$sthDb->finish;

			$dbh->do("FLUSH PRIVILEGES") 
				or die("#2016: $DBI::errstr\n");

			$out = `$cmd`; ## repead checking
			chomp $out;

		}
	}

	unless( $out ) {
    if ( &YesNoQuestion (&ltext('install_db_mysql_db_exists', $dbDB ) ) ) {
      $dbh->do("DROP DATABASE $dbDB") 
				or die("#2017: $DBI::errstr\n");
    }
  }

  $dbh->do("CREATE DATABASE $dbDB") 
    or die("#2017: $DBI::errstr\n");
  $dbh->disconnect;

	$cmd = "$cmdPrefix $dbDB <$mysqldump";
	
  if ( $return = system( $cmd ) ) {
		&hard_error ( &ltext('update_db_table_add_err', $dbDB) );
	}
}


sub CreateAdminDefaults{
  my ($use_webalizer,$use_frontpage);
  (-x $bin_webalizer) ? ($use_webalizer = 1) : ($use_webalizer = 0);
  (-x $bin_fpsrvadm) ? ($use_frontpage = 1) : ($use_frontpage = 0);
  my ($index, $dbh, $dbaddress);
  $index = &ltext('install_default_indexcode', $hostname);
  my ($use_mail);
  if($mta eq "noEmail" || $mta eq ""){
    $use_mail = 0;
  }
  else{
    $use_mail = 1;
  }

  $dbaddress = &makeDSN( $dbType, $dbServer, $dbDB, $dbPort );

  $dbh = DBI->connect($dbaddress, $dbUser, $dbPw) or
		die ( &ltext('db_connect', '#2009', "$DBI::errstr") );

  my $sth = $dbh->prepare("SELECT * FROM webmail_sign");
  $sth->execute or 
		die ("#2020: $DBI::errstr\n");
  while( my @row = $sth->fetchrow_array ){
    # nothing;
  }
	$sth->finish;

  my $use_pop = $mail_pop3Server?1:0;
 
	$use_webmail = 1 unless defined( $use_webmail );
	$use_webftp = 1 unless defined( $use_webftp );

 
  my $sql = "INSERT INTO admin (passwort, mysqlshelluser, mysqlshellpasswort, mysqlshellhost, pop, email,".
    " webftp, webmail, mysql, lokaleips, minuid, " .
    " maxuid, standardip, quota, indexcode, indexfile, cssl, frontpage, statistik, standarddomain,".
    " longpw, dns, ip_pns, ip_sns, dnstemplate,".
    " dnr,  userprefix, spamfilter, coldfusion, cronjobs, modpython, hostname ) " .
    " VALUES ('', '$mysql_shell_user', '$mysql_shell_user_pw', '$mysql_shell_user_host', $use_pop, $use_mail,".
    " $use_webftp,$use_webmail, '$use_mysql', '$lokaleips', '$min_uid',".
    " '$max_uid', '$stdIP', '$use_quota', '$index','index.html', $use_SSL, $use_frontpage,$use_webalizer, '$stdDomain',".
    " '$confixx_admin_pw_crypt','$use_dns','$ip_pns','$ip_sns', ".
    "'##domain##.      86400  IN   A         ##ip##\n".
    "*.##domain##.   86400  IN   A         ##ip##\n\n".
    "##domain##.     86400   IN   MX 10   mail.##domain##.\n\n".
    "##domain##.     86400   IN   NS        ##ns1##.\n".
    "##domain##.     86400   IN   NS        ##ns2##.', " .
    "'$use_dnr', '$user_prefix', '$spamassassin_support', '$coldfusion_support', '$cronjobs_support',
     '$modpython_support', '$hostname' )";
  $dbh->do($sql) or die ("#2010: $DBI::errstr\n");

  my $scponly = '0';
  if ( -x $scponly_shell ) {
    $dbh->do("UPDATE admin SET scponly=1") or 
			die ("#2011: $DBI::errstr\n");
    $scponly = 1;
  }

  if ( $use_phpmyadmin ) {
    $dbh->do("UPDATE admin SET phpmyadmin=1,phpmyadminpfad='$phpmyadminpfad'") or 
			die ("#2011: $DBI::errstr\n");
  }
  if ( $support_master_module ) {
    $dbh->do("UPDATE admin SET business=1") or
			die ("#2022: $DBI::errstr\n");
  }
  if (!$rpm_version_flag) {
    $dbh->do("UPDATE admin SET postconf=1") or
			die ("#2023: $DBI::errstr\n");
  }
  if($use_mysqlshell){
    $dbh->do("UPDATE admin SET mysqlshelluser='$mysql_shell_user', mysqlshellpasswort='$mysql_shell_user_pw',".
             " mysqlshellhost='$mysql_shell_user_host', mysqlshelllongpwcrypt='$mysql_shell_user_pw_crypt',".
             " mysqlshelluid='$mysql_shell_uid'")  or
							 die ("#2012: $DBI::errstr\n");
  }

  $dbh->do("INSERT INTO allgemein (newpwd) VALUES (0)") or
		die ("#2013: $DBI::errstr\n");

  $dbh->do("INSERT INTO grep (type,pattern) VALUES ('ftp','####NEW####')") or
		die ("#2014: $DBI::errstr\n");

  $dbh->do("INSERT INTO zeiten (confixxfaktor,checknewversion) VALUES (2,12)") or
		die ("#2015: $DBI::errstr\n");

  $dbh->do("INSERT INTO register (hinweis) VALUES ('')") or
		die ("#2016: $DBI::errstr\n");

  $dbh->do("UPDATE allgemein SET newpwd=1, httpdupdate=0, aliases=1, webalizerpw=1, domains=1, adduser=1")
		or die ("#2017: $DBI::errstr\n");

	if($bin_fpsrvadm && -x $bin_fpsrvadm){ 
		$dbh->do("UPDATE allgemein SET frontpageadd=1") or
			die ("#2016: $DBI::errstr\n");
	}

  $dbh->do("UPDATE admin SET ftp=1, fehlerseiten=1, pwschutz=1, php=1, phpupload=1, dirlist=1,".
					 " login='$confixx_admin_user', language='$language', ssi=1, perl=1, subdomains=1,".
					 " stdcgi=1, shell=1, wap=1") or
						 die ("#2019: $DBI::errstr\n");
  if( $mta ) {
    $dbh->do("UPDATE admin SET autoresponder=1") or
			die ("#2020: $DBI::errstr\n");
  }

  $dbh->do("INSERT INTO domains (domain, richtigedomain) VALUES (?, '5')", undef, $confixx_domain) or
		die ("#2021: $DBI::errstr\n");

  $dbh->do("INSERT INTO bdefault (defaultserver) VALUES (0)");

  my $idn = '0'; # for comfixx easy 
  if(-x $idn_shell && $idn_vendor){
    $dbh->do("UPDATE admin SET idn=1") or
			die ("#2019: $DBI::errstr\n");
    $idn = '-1';
  }
  
  my $maillist = '0';
  if(-d $majordomo_home && -x $majordomo_wrapper){
    $dbh->do("UPDATE admin SET majordomo=1, majordomohome=".$dbh->quote($majordomo_home).
	", majordomoml=".$dbh->quote($majordomo_ldir)) or
		die ("#2019: $DBI::errstr\n");
    $maillist = '-1';
  }
  
  if ( $install_default_users == 1 ) {
		my( $maxpop, $maxemail);
    $maxpop = $maxemail = $use_mail?'-1':'0';
    my $maxmysql = $use_mysql?'-1':'0';
    my $maxautoresponder = $mta?'-1':'0';
    my $ssl = $use_SSL?'1':'0';
    my $timestamp = time;
    my $maxcronjobs = $cronjobs_support?'-1':'0';
  
    $dbh->do("insert into anbieter (
    anbieter, number, passwort, longpw, maxkunden,
    maxkundenlimit, maxpop, maxpoplimit, maxkb, maxkblimit,
    maxmysql, maxmysqllimit, maxemail,  maxautoresponder, maxemaillimit,
    maxautoresponderlimit, maxftp, maxftplimit, maxtransfer, maxsubdomains,
    maxsubdomainslimit, maxdomains, maxdomainslimit, maxwildcards, php,
    ftp, perl, ssi, cssl, shell,
    statistik, pwschutz, fehlerseiten, webftp, webmail,
    stdcgi, frontpage, anmeldedatum, name, firma,
    anschrift, plzort, telefon, fax, gender,
    firstname, plz, land, emailadresse, kundennummer,
    freifeldname1, freifeldwert1, freifeldname2, freifeldwert2, freifeldname3,
    freifeldwert3, personendatenangeben, kundendatenanzeigen, kundendatenbeikundenanzeigen, indexcode,
    indexfile, hilfecode, standardip, language, lastchange,
    httpdspezial, phpupload, dirlist, dbext, wap,
    coldfusion, dns, pns, sns, dnr,
    maxcronjobs, maxcronjobslimit, spamfilter, maxidn, maxidnlimit,
    maxmaillist, maxmaillistlimit, scponly, maxatdomains, modpython
  
    ) VALUES (
  
    'res0', 0, '', '$confixx_admin_pw_crypt', -1,
    0, $maxpop, 0,  -1, 0,
    $maxmysql, 0, $maxemail, $maxautoresponder, 0,
    0, -1, 0, -1, -1,
    0, -1, 0, -1, 1,
    1, 1, 1, $ssl, 1,
    1, 1, 1, $use_webftp, $use_webmail,
    1, $use_frontpage, '$timestamp', 'res0', '',
    '', '', '', '', '',
    '', '', '', '', '',
    '', '', '', '', '',
    '', 1, 0, 1, '$index',
    'index.html', '', '$stdIP', '$language', '$timestamp',
    '', 1, 1, 1, 1,
    '$coldfusion_support', '$use_dns', '$hostname', '$hostname', '$use_dnr',
    '$maxcronjobs', 0, '$spamassassin_support', '$idn', 0,
    '$maillist', 0, '$scponly', -1, '$modpython_support'
    )") or
			die ("#2024: $DBI::errstr\n");

    $dbh->do("update ipadressen set anbieter='res0' where ip = '$stdIP' and anbieter = ''") or
			die ("#2025: $DBI::errstr\n");
    $dbh->do("insert into skins (cuser, skin) values ('res0','default')") or
			die ("#2026: $DBI::errstr\n");


    my $username = $user_prefix . '0';
    my $userdomain = $username . "." . $stdDomain;

    $dbh->do("insert into domains (domain, kunde, anbieter, richtigedomain, pfad, lastchange, zusatz) 
    VALUES ('$userdomain', '$username', 'res0', '3', '/', '$timestamp','')") or
			die ("#2027: $DBI::errstr\n");
    $dbh->do("insert into domainlog (kunde, neu, domain, loeschen) VALUES ('$username', 1, '$userdomain', 0)");
    $dbh->do("update allgemein set domains = 1") or
			die ("#2028: $DBI::errstr\n");


    $dbh->do("insert into webalizer (kunde, loeschen, neu, anbieter) VALUES ('$username', '0', '1', 'res0')") or
			die ("#2031: $DBI::errstr\n");
    $dbh->do("update allgemein set webalizer='1'") or
			die ("#2032: $DBI::errstr\n");
    $dbh->do("insert into perl (kunde, loeschen, neu, anbieter) VALUES ('$username', '0', '1', 'res0')") or
			die ("#2033: $DBI::errstr\n");
    $dbh->do("update allgemein set perl='1'") or
			die ("#2034: $DBI::errstr\n");
    $dbh->do("update allgemein set stdcgi='1'") or
			die ("#2035: $DBI::errstr\n");

	$scponly = $scponly? 2: '0'; ## need for creating
  
    $dbh->do("insert into kunden (
    kunde, number, uid, passwort, longpw,
    anbieter, maxpop, maxkb, maxmysql, maxemail,
    maxautoresponder, maxftp, maxtransfer, maxsubdomains, php,
    ftp, wildcard, perl, ssi, shell,
    statistik, statistikpasswort, statistiklongpw, pwschutz, fehlerseiten,
    webftp, webmail, stdcgi, anmeldedatum, name,
    firma, anschrift, plzort, telefon, fax,
    gender, firstname, plz, land, emailadresse,
    kundennummer, freifeldname1, freifeldwert1, freifeldname2, freifeldwert2,
    freifeldname3, freifeldwert3, kundendatenanzeigen, ip, quota,
    language, lastchange, phpupload, wap, coldfusion,
    dirlist, httpdspezial, maxcronjobs, spamfilter, maxidn,
    maxmaillist, scponly, maxatdomains, modpython
  
    ) VALUES (
  
    '$username', '0', '0', '', '$confixx_admin_pw_crypt',
    'res0', '$maxpop', '-1', '$maxmysql', '$maxemail',
    '$maxautoresponder', '-1', '-1', '-1', '1',
    '1', '-1', '1', '1', '1',
    '1', '', '$confixx_admin_pw_crypt', '1', '1',
    $use_webftp, $use_webmail, '1', '$timestamp', '$username',
    '', '', '', '', '',
    '', '', '', '', '',
    '', '', '', '', '',
    '', '', '0', '$stdIP', '1',
    '$language', '$timestamp', '1', '1', '1',
    '1', '', '$maxcronjobs', '$spamassassin_support', '$idn',
    '$maillist', '$scponly', '-1', '$modpython_support'
    )") or
			die ("#2036: $DBI::errstr\n");
  
    $dbh->do("update transfer set geloescht = 1 where kunde = '$username'") or
			die ("#2037: $DBI::errstr\n");
    $dbh->do("update allgemein set adduser='1', httpd='1', httpdupdate=1, quota=1") or
			die ("#2038: $DBI::errstr\n");
  }
  

  $sth->finish;
  $dbh->disconnect;
}

sub CreateEvents {

  my $dbaddress = &makeDSN($dbType,$dbServer,$dbDB,$dbPort);

  my $dbh = DBI->connect($dbaddress, $dbUser, $dbPw)
    or die ( &ltext('db_connect', '#2009', "$DBI::errstr") );

#
# from subs_include_events.pl
#
  &install_types($dbh);


  $dbh->disconnect;

}

sub header2{
  my ($header) = @_;
  my ($length, $count, $fix, $space);
  $fix = 35;
  $length = length($header);
  if($length > $fix){
    $fix = $length + 2;
  }
  $space = int(( $fix - $length ) / 2);
  print '#' x $fix, "\n";
  print ' ' x $space;
  print "$header \n";
  print '#' x $fix, "\n\n";
}

## /Unterprogramme
