#!/usr/bin/perl

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


BEGIN {
  use FindBin;
  use lib "$FindBin::Bin/subs";
  use lib "$FindBin::Bin/scripts";
}

use File::Basename;
use Sys::Hostname;
use Socket;
use POSIX;

use lib_module_common;
use lib_module_db;

use strict;

$confixxState = 'configure';

## einige Variablen
$OSTYPE = `uname -s`;
chop($OSTYPE);

$language = 'en';



# it is replaced during make

$version = '3.0.9';
$langfileversion = '3.0.7';



umask 077;

#
# clean lof-file
#
if ( open(LOG ,'>INSTALLATION_PROBLEMS.LOG') ) {
	close (LOG);
} else {
	warn "Can't open file 'INSTALLATION_PROBLEMS.LOG' to write: $!\n";
}


my $wDir = &getCanonPath( dirname( $0 ) );

my @need_binaries = ( 'grep', 'cp', 'find', 'chown', 'rm', 'chmod',
											'ifconfig', 'du', 'sendmail', 'gzip', 'tar', 
											'su', 'ldd', 'df' );

my @ftpDaemons = ('ProFTPD', 'wu-ftpd', 'vsftpd');
my @mtas = ('sendmail', 'postfix', 'qmail');
my $configFile = "$wDir/.config";
$ENV{"LANG"}='C'; # ifconfig
$ENV{"LANGUAGE"}='C'; # ifconfig
my $EXTERNAL = 0;
## /einige Variablen

## Pre-Main
foreach my $script qw( subs_include_questions.pl 
											 subs_include_files.pl
											 subs_include_modules.pl
											 subs_include_check.pl
											 subs_include_db.pl
										 ) {
	safe_do "$wDir/subs/$script";
}

foreach my $binary (@need_binaries){
  $bin{$binary} = &getBin($binary);
}
## /Pre-Main

## Main
system("clear");
&choose_language;
$EXTERNAL = &check_external;
unless( $EXTERNAL ) {
  &Welcome;
}

&confirmLicence;
&checkRequirement;

safe_do "$wDir/subs/subs_include_IDN.pl";
safe_do "$wDir/subs/scponly_install.pl";

&GetUserInfo;
&writeTmpFile;
&Goodbye;
## /Main

## UNTERPROGRAMME
sub get_version_of_SuSE() {
	my ($file) = @_;
	$file = '/etc/SuSE-release' unless (defined $file);

	open(FILE, "<$file")
		or die("Can not open file '$file' for reading: $!\n");
	while (<FILE>) {
		chomp;
		return '9.0' if /^SuSE Linux 9\.0/;
		return $1 if /^\s*VERSION\s*=\s*(\d+\.\d+)/;
	}
	close(FILE)
		or die("Can not close file '$file': $!\n");
	return undef;
}

sub GetUserInfo{
  my ($weiter);
  my ($dist,$dist_ver);

  if(-e '/etc/mandrake-release' ) {
    $dist = 'mandrake';

  } elsif ( -e  '/etc/redhat-release' ) {
    $dist = 'redhat';

  } elsif ( -e '/etc/SuSE-release' ) {
    $dist = 'suse';
		$dist_ver = &get_version_of_SuSE('/etc/SuSE-release');

	} elsif ( -e '/etc/debian_version' ) {
    $dist = 'debian';
  }

  my $default_installDir = '/root/confixx';
  my $default_ftpLogFile = '/var/log/xferlog';
  my $default_userHomeDir = '/home/www';

  if ( $dist =~ /(redhat|mandrake|debian)/ ) {
    $default_userHomeDir = '/var/www';

  } elsif ($OSTYPE eq 'FreeBSD') {
     $default_userHomeDir = '/usr/home/www';

  } elsif ($dist =~ /suse/) {
     $default_userHomeDir = '/srv/www/htdocs';
  }

  my $default_shell = '/bin/bash';
  if ($OSTYPE eq 'FreeBSD') {
     $default_shell = '/bin/sh';
  }
  my $default_emailHomeDir = '/home/email';
  my $default_dbUser = 'root';
  my $default_Pw = ' ';
  my $default_dbDB = 'confixx';
  my $default_dbServer = 'localhost';
  my $default_confixxUser = 'confixx';
  my $default_confixxGroup = 'confixx';
  my $default_confixxHomeDir = '/home/confixx';
  my $default_hostname = 'www.confixx.de';
  my $default_confixxAdminUser = 'Administrator';
  my $default_mailSpool = '/var/spool/mail';
  my @maildrops = ('/var/spool/mail/USER', 'HOMEDIR/Mailbox', 'HOMEDIR/Maildir/');
  my @httpds = ('apache1.3', 'apache2.0');
  my $default_httpd_conf = '/etc/httpd/conf/httpd.conf';

	foreach my $path ( '/usr/local/apache/conf/httpd.conf',
										 '/usr/local/etc/apache/httpd.conf',
										 '/usr/local/etc/apache/httpd.conf',
										 '/etc/httpd/httpd.conf',
										 '/etc/httpd/conf/httpd2.conf', ## mandrake 10.0
										 '/etc/apache/conf/httpd.conf'
									 ) {
		if ( -e $path ) {
			$default_httpd_conf = $path;
			last;
		}
	}


  my $default_mysql_homeDir = '/var/lib/mysql';
  if(-d '/var/db/mysql' ) {
    $default_mysql_homeDir = '/var/db/mysql';
  }

  my $default_popGroup = 'poponly';
  my $default_userGroup = 'ftponly';
  my $default_apacheGroup = 'www';
  my $default_apacheUser = 'www';

  if($dist =~ /(redhat|mandrake)/){
    $default_apacheGroup = 'apache';
    $default_apacheUser = 'apache';

  } elsif ($dist =~ /debian/) {
    $default_apacheGroup = 'www-data';
    $default_apacheUser = 'www-data';

  } elsif ($dist =~ /suse/) {
    $default_apacheGroup = 'www';
    $default_apacheUser = 'wwwrun';
  }

  my $default_PIDDir = '/var/run/confixx';
  my $default_mysql_shell_user = 'mysqlshell';
  my $default_postgres_shell_user = 'postgresshell';
  my $default_postgresRootUser = 'postgres';
	my (%admin);

  ## Datenbanken
  if ($dbType eq 'mysql'){
    $bin{'mysql'} = &getBin('mysql');
    $bin{'mysqldump'} = &getBin('mysqldump');

  } else {
    $bin{'psql'} = &getBin('psql');
  }

	$default_dbServer = $EXTERNAL? 'remotehost.tld': 'localhost';

	my( $dbh, $sth );
	if ( $EXTERNAL ) {
		($dbServer,$dbDB,$dbUser,$dbPw,$dbPort) = &configDbAccess();
		$db_address = &makeDSN( $dbType, $dbServer, $dbDB, $dbPort );
		eval {
			$dbh = DBI->connect( $db_address, $dbUser, $dbPw );
		};

		if ( $dbh ) {
			$sth = $dbh->prepare("SELECT * FROM admin");
			if ( $sth->execute ) {
				%admin = %{$sth->fetchrow_hashref};
			}
			$sth->finish;
			$dbh->disconnect;
		} else {
			print STDERR "Error: unable to connect to Confixx database: $DBI::errstr\n";
		}

	} else { ## MAIN Confixx

    if ( $dbType eq 'mysql' ) {
			($dbServer,$dbRootUser,$dbRootPw,$dbPort)  = &configRootDbAccess();
			
			my ($ptrHash,$errstr) = &getMysqlInfo( { 'user' => $dbRootUser,
																							 'server' => $dbServer,
																							 'password' => $dbRootPw,
																							 'port' => $dbPort}
																					 );
			if ( $ptrHash ) {
				( undef, $dbMysqlHost) = split( /@/, $ptrHash->{'current user'} );
				$dbMysqlVersion = $ptrHash->{'server version'};
			} else {
				print STDERR "Error: unable to connect to database: $errstr\n";
			}

			($dbDB,$dbUser,$dbPw) = &configNewDbAccess();

		} else { ## PosgreSQL
			($dbServer,$dbDB,$dbUser,$dbPw,$dbPort) = &configDbAccess();
		}
		$db_address = &makeDSN( $dbType, $dbServer, $dbDB, $dbPort );
  }

  ## /Datenbanken


  $hostname = hostname();
  my $address = gethostbyname($hostname);
  $hostname = gethostbyaddr($address, AF_INET);
  if ($hostname eq ""){
    $hostname = $default_hostname;
  }
  else{
    $default_hostname = $hostname;
  }
  $hostname = &ServerQuestion( &ltext('install_question_hostname') , $default_hostname);
  $installDir = &PathQuestion( &ltext('install_question_installdir') , $default_installDir);
  $PIDDir = "$installDir/run";
  
  if ( $EXTERNAL ) {
		$user_prefix = $admin{'userprefix'};
	} else {
    $user_homeDir = &PathQuestion( &ltext('install_question_userhomedir') , $default_userHomeDir);
    $userGroup = &UGQuestion( &ltext('install_question_usergroup') , $default_userGroup);
    $user_prefix = "";
    while(($user_prefix !~ /^[A-Za-z][\w]{0,4}$/)){
      $user_prefix = &Question( &ltext('install_question_userprefix') , 'web');
      if($user_prefix !~ /^[A-Za-z][\w]{0,4}$/){
        print &ltext('install_question_userprefix_error');
      }
    }
    $user_prefix =~ tr/A-Z/a-z/;
  }
	$stdShell = $default_shell;

  if ($OSTYPE eq 'Linux') {
    $passwdDir = '/etc/passwd';
    $shadowDir = '/etc/shadow';
  }
  elsif ($OSTYPE eq 'FreeBSD') {
    $passwdDir = '/etc/passwd';
    $shadowDir = '/etc/master.passwd';
  }
  $groupDir = '/etc/group';

	my ( @ips, $apacheDefaultLog);

  if ( $EXTERNAL ) {
#
# get min,max uid & amend mit MAIN
#
    my $default_min_uid = &GetMinUID + 110;  ## +10 forwards for mail lists
    $min_uid = $default_min_uid + 35;
		if ( $admin{'minuid'} && ( $admin{'minuid'} > $min_uid ) ) {
			$min_uid = $admin{'minuid'};
		}

    my $default_max_uid = &GetMaxUID;
    $max_uid = $default_max_uid;
		if ( $admin{'maxuid'} && ( $admin{'maxuid'} < $max_uid ) ) {
			$max_uid = $admin{'maxuid'};
		}
	
    if(&FindUID($min_uid, $max_uid)){
      &ltext('install_question_finduid', $min_uid, $max_uid);
			exit 1;
    }

	} else {
    $httpd = &SelectQuestion( &ltext('install_question_httpd') , @httpds);
		if ($dist =~ /suse/ && $httpd eq "apache2.0") {
			$default_httpd_conf = "/etc/apache2/httpd.conf";
		}
		if ($dist =~ /debian/ && $httpd eq 'apache2.0' )	{
			$default_httpd_conf = "/etc/apache2/apache2.conf";
		}
    $httpd_conf = &FileQuestion( &ltext('install_question_httpdconf') , $default_httpd_conf);
    my $apacheDir = dirname($httpd_conf);
    $vhost_conf = "$apacheDir/confixx_vhost.conf";
    $mhost_conf = "$apacheDir/confixx_mhost.conf";
    $fpfake = "$apacheDir/fpfake";
    @ips = &GetLocalIPs;
    $lokaleips = time();
    $lokaleips .= ":";
    $lokaleips .= join(':', @ips);
    $stdIP = &SelectQuestion( &ltext('install_question_stdip') , @ips);

    my $defaultApacheScript = '/etc/init.d/httpd';
    if ($dist =~ /debian/) {
			if ( $httpd eq 'apache2.0' )	{
				$defaultApacheScript = '/etc/init.d/apache2';
			} else {				
      	$defaultApacheScript = '/etc/init.d/apache';
			}	
    } elsif ($dist =~ /suse/ && $httpd eq 'apache1.3') {
      $defaultApacheScript = '/etc/init.d/apache';
    } elsif ($dist =~ /suse/ && $httpd eq 'apache2.0') {
      $defaultApacheScript = '/etc/init.d/apache2';
    }

    my $apacheScript = &FileQuestion(&ltext('install_question_apache_script'), $defaultApacheScript);

		my $reload = &getReloadKey($apacheScript,'reload','restart') || 'reload';

    $pm_apache_reload = "$apacheScript $reload";
    $pm_apache_start  = "$apacheScript start";

    my %apacheOwner = ('User'=>$default_apacheUser,
		      'Group'=>$default_apacheGroup);

    unless (&checkApacheConfig($apacheDir,\%apacheOwner)){
      $apacheUser = &UGQuestion( &ltext('install_question_apacheuser') , $apacheOwner{'User'});
      $apacheGroup = &UGQuestion( &ltext('install_question_apachegroup') , $apacheOwner{'Group'});
    }else{
      $apacheUser = $apacheOwner{'User'};
      $apacheGroup = $apacheOwner{'Group'};
    }

    $apacheDefaultLog = '/var/log/httpd';
    if ($dist =~ /suse/ && $httpd eq "apache2.0") {
      $apacheDefaultLog = '/var/log/apache2';
    } elsif ( $dist =~ /debian/ ) {
      $apacheDefaultLog = '/var/log/apache';
    }
    $apacheLogDir = &PathQuestion( &ltext('install_question_apachelog') , "$apacheDefaultLog/confixx");
    $apacheBackupDir = "$apacheDefaultLog/old";
    $apacheBackupSize = 10*1024;
	
    my $default_min_uid = &GetMinUID + 110;  ## +10 forwards for mail lists
    $min_uid = $default_min_uid;
    my $default_max_uid = &GetMaxUID;
    $max_uid = $default_max_uid;
    if(&FindUID($min_uid, $max_uid)){
      &ltext('install_question_finduid', $min_uid, $max_uid);
	  exit 1;
    }    
    $min_uid += 35;
	
    $stdDomain = &Question( &ltext('install_question_stddomain', $user_prefix . '##.' . $hostname) , $hostname);

#
# SSL settings
#
    $use_SSL = &YesNoQuestion( &ltext('install_question_ssl') );
		$bin{'openssl'} = &getBin('openssl',$use_SSL? 0: 1);
		unless($bin{'openssl'} && -x $bin{'openssl'}){
			if ($use_SSL){
				$bin{'openssl'} = &BinQuestion(&ltext('install_bin_path','openssl'),
																			 '/usr/bin/openssl');
			}
		}
		if($bin{'openssl'} && -x $bin{'openssl'}){
			my $default_sslKeyDir = "$apacheDir/ssl.key";
			unless(-d $default_sslKeyDir){
				$default_sslKeyDir = dirname($apacheDir).'/ssl.key';
			}
			if ($use_SSL){
				$sslKeyDir = &PathQuestion( &ltext('install_question_sslkey'), 
																		$default_sslKeyDir);
			}else{
				$sslKeyDir = $default_sslKeyDir;
			}
			my $default_sslCrtDir = dirname($sslKeyDir).'/ssl.crt';
			$default_sslCrtDir =~ s/\/\//\//; ## // -> /
			if ($use_SSL){
				$sslCrtDir = &PathQuestion( &ltext('install_question_sslcrt'),
																		$default_sslCrtDir);
			}else{
				$sslCrtDir = $default_sslCrtDir;
			}
		}
#
# end SSL settings
#
    if(&YesNoQuestion( &ltext('install_question_webalizer') )){
      $bin{'webalizer'} = &getBin('webalizer');
    }
    $bin{'gzip'} = &getBin('gzip');
    $bin{'unzip'} = &getBin('unzip',"don't ask");
		if ( ! ( $bin{'unzip'} && -x $bin{'unzip'} ) 
				 && &YesNoQuestion( &ltext( 'install_question_unzip' ) ) ) {
			$bin{'unzip'} = &getBin('unzip');
		}
    if(&YesNoQuestion( &ltext('install_question_frontpage') )){
      my $fpversion = &SelectQuestion( &ltext('install_question_fpversion') ,
																			 "FPSE 2000 (4.0)", "FPSE 2002 (5.0)");
      if($fpversion =~ /2000/){
        $bin{'fpsrvadm'} = &getBin('fpsrvadm.exe', 0, "/usr/local/frontpage/version4.0/bin", "/usr/lib/frontpage/version4.0/bin");

      } else {
        $bin{'fpsrvadm'} = &getBin('owsadm.exe', 0, "/usr/local/frontpage/version5.0/bin", "/usr/lib/frontpage/version5.0/bin");
      }
      my $default_fphome = '/usr/local/frontpage';
      if($bin{'fpsrvadm'} =~ /(\/\S+\/frontpage)\/\S+/){
        $default_fphome = $1;
      }
      $fp_homeDir = &DirQuestion( &ltext('install_question_frontpagedir') , $default_fphome);
      $fp_uid = (getpwnam('bin'))[2];
      $fp_gid = (getpwnam('bin'))[3];
    }
  }

  ## dns & dnr
  if ( $use_dns = &YesNoQuestion( &ltext('install_question_dns' ) ) ) {

    if ( $EXTERNAL ) {
      $dns_server = 2;
    } else {
      $dns_server = 1;
    }

		safe_do "$wDir/subs/subs_include_dns.pl";

		&configureDns( $dist );

  } else {
    $dns_server = 0;
  }

  ## /dns & dnr

  ## IDN-support
  if(&YesNoQuestion( &ltext('install_question_IDN') )){

    safe_do "$wDir/subs/IDN_install.pl";

    ($idn_vendor,$idn_shell,$iconv_shell,$iconv_utf8) = &idnConfigure(\%bin);

  }
  ## /IDN-support

  ## /Allgemeine Einstellungen

  ## Confixx Webseiten
  unless ( $EXTERNAL ) {
    $confixx_domain = &Question( &ltext('install_question_confixxdomain') , $hostname );
    if(!(&YesNoQuestion( &ltext('install_question_confixxip_stdip', $confixx_domain, $stdIP) , "j"))){
      $confixx_IP = &SelectQuestion( &ltext('install_question_confixxip', $confixx_domain) , @ips);
    }
    else{
      $confixx_IP = $stdIP;
    }
    $confixx_user = &UGQuestion( &ltext('install_question_confixxuser') , $default_confixxUser);
    $confixx_group = &UGQuestion( &ltext('install_question_confixxgroup', $confixx_user) , $default_confixxGroup);
    $confixx_homeDir = &PathQuestion( &ltext('install_question_confixxhome', $confixx_user) , "$user_homeDir/$confixx_user");
    $confixx_htmlDir = "$confixx_homeDir/html";
    $confixx_droot = $confixx_htmlDir;
    $confixx_cgiDir = "$confixx_htmlDir/cgi-bin";
    $confixx_accessLog = "$apacheDefaultLog/$confixx_domain\_access.log";
    $confixx_errorLog = "$apacheDefaultLog/$confixx_domain\_error.log";
    $confixx_admin_user = &Question( &ltext('install_question_adminuser'), $default_confixxAdminUser);
    $confixx_admin_pw = &PassQuestion( &ltext('install_question_adminpass', $confixx_admin_user) , $default_Pw);
    my $salt = join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64];
    $confixx_admin_pw_crypt = crypt($confixx_admin_pw, $salt);
  }
  ## /Confixx Webseiten

## scponly
  unless ( $EXTERNAL ) {

    $use_scponly = &YesNoQuestion( &ltext('install_question_scponly') );
    if ($use_scponly){
      ($scponly_shell,$scponly_chroot) = &scponlyConfigure(\%bin,$confixx_homeDir,$user_prefix,
							   $confixx_user,'empty');
    }

  }
## /scponly

  ## Email
  if(&YesNoQuestion( &ltext('install_question_mailmaster'),  "j" )){
    if($EXTERNAL){
      $mail_server = 2;
    }else{
      $mail_server = 1;
    }
    $use_autorespond = 1;	

    $mta = &SelectQuestion( &ltext('install_question_mta') , @mtas);
	
    unless( &checkMTAConfig( $mta ) ) {
      print "\n",&ltext('install_mta_problem'),"\n\n";
      if(&YesNoQuestion( &ltext('install_break'),  "j" )){
				exit 1;
      }
    }
		

		safe_do "$wDir/subs/mta_config.pl";

		&configureMta( $mta, 'force' );

    $popGroup = &UGQuestion( &ltext('install_question_popgroup') , $default_popGroup);

		$mail_pop3Server = 'localhost';
		$use_webmail = 1;

  } elsif ( !$EXTERNAL ) {
		$use_webmail = 0;
    $mail_server = 0;
    $mail_pop3Server = &Question( &ltext('install_question_pop3server') , 'localhost');
  }
  ## /Email


  ## Majordomo
  if ($mail_server==1 || $mail_server==2){
    if ( &YesNoQuestion( &ltext( 'install_question_majordomo') ) ) {
			safe_do "$wDir/subs/majordomo_install.pl";

			&configureMajordomo();

		} else {
	    $majordomo_wrapper='';
	    $majordomo_home='';
		}	
  }
  ## /Majordomo

  ## FTP
  unless($EXTERNAL){
    $ftpDaemon = &SelectQuestion( &ltext('install_question_ftpdaemon') , @ftpDaemons);

    if ($ftpDaemon eq 'ProFTPD'){
      safe_do "$wDir/subs/subs_include_proFTPD.pl";
      &configureFtpd($ftpConfFile);

    } elsif ( $ftpDaemon eq 'vsftpd' ) {
      safe_do "$wDir/subs/subs_include_vsftpd.pl";
      &configureFtpd($ftpConfFile);

    } elsif ( $ftpDaemon eq 'wu-ftpd') {
      safe_do "$wDir/subs/subs_include_wu-ftpd.pl";
      &configureFtpd($ftpConfFile);

    }
    unless(-e "$default_ftpLogFile"){
      open(TOUCH, ">>$default_ftpLogFile");
      close(TOUCH);
      chmod(0600, "$default_ftpLogFile");
    }
    $ftpLogFile = &FileQuestion( &ltext('install_question_ftplog') , $default_ftpLogFile);
  }
	$use_webftp = 1;
  ## /FTP


  ## Quota
  if ( &YesNoQuestion( &ltext('install_question_quota') )){
		safe_do "$wDir/subs/subs_include_quota.pl";
  
    $use_quota = 1;
    $user_quota = 1;
    $mail_quota = 1;
    if ($majordomo_ldir){
      $majordomo_quota = 1;
    }else{
      $majordomo_quota ='0';
    }

    &quotaSupportCheck('configure');

    $bin_quota = $bin{'quota'};
    $bin_quotaon = $bin{'quotaon'};
    $bin_quotaoff = $bin{'quotaoff'};
    $bin_quotacheck = $bin{'quotacheck'};
    $bin_setquota = $bin{'setquota'};

  }
  ## /Quota


  ## ColdFusion
  unless($EXTERNAL){
		if (&YesNoQuestion(&ltext('install_question_coldfusion_support'))) {
			$coldfusion_support = 1;
		} else {
			$coldfusion_support = 0;
		}
  }
  ## /ColdFusion


  ## ModPython
  unless( $EXTERNAL ) {
		if (&YesNoQuestion(&ltext('install_question_modpython_support'))) {
			$modpython_support = 1;
		} else {
			$modpython_support = 0;
		}
  }
  ## /ModPython


  ## SpamAssassin
  if ( $mail_server == 1 || $mail_server == 2){
    if (&YesNoQuestion( &ltext( 'install_question_spamassassin_support' ) ) ) {
			$spamassassin_support = 1;

			safe_do "$wDir/subs/spamassassin_install.pl";
			&configureSpamassassin();

    } else {
			$spamassassin_support = 0;
    }
  }
  else{
    $spamassassin_support = 0;
  }
  ## /SpamAssassin

  ## CronJobs
  unless($EXTERNAL){
		if ( &YesNoQuestion( &ltext( 'install_question_cronjobs_support' ) ) ) {
			$cronjobs_support = 1;
		} else {
			$cronjobs_support = 0;
		}
  }
  ## /CronJobs


  if ( $EXTERNAL && ($mail_server != 2) && ($dns_server == 0 ) ) {
    print "Nothing selected\n";
    exit 0;
  }

#
# user's mysql
#

	unless ( $EXTERNAL ) {
		if(&YesNoQuestion( &ltext('install_question_mysqlusers') )){
			if($dbType ne 'mysql'){

				&checkAndInstallPkgs( 'DBD::mysql' );

				my($ret,$errmsg) = &loadModule('DBD::mysql');
				unless( $ret ) {
					die( $errmsg."\n".
							 &ltext('install_question_module_load', 'DBD::mysql') );
				}
				system("clear");
				print "\n";
			}

			$mysqlUserServer = &ServerQuestion( &ltext('install_question_mysqluserserver') , $dbServer);
			if ($mysqlUserServer eq $dbServer) {
				# if the host specified is the same as for 'root', than we can take already
				# entered 'root' credentials
				$mysqlUserUser = $dbRootUser;
				$mysqlUserPw = $dbRootPw;	
				$mysqlUserPort = $dbPort;
				$mysqlUserHost = $dbMysqlHost;
				$mysqlUserVersion = $dbMysqlVersion;

			} else {
				# request for 'root' credentials on another box

				($mysqlUserServer,$mysqlUserUser,$mysqlUserPw,$mysqlUserPort) = &configRootDbAccess($mysqlUserServer);
				my ($ptrHash, $errstr);
				($ptrHash, $errstr) = &getMysqlInfo( { 'user'=>$mysqlUserUser,
																							 'server'=>$mysqlUserServer,
																							 'password'=>$mysqlUserPw,
																							 'port'=>$mysqlUserPort
																						 } );
				if ( $ptrHash ) {
					( undef, $mysqlUserHost ) = split( /@/, $ptrHash->{'current user'});
					$mysqlUserVersion = $ptrHash->{'server version'};
				} else {
					print STDERR "Error: unable to connect to database: $errstr\n";
				}
				unless ( $mysqlUserHost ) {
					if ( $mysqlUserServer eq 'localhost' ) {
						$mysqlUserHost = 'localhost';
					} else {
						$mysqlUserHost = $hostname;
					}
				}
			}

			if ($mysqlUserServer eq 'localhost') {
				$mysql_shell_user_host = $hostname;
				my $ptrHash = &parseMyCnf( '/etc/my.cnf', 'datadir' );
				if ( $ptrHash && $ptrHash->{'datadir'} ) {
					$default_mysql_homeDir = $ptrHash->{'datadir'};
				}
				$mysql_homeDir = &DirQuestion( &ltext('install_question_mysqlhomedir') , $default_mysql_homeDir);
			}	else {
				$mysql_shell_user_host = $mysqlUserServer;
				$mysql_homeDir = '';
			}

			
			$use_mysqlshell = 0;
			$mysql_shell_uid = '';
			$mysql_shell_user_pw_crypt = '';

			if(&YesNoQuestion( &ltext('install_question_phpmyadmin') )){
				$phpmyadminpfad = '../../phpMyAdmin/';
				$use_phpmyadmin = 1;

			} else {
				$use_phpmyadmin = 0;
			}

			$use_mysql = 1;

		}	else {
			$use_mysql = 0;

			$mysqlUserServer = '';
			$mysqlUserUser = '';
			$mysqlUserPw = '';
			$mysqlUserPort = '';
			$mysqlUserHost = '';
			$mysqlUserVersion = '';

			$mysql_shell_user_host = '';
			$mysql_shell_user = '';
			$mysql_shell_user_pw = '';
		}
	}
#
# /user's mysql
#


  ## default users
  $install_default_users = 1;	# by default
  if($EXTERNAL){
    $install_default_users = 0;	# by default
  }
  ## /default users
}



sub Welcome{
  system("clear");
  print &ltext('install_configure_pre', $configFile);
}


sub Goodbye{
  system("clear");
  print &ltext('install_configure_post', $configFile, $0, "$wDir/install.pl");
}

sub GetMinUID{
  my $uid = 0;
  open(FILE, $passwdDir);
  while (<FILE>){
    if ($_ =~ /^\S+:\S:(\d+)/){
      if (($1 > $uid) && (($1 - $uid) <= 10000)){
        $uid = $1;
      }
    }
  }
  close (FILE);
  if($uid < 500){
    $uid = 500;
  }
  return($uid);
}


sub GetMaxUID{
  my $uid = 65000;
  open(FILE, $passwdDir);
  while (<FILE>){
    if ($_ =~ /^\S+:\S:(\d+)/){
      if (($1 < $uid) && ($1 > $min_uid)){
        $uid = $1;
      }
    }
  }
  close (FILE);
  return($uid);
}


sub FindUID{
  my ($min, $max) = @_;
  my $uid = 0;
  open(FILE, $passwdDir);
  while (<FILE>){
    if ($_ =~ /^\S+:\S:(\d+)/){
      if (($1 < $max) && ($1 > $min)){
        $uid = 1;
      }
    }
  }
  close (FILE);
  return($uid);
}


sub GetLocalIPs{
  my (@ausgabe, $line, @ips);
  $bin{'ifconfig'} = "/sbin/ifconfig";
  @ausgabe = `$bin{'ifconfig'}`;
  my $i = 0;
  if ($OSTYPE eq 'Linux') {
    foreach $line (@ausgabe){
      if ($line =~ /addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ && $line !~ /127.0.0.1/){
        $ips[$i++] = $1;
      }
    }
  }
  elsif ($OSTYPE eq 'FreeBSD') {
    foreach $line (@ausgabe){
      if ($line =~ /inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ && $line !~ /127.0.0.1/){
        $ips[$i++] = $1;
      }
    }
  }
  return(@ips); # alle Lokalen IP-Adressen, ausser 127.0.0.1
}


sub confirmLicence {
  my $lizenz;
  print &ltext('install_question_licence');
  $lizenz = <STDIN>;
  chop($lizenz);
  $lizenz =~ tr/A-Z/a-z/;
  unless($lizenz eq &ltext('install_question_licence_agree')){
    die( &ltext('install_question_licence_disagree', &ltext('install_question_licence_agree')) );
  }
  print "\n\n";
}

sub checkRequirement {

	my $type = @_? shift: $dbType;

	unless ( $type ) {
		$type = &SelectQuestion( &ltext('install_question_selectdb') , 'MySQL', 'PostgreSQL');
		if ( $type eq 'MySQL' ) {
			$type = 'mysql';
		} else {
			$type = 'Pg';
		}
		$dbType = $type;
	}

	my @req = ( 'DBI',
							"DBD::$type",
							'XML::Parser',
							'XML::DOM' );

  &checkAndInstallFlat( @req );

	foreach my $pkg (@req) {
		unless( &loadPackage( $pkg ) ) {
			die( &ltext('install_question_module_load', $pkg));
		}
	}

}

sub header{
  my ($header) = @_;
  my ($length, $count);
  $length = length($header);
  print "\n\n$header\n",'~' x $length,"\n\n";
}


sub GetGroupFromUser{
  my ($user) = @_;
  my ($group);
  my $gid = (getpwnam($user))[3];
  if ($gid =~ /^\d+$/){
    $group = getgrgid($gid);
  }
  else{
    $group = "";
  }
  return($group);
}


sub writeTmpFile{
  if(-e $configFile){
    print "Loesche alte \"$configFile\"\n";
    unlink($configFile);
  }
  my $time = localtime();
  print &ltext('install_do_file_create', $configFile);
  open (FILE, ">$configFile")
	or die ("Can not open file '$configFile' for writing: $!\n");

  print FILE << "CONFIG";
#### CONFIXX TMP-CONF  ####
#### created $time ###

# allgemein
\$OSTYPE = '$OSTYPE';
\$version = '$version';
\$language = '$language';
\$langfileversion = '$langfileversion';  
\$user_homeDir = '$user_homeDir';
\$installDir = '$installDir';
\$stdShell = '$stdShell';
\$userGroup = '$userGroup';
\$popGroup = '$popGroup';
\$passwdDir = '$passwdDir';
\$shadowDir = '$shadowDir';
\$min_uid = '$min_uid';
\$max_uid = '$max_uid';
\$hostname = '$hostname';
\$PIDDir = '$PIDDir';
\$user_prefix = '$user_prefix';
\$lokaleips = '$lokaleips';
\$stdIP = '$stdIP';
\$inode_std = '0';
\$groupDir = '$groupDir';
\$pm_apache_name = '$pm_apache_name';
\$pm_apache_user = '$pm_apache_user';

# apache
\$apacheBackupSize = '$apacheBackupSize';
\$vhost_conf = '$vhost_conf';
\$mhost_conf = '$mhost_conf';
\$apacheLogDir = '$apacheLogDir';
\$apacheBackupDir = '$apacheBackupDir';
\$confixx_homeDir = '$confixx_homeDir';
\$confixx_htmlDir = '$confixx_htmlDir';
\$confixx_cgiDir = '$confixx_cgiDir';
\$httpd_conf = '$httpd_conf';
\$apacheGroup = '$apacheGroup';
\$apacheUser = '$apacheUser';
\$confixx_admin_user = '$confixx_admin_user';
\$confixx_admin_pw_crypt = '$confixx_admin_pw_crypt';
\$confixx_user = '$confixx_user';
\$confixx_group = '$confixx_group';
\$use_SSL = '$use_SSL';
\$sslKeyDir = '$sslKeyDir';
\$sslCrtDir = '$sslCrtDir';
\$apacheLogDir = '$apacheLogDir';
\$confixx_IP = '$confixx_IP';
\$confixx_domain = '$confixx_domain';
\$confixx_accessLog = '$confixx_accessLog';
\$confixx_errorLog = '$confixx_errorLog';
\$stdDomain = '$stdDomain';
\$fpfake = '$fpfake';
\$fp_homeDir = '$fp_homeDir';
\$fp_uid = '$fp_uid';
\$fp_gid = '$fp_gid';
\$httpd = '$httpd';
\$pm_apache_start = '$pm_apache_start';
\$pm_apache_reload = '$pm_apache_reload'; 
\$use_webmail = '$use_webmail';
\$use_webftp = '$use_webftp';

#scponly
\$scponly_shell = '$scponly_shell';
\$scponly_chroot = '$scponly_chroot';

# email
\$mail_server = '$mail_server';
\$mta = '$mta';
\$mailSpool = '$mailSpool';
\$maildrop = '$maildrop';
\$mailBoxName = '$mailBoxName';
\$bin_makemap = '$bin{'makemap'}';
\$bin_postmap = '$bin{'postmap'}';
\$bin_postfix = '$bin{'postfix'}';
\$pop_homeDir = '$pop_homeDir';
\$use_autorespond = '$use_autorespond';
\$MailConfigFile = '$MailConfigFile';
\$aliases = '$aliases';
\$virtUserTableDB = '$virtUserTableDB';
\$virtUserTableFile = '$virtUserTableFile';
\$localDomainsFile = '$localDomainsFile';
\$mta_uid = '$mta_uid';
\$mta_gid = '$mta_gid';

\$spamassassin_support = '$spamassassin_support';
\$pm_spamassassin_reload = '$pm_spamassassin_reload';
\$pm_spamassassin_start = '$pm_spamassassin_start';

\$coldfusion_support = '$coldfusion_support';
\$modpython_support = '$modpython_support';
\$cronjobs_support = '$cronjobs_support';

# maillist manager
\$majordomo_home = '$majordomo_home';
\$majordomo_wrapper = '$majordomo_wrapper';
\$majordomo_ldir = '$majordomo_ldir';
\$majordomo_user = '$majordomo_user';
\$majordomo_config = '$majordomo_config';


# IDN support
\$idn_shell =  '$idn_shell';
\$idn_vendor = '$idn_vendor';
\$iconv_shell = '$iconv_shell';
\$iconv_utf8 = '$iconv_utf8';

# bins
\$bin_tar = '$bin{'tar'}';
\$bin_gzip = '$bin{'gzip'}';
\$bin_find = '$bin{'find'}';
\$bin_unzip = '$bin{'unzip'}';
\$bin_cp = '$bin{'cp'}';
\$bin_grep = '$bin{'grep'}';
\$bin_chown = '$bin{'chown'}';
\$bin_chmod = '$bin{'chmod'}';
\$bin_rm = '$bin{'rm'}';
\$bin_du = '$bin{'du'}';
\$bin_mysql = '$bin{'mysql'}';
\$bin_mysqldump = '$bin{'mysqldump'}';
\$bin_psql = '$bin{'psql'}';
\$bin_ifconfig = '$bin{'ifconfig'}';
\$bin_webalizer = '$bin{'webalizer'}';
\$bin_fpsrvadm = '$bin{'fpsrvadm'}';
\$bin_openssl = '$bin{'openssl'}';
\$bin_sendmail = '$bin{'sendmail'}';
\$bin_iconv = '$bin{'iconv'}';
\$bin_idn = '$bin{'idn'}';
\$bin_iconv = '$bin{'iconv'}';
\$bin_su = '$bin{'su'}';
\$bin_ldd= '$bin{'ldd'}';
\$bin_df= '$bin{'df'}';


# quota
\$use_quota = '$use_quota';
\$user_quota = '$user_quota';
\$mail_quota = '$mail_quota';
\$majordomo_quota = '$majordomo_quota';
\$bin_quota='$bin{'quota'}';
\$bin_quotaon='$bin{'quotaon'}';
\$bin_quotaoff='$bin{'quotaoff'}';
\$bin_quotacheck='$bin{'quotacheck'}';
\$bin_setquota='$bin{'setquota'}';

# ftp
\$ftpDaemon = '$ftpDaemon';
\$ftpConfFile = '$ftpConfFile';
\$ftpLogFile = '$ftpLogFile';
\$ftpdType = '$ftpdType';
\$ftpConfAdmin = '$ftpConfAdmin';
\$pm_ftpd_reload = '$pm_ftpd_reload';
\$pm_ftpd_start = '$pm_ftpd_start';
\$pm_ftpd_noscript = '$pm_ftpd_noscript';
\$ftp_bin_ls = '$ftp_bin_ls';

# dbs
\$use_mysql = '$use_mysql';
\$dbType = '$dbType';
\$dbServer = '$dbServer';
\$dbPort = '$dbPort';
\$dbRootUser = '$dbRootUser';
\$dbRootPw = '$dbRootPw';
\$dbUser = '$dbUser';
\$dbPw = '$dbPw';
\$dbDB = '$dbDB';
\$dbMysqlHost = '$dbMysqlHost';
\$dbMysqlVersion = '$dbMysqlVersion';
\$db_address = '$db_address';

\$mysqlUserServer = '$mysqlUserServer';
\$mysqlUserUser = '$mysqlUserUser';
\$mysqlUserPw = '$mysqlUserPw';
\$mysqlUserPort = '$mysqlUserPort';
\$mysqlUserHost = '$mysqlUserHost';
\$mysqlUserVersion = '$mysqlUserVersion';

\$use_mysqlshell = '$use_mysqlshell';
\$mysql_shell_uid = '$mysql_shell_uid';
\$mysql_shell_user_host = '$mysql_shell_user_host';
\$mysql_shell_user = '$mysql_shell_user';
\$mysql_shell_user_pw = '$mysql_shell_user_pw';
\$mysql_shell_user_pw_crypt = '$mysql_shell_user_pw_crypt';
\$mysql_homeDir = '$mysql_homeDir';
\$use_phpmyadmin = '$use_phpmyadmin';
\$phpmyadminpfad = '$phpmyadminpfad';

# cgis
\$confixx_droot = '$confixx_droot';
\$mail_pop3Server = '$mail_pop3Server';

# dns - dnr
\$dns_server = '$dns_server';
\$dns_serverid  = '$dns_serverid';
\$use_dns = '$use_dns';
\$ip_pns = '$ip_pns';
\$ip_sns = '$ip_sns';
\$use_dnr = '$use_dnr';
\$dns_conf = '$dns_conf';
\$dns_configure = '$dns_configure';
\$dns_dir = '$dns_dir';
\$pm_bind_user = '$pm_bind_user';
\$pm_bind_reload = '$pm_bind_reload';
\$pm_bind_start  = '$pm_bind_start';
\$dns_chroot = '$dns_chroot';
\$dns_copyconf = '$dns_copyconf';

# spamassassin
\$spamassassinConfig = '$spamassassinConfig';
\$spamassassinScript = '$spamassassinScript';
\$spamassassinUid = '$spamassassinUid';

# default users
\$install_default_users = '$install_default_users';

\$confixx_conf_ende = '77';

# updates

\$new_version_url = 'http://updates.confixx.de/';
     ### ENDE ####
CONFIG
close (FILE) 
or die ("Can not close file '$configFile': $!\n");
  chmod(0600, "$configFile");
}


sub ltext {
  my $text_name = shift;
  if (!%lang_text) {
    my $langFile = "$wDir/languages/$language/scripts.local";
    do $langFile;
  }
  if (!defined($lang_text{$text_name})) {
    return "Sorry, text $text_name not found!";
  }
  else {
    my @VAR = @_;
    my $text = $lang_text{$text_name};
    $text =~ s/\$VAR\[(\d+)\]/$VAR[$1]/g;
    if ($text) {
      return $text;
    }
    else {
      return "Sorry, localizing text $text_name failed!";
    }
  }
}


sub choose_language{

  print "\n\n";

  do "$wDir/languages/$language/scripts.local";

  my ($lang, %lang, @lang, $i);

  opendir(DIR, "$wDir/languages");
  while(defined($lang = readdir(DIR))){
    if(($lang =~ /^\w+$/) && (-T "$wDir/languages/$lang/misc.local")){
      do "$wDir/languages/$lang/misc.local";
      $lang{$lang_text{'language_name_nat'}} = $lang if ( $langfileversion eq $lang_version );
      undef ($lang_version);
    }
  }
  closedir(DIR);

  $i = 0;
  foreach $lang (keys %lang){
    $lang[$i++] = $lang;
  }

  $lang = &SelectQuestion( &ltext('install_question_language') , @lang);
  $language = $lang{$lang};

  do "$wDir/languages/$language/scripts.local";

  print "\n\n";

}


sub check_external_db{

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

  my $dbh = DBI->connect($db_address, $dbUser, $dbPw) or return 2;

  if($dns_server == 2){
    $dbh->do("SELECT domain,zonefile,lastchange,neu,anbieter FROM dns") or return 3;
    $dbh->do("SELECT dns FROM allgemein") or return 4;
    $dbh->do("SELECT pns FROM anbieter") or return 5;
  }
  if($mail_server == 2){
    $dbh->do("SELECT ident FROM autoresponder") or return 6;
    $dbh->do("SELECT account,longpw,uid,gesperrt FROM pop3") or return 7;
    $dbh->do("SELECT addpop,delpop FROM allgemein") or return 8;
    $dbh->do("SELECT prefix,domain,pop3,ident,pop3x FROM email") or return 9;
  }

  $sth = $dbh->prepare("SELECT minuid, maxuid, userprefix FROM admin");
  $sth->execute or return 10;
  ($min_uid, $max_uid, $user_prefix) = $sth->fetchrow_array or return 11;

  $dbh->disconnect or return 12;

  return 1;
}


sub check_external{
  my $external;

  $external = &SelectQuestion( &ltext('install_question_installtype') , &ltext('install_question_installbase'), &ltext('install_question_installext'));

  if($external eq &ltext('install_question_installbase')){
    $EXTERNAL = 0;
  }
  else{
    $EXTERNAL = 1;
  } 

  return $EXTERNAL;

}

sub createRandPw {

  my $pw = join '', (0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64, rand 64, rand 64, rand 64, rand 64, rand 64, rand 64];

  return $pw;
}


## /UNTERPROGRAMME
