#!/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";
  use lib "$FindBin::Bin/../scripts";
}

use lib_module_common;
use lib_module_db;

## Pre-Main
use File::Basename;
use File::Copy;
use File::Path;
use File::Find;

use strict;

use vars qw/$wDir/;

my ($baseDir);

if ( $wDir ) {
	if ( $confixxState=~/conf|install/ ) {
		$baseDir = $wDir.'/subs';
	} else {
		$baseDir = $wDir.'/../subs';
	}
} else {
	$baseDir = $wDir = dirname($0);
}

unless ( $baseDir =~ /\/subs$/ ){
	my $path;
	foreach my $dir ('/subs','../subs'){
		$path = $baseDir.$dir;
		if ( -d $path ) {
			$baseDir = $path;
			last;
		}
	}
}

safe_do "$baseDir/subs_include_questions.pl";
safe_do "$baseDir/subs_include_writeConfig.pl";
safe_do "$baseDir/subs_include_files.pl";
safe_do "$baseDir/subs_include_webInstall.pl";

$baseDir =~ s/\/[^\/]+$//;

my $htmlDir = "$baseDir/html";
my $scriptDir = "$baseDir/scripts";
my $langDir = "$baseDir/languages";


&initConfig;

&ReadMainConfigFile;

&header2( &ltext('install_header_web') );
## Pre-Main

$bin_cp ||= $bin{'cp'} || 'cp';
$bin_chown ||= $bin{'chown'} || 'chown';
$bin_chmod ||= $bin{'chmod'} || 'chown';
$bin_find ||= $bin{'find'} || 'find';

## Main
&installWebPages;
&installScripts;
&WriteMainConfigFile;
&WritePHPConfigFile;
## /Main


## UNTERPROGRAMME

sub installWebPages{
  my (@dirs, $safeDir);
  if($confixx_htmlDir =~ /^\/\S+\/\S*/){
    
    if(-d "$confixx_htmlDir/reg"){
      print &ltext('install_do_dir_del_rec', "$confixx_htmlDir/reg");
      rmtree("$confixx_htmlDir/reg");
    }
    if(-d "$confixx_htmlDir/anbieter"){
      print &ltext('install_do_dir_del_rec', "$confixx_htmlDir/anbieter");
      rmtree("$confixx_htmlDir/anbieter");
    }
    if(-d "$confixx_htmlDir/kunde"){
      print &ltext('install_do_dir_del_rec', "$confixx_htmlDir/kunde");
      rmtree("$confixx_htmlDir/kunde");
    }
    if(-d "$confixx_htmlDir/admin"){
      print &ltext('install_do_dir_del_rec', "$confixx_htmlDir/admin");
      rmtree("$confixx_htmlDir/admin/business_inc");
      system("rm $confixx_htmlDir/admin/*.php");
    }
    if(-d "$confixx_htmlDir/user"){
      print &ltext('install_do_dir_del_rec', "$confixx_htmlDir/user");
      rmtree("$confixx_htmlDir/user/ftplogin");
      rmtree("$confixx_htmlDir/user/poplogin");
      rmtree("$confixx_htmlDir/user/cron_inc");
      system("rm $confixx_htmlDir/user/*.php");
    }
    if(-d "$confixx_htmlDir/reseller"){
      print &ltext('install_do_dir_del_rec', "$confixx_htmlDir/reseller");
      system("rm $confixx_htmlDir/reseller/*.php");
    }
	
	if(-d "$confixx_htmlDir/include"){
      print &ltext('install_do_dir_del_rec', "$confixx_htmlDir/include");
      rmtree("$confixx_htmlDir/include");
	}
	if(-d "$confixx_htmlDir/poplogin"){
      print &ltext('install_do_dir_del_rec', "$confixx_htmlDir/poplogin");
      rmtree("$confixx_htmlDir/poplogin");
	}
	if(-d "$confixx_htmlDir/ftplogin"){
      print &ltext('install_do_dir_del_rec', "$confixx_htmlDir/ftplogin");
      rmtree("$confixx_htmlDir/ftplogin");
	}
  }
  unless(-d $confixx_htmlDir){
    print &ltext('install_do_dir_create', "$confixx_htmlDir");
    &RecCreateDir($confixx_htmlDir, 0755);
  }
  unless(-d "$confixx_htmlDir/webalizer"){
    print &ltext('install_do_dir_create', "$confixx_htmlDir/webalizer");
    mkdir("$confixx_htmlDir/webalizer", 0755); # für die Statistiken der Kunden
  }
  unless(-d "$confixx_htmlDir/skins") {
    print &ltext('install_do_dir_create', "$confixx_htmlDir/skins");
    mkdir("$confixx_htmlDir/skins", 0775);
  }
	chmod (0775,"$confixx_htmlDir/skins"); ## allow group rights to write for apache

  print "\n";

  &rescueIMG("$confixx_htmlDir/back.gif", '1');
  &rescueIMG("$confixx_htmlDir/file.gif", '1');
  &rescueIMG("$confixx_htmlDir/folder.gif", '1');
  &rescueIMG("$confixx_htmlDir/ftptransf.gif", '1');
  &rescueIMG("$confixx_htmlDir/webtransf.gif", '1');
  &rescueIMG("$confixx_htmlDir/logo.gif", '1');
  &rescueIMG("$confixx_htmlDir/logogross.gif", '1');
  &rescueIMG("$confixx_htmlDir/style.css", '1');
  print "\n";

  print &ltext('install_webpages_copy', $confixx_htmlDir);
  system( "$bin_cp -rf $htmlDir/* $confixx_htmlDir/" );
  system( "$bin_cp -rf $htmlDir/admin/skins/* $confixx_htmlDir/skins" );
  print "\n";

  print &ltext('install_languages_copy', $confixx_htmlDir);
  system( "$bin_cp -rfv $langDir $confixx_htmlDir/");
  print "\n";

  unless(-d "$confixx_htmlDir/include/template/templates_c"){
		mkdir("$confixx_htmlDir/include/template/templates_c", 0777);
  }

  &rescueIMG("$confixx_htmlDir/back.gif");
  &rescueIMG("$confixx_htmlDir/file.gif");
  &rescueIMG("$confixx_htmlDir/folder.gif");
  &rescueIMG("$confixx_htmlDir/ftptransf.gif");
  &rescueIMG("$confixx_htmlDir/webtransf.gif");
  &rescueIMG("$confixx_htmlDir/logo.gif");
  &rescueIMG("$confixx_htmlDir/logogross.gif");
  &rescueIMG("$confixx_htmlDir/style.css");
  print "\n";

  
  print &ltext('install_webpages_perms', $confixx_htmlDir);

	find ( sub {
					 my ($mode);
					 unless ( -l $File::Find::name ) {

						 if ( -d $File::Find::name ) {
							 $mode = 0755;

						 } elsif ( -f $File::Find::name ) {
							 $mode = /\.cgi$/? 0755: 0644;
						 }

						 if ( $mode ){
							 chmod ( $mode, $File::Find::name );
							 chown ( $confixx_uid, $confixx_gid, $File::Find::name );
						 }
					 }
				 },
				 $confixx_htmlDir );
#
# extra case
#
	chmod ( 0777, "$confixx_htmlDir/include/template/templates_c" );

	chmod ( 0775, "$confixx_htmlDir/skins" );
	chown ( $confixx_uid, $gidapache, "$confixx_htmlDir/skins" );

	print "\n";
}


sub rescueIMG{
  my ($img, $backup) = @_;
  if(($backup) && (-e "$img")){
    print &ltext('install_do_file_copy', $img, "$img.old");
    copy("$img", "$img.old");
  }
  elsif(-e "$img.old"){
    print &ltext('install_do_file_mv', "$img.old", $img);
    copy("$img.old", "$img");
    unlink("$img.old");
  }
}


sub installScripts {
  my (@Script, $i);
  unless ( $confixx_binDir ) {
    $confixx_binDir = dirname($confixx_htmlDir) . "/bin";
  }
  unless(-d $confixx_binDir ) {
    print &ltext('install_do_dir_create', $confixx_binDir );
    mkdir( $confixx_binDir, 0755);
  }
  unless( $confixx_sbinDir ) {
    $confixx_sbinDir = dirname($confixx_htmlDir) . "/sbin";
  }
  unless(-d $confixx_sbinDir ) {
    print &ltext('install_do_dir_create', $confixx_sbinDir );
    mkdir( $confixx_sbinDir, 0750);
  }
  chown( $confixx_uid, $confixx_gid, $confixx_binDir );
  chown( $confixx_uid, $gidapache, "$confixx_sbinDir"  ) or 
		warn("Can not chown $confixx_sbinDir: $!\n");

  unless( $confixx_tmpDir ) {
    $confixx_tmpDir = dirname($confixx_htmlDir) . "/tmp";
  }
  unless(-d $confixx_tmpDir ) {
    print &ltext('install_do_dir_create', $confixx_tmpDir );
    mkdir( $confixx_tmpDir, 0777);
  }
  chown($confixx_uid, $confixx_gid, $confixx_tmpDir);
  chmod(0777, $confixx_tmpDir);

  print &ltext('install_do_file_create', "$confixx_binDir/lsdir.pl");
  open (FILE, "$scriptDir/lsdir.pl");

  @Script=();
  while (<FILE>){
    $_ =~ s/^\$root =.*$/\$root = \'$user_homeDir\';/;
    push @Script, $_;
  }
  close(FILE);
  open(FILE, ">$confixx_binDir/lsdir.pl");
  print FILE @Script;
  close(FILE);
  chmod(0755, "$confixx_binDir/lsdir.pl");
  chown($confixx_uid, $confixx_gid, "$confixx_binDir/lsdir.pl");


  if(-e "$scriptDir/sslgen.pl"){
    print &ltext('install_do_file_create', "$confixx_binDir/sslgen.pl");
    open (FILE, "$scriptDir/sslgen.pl");
    @Script = ();
    while (<FILE>){
	  	chomp;
	  	unless ( /^\s*(#|$)/ ){    ## skip blank & comment
	  		$_ =~ s/(?:^|\s|;)\$db_address\s*=.+/\$db_address = \'$db_address\';/;
    		$_ =~ s/(?:^|\s|;)\$dbUser\s*=.+/\$dbUser = \'$dbUser\';/;
    		$_ =~ s/(?:^|\s|;)\$dbPw\s*=.+/\$dbPw = \'$dbPw\';/;
    		$_ =~ s/(?:^|\s|;)\$bin_openssl\s*=.+/\$bin_openssl = \'$bin_openssl\';/;
    		$_ =~ s/(?:^|\s|;)\$tmpdir\s*=.+/\$tmpdir = \'$confixx_tmpDir\';/;
	  	}
    	push @Script,$_;
    }
    close(FILE);

#
# save result
#    
		open(FILE, ">$confixx_binDir/sslgen.pl");
    map { print FILE $_,"\n" } @Script;
    close(FILE);
	
    chmod(0755, "$confixx_binDir/sslgen.pl");
    chown($confixx_uid, $confixx_gid, "$confixx_binDir/sslgen.pl");
  }

  if(-e "$scriptDir/perldebug.pl"){
    print &ltext('install_do_file_create', "$confixx_binDir/perldebug.pl");
    open (FILE, "$scriptDir/perldebug.pl");
    $i = 0;
    undef @Script;
    while (<FILE>){
      $_ =~ s/^\$base =.*$/\$base = \'$user_homeDir\';/;
      $Script[$i++] = $_;
    }
    close(FILE);
    open(FILE, ">$confixx_binDir/perldebug.pl");
    print FILE (@Script);
    close(FILE);
    chmod(0755, "$confixx_binDir/perldebug.pl");
    chown($confixx_uid, $confixx_gid, "$confixx_binDir/perldebug.pl");
  }

	# rwsr-s--x mode
	&installScript( 'skinmng.pl', $confixx_uid, $gidapache, 0750, $confixx_sbinDir, &skinmng_opt );

	# work around suidperl
#	&checkSuidPerl;

	
	my %idn_opt = ( 
								 'idn_shell'		=> $idn_shell,
								 'idn_vendor'	=> $idn_vendor,
								 'iconv_shell' => $iconv_shell,
								 'iconv_utf8'  => $iconv_utf8,					 
	);
	&installScript( 'idn_translate.pl', $confixx_uid, $confixx_gid, 0755, $confixx_binDir, %idn_opt );

	$bin_cp ||= $bin{'cp'}||'cp';
	my $srcModules = "$scriptDir/Modules";
	my $dstModules = "$confixx_sbinDir/Modules";
	if ( opendir( SRC, $srcModules ) ) {

		unless ( -d $dstModules ) { ## create dir if it is not exists
			unlink $dstModules if -e $dstModules;
			mkdir $dstModules,0750;
		}

		my %srcDirs = ( 'File' => 1 ); ## list of dirs to copy

		my ($srcPath,$dstPath,$name);

		while ( $name = readdir( SRC ) ) {
			next if $name =~ /^\.\.?$/; ## skip . & ..
			$srcPath = "$srcModules/$name";
			$dstPath = "$dstModules/$name";
			if ( -d $srcPath ){
				if ( $srcDirs{$name} ) {
					system("$bin_cp -rf \"$srcPath\" \"$dstModules\"");
				}
			} else {
				copy( $srcPath, $dstPath);
			}
		}
		closedir (SRC);

	}else{
		system("$bin_cp -rf \"$srcModules\" \"$confixx_sbinDir\"");
	}

#
# restore ownership
#
	find ( sub {
					 unless ( -l $File::Find::name ) {
						 my ($mode);
						 if ( -f $File::Find::name ) {
							 if ( /\.(pl|cgi)$/ ) {
								 $mode = 0755;
							 } else {
								 $mode = 0644;
							 }
						 } elsif ( -d $File::Find::name ) {
							 $mode = 0755;
						 }
						 if ( $mode ) {
							 chmod ( $mode, $File::Find::name );
							 chown ( $confixx_uid, $gidapache, $Find::Find::name );
						 }
					 }
				 },
				 $dstModules
			 );
}

sub checkSuidPerl {
	my $suidperl = "/usr/bin/suidperl";
	my @ver = unpack('C3',$^V);
	my $sperl = dirname($suidperl).'/sperl'.join('.',@ver);  

	my  $verN = $ver[0] + $ver[1]*0.001 + $ver[2]*0.000001;
	if ( ( $verN >= 5.006002 && $verN < 5.007 ) || $verN >= 5.008004 ) { ## new shema
	  unless ( -e $sperl) {
			# mostly for Debian: no suidperl installed
			&report_error("You do not have suidperl installed: file $sperl is not found.\n".
										" Some features like skin editing will not be available until".
										" you will enable suidperl.");
		} else {
			my $perl = '/usr/bin/perl';
			if ( -f $perl ) {
				if ( -f $suidperl ) {
					if ( ( -l $suidperl ) ||  ( (stat( $suidperl ))[1] != (stat( $perl ))[1] ) ) {
						unlink $suidperl;
					}
				}
				unless ( -f $suidperl ) {
					symlink $perl, $suidperl;
				}	
			}
	  }	
	  my $mode = ( stat( $sperl ) )[2];
	  if (($mode & 06000) == 0) {	## check suid bit
			chmod( 06755, $sperl ) or 
				&report_error("You suidperl installed, but not enabled: ".
											"file '$sperl' ass no SUID bit found.\n".
											" Some features like skin editing will not be available".
											" until you will enable suidperl.");
	  }

	} else { ## old shema
	  unless ( -e $suidperl) {
			# mostly for Debian: no suidperl installed
			&report_error("You do not have suidperl installed: file $suidperl is not found.\n".
										" Some features like skin editing will not be available until ".
										"you will enable suidperl.");
	  } else {
		#
		# get name of sperl5.8.0
		#

			unless ( ( -f $sperl ) && ## there is the file
							 ( (stat( $suidperl ))[1] == (stat( $sperl ))[1] ) ) { ## inods are not same
				if ( -f $sperl ) {
					unlink $sperl;
				}
		#
		# make hard link
		#  
				link $suidperl,$sperl or
					&report_error("Unbale to make hard link to '$suidperl' ('$sperl'): $!\n");
				chmod(04755,$sperl) or
					&report_error("Unable to chnage mode of '$sperl' (hard link of '$suidperl'): $!\n");		
				
		# mostly for SuSE: no suid bit set
				my $mode = (stat( $suidperl ))[2];
				if (($mode & 04000) == 0) {	## check suid bit
					chmod( 04755, $suidperl ) or 
						&report_error("You suidperl installed, but not enabled: ".
													"file '$suidperl' ass no SUID bit found.\n".
													" Some features like skin editing will not be available".
													" until you will enable suidperl.");
				}
			}	
	  }	
	}
#
#================================================================
#		
	if ( -f $suidperl ) {
		my $file = '/etc/permissions.local';
		if ( -T $file ) {
			if ( open (CONF, '<'.$file ) ) {
				my ($ok,$head,$pat);
				$pat = qr/^\s*\Q$suidperl\E\s+(\w+\.\w+)\s+(\d+)$/;
				while ( <CONF> ) {
					chomp;
					if ( !/^\s*(?:#|$)/ && /$pat/ ) {
						$ok = ($1 eq 'root.root' && $2 eq '4755');
					}else{
						$head .= $_;
						$head .= "\n";
					}
				}
				close CONF;
				unless($ok){
					system("cp -f $file $file.confixx_backup");
					if ( open( CONF, '>'.$file ) ) {
						print CONF $head;
						print CONF "\n$suidperl\troot.root\t4755\n";
						close(CONF);
					}else{
						&report_error("Error: can not open '$file' to write: $!\n");
					}
				}
			}else{
				&report_error("Error: can not open '$file' to read: $!\n");
			}
		}
	}
}

sub report_error($) {
	my ($str) = @_;

	warn "PROBLEM FOUND: $str\n";
	my $logfile = "$installDir/INSTALLATION_PROBLEMS.LOG";
	unless (open(FILE, ">>$logfile")) {
		warn "Warning: can not save problem description to $logfile: can not open file $logfile: $!\n";
		return;
	}
	print FILE "$str\n";
	unless (close(FILE)) {
		warn "Warning: can not save problem description to $logfile: can not close file $logfile: $!\n";
		return;
	}
}
## /UNTERPROGRAMME
