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

## Pre-Main
use File::Basename;
use DBI;

use lib_module_common;
use lib_module_db;

use strict;

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

if (-d "$wDir/subs" ){ ## install
	$wDir = "$wDir/subs";
} elsif( -d "$wDir/../subs") { ## update
	$wDir = &getCanonPath( "$wDir/../subs" );
}

my $subs_include_questions = "$wDir/subs_include_questions.pl";

unless(-f $subs_include_questions){
  $wDir =~ s/\/[^\/]+$/\/subs/; 
  $subs_include_questions = "$wDir/subs_include_questions.pl";
	unless ( -f $subs_include_questions ) {
		if ( -d $installDir ) {
			$wDir = "$installDir/admin/subs";
			$subs_include_questions = "$wDir/subs_include_questions.pl";
		}
	}
}
safe_do $subs_include_questions;
safe_do "$wDir/subs_include_writeConfig.pl";

safe_do "$wDir/MySQLLogin_install.pl";  # to run &installMySQLLogin;

&ReadMainConfigFile;

safe_do "$wDir/subs_include_files.pl";

my $subs_include_writeConfig = "$wDir/subs_include_writeConfig.pl";
my $subs_include_qmail = "$wDir/subs_include_qmail.pl";
my $subs_include_postfix = "$wDir/subs_include_postfix.pl";
my $subs_include_sendmail = "$wDir/subs_include_sendmail.pl";
my $subs_include_majo = "$wDir/subs_include_majo.pl";
my $subs_include_IDN = "$wDir/subs_include_IDN.pl";
my $subs_include_events = "$wDir/subs_include_events.pl";
my $subs_include_quota = "$wDir/subs_include_quota.pl";

my ($baseDir);
($baseDir = $wDir) =~ s/\/[^\/]+$//;

my $scriptDir = "$baseDir/scripts";
my $contribDir = "$baseDir/contrib";

&header2( &ltext('install_header_scripts') );
## /Pre-Main

## Main
unless( $PIDDir  && -d $PIDDir ) {
  print &ltext('install_do_dir_create', $PIDDir);
  mkdir($PIDDir, 0755) or 
		print( &ltext('install_dir_create', $PIDDir) );
}

$bin_cp ||= $bin{'cp'}||'cp';

&invalidShell;
&installUpdateScript;
&installModules( $baseDir );
&installFTPTraffik;
&installHTTPDTraffik;
&installWebalizer;
&installAdmin;
&installPipe;
&installInstall( $baseDir );

if(-e "$scriptDir/autoresponder.pl" && $mail_server>=1 && $mta ){
  &installAutoresponder('autoresponder.pl');
}

if(-e "$scriptDir/confixxevent.pl" && $mail_server>=1 && $mta ){
  &installAutoresponder ('confixxevent.pl',($mta eq 'qmail')?'alias':undef);  
	## alias - system account for call confixxevent.pl by qmail
}

if(-e "$scriptDir/newsletter.pl"){
  &installNewsletter();
}

&installUserManager;

&UpdateAllConfig;

if ( $mysqlUserServer  && $mysqlUserUser && $mysqlUserPw ) {
  &installMySQLLogin;
}

## /Main

#
#
#=================================================
#
#

## UNTERPROGRAMME

sub installUpdateScript{
  my (@Script);

  print &ltext('install_install_group', 'UpdateScript');

  print &ltext('install_do_file_copy', "$scriptDir/confixx_updatescript.pl", "$installDir/confixx_updatescript.pl");

  copy( "$scriptDir/confixx_updatescript.pl", "$installDir/confixx_updatescript.pl");
  chmod( 0755, "$installDir/confixx_updatescript.pl");

  copy( "$scriptDir/backup.pl", "$installDir/backup.pl");
  chmod( 0755, "$installDir/backup.pl");
  copy( "$scriptDir/restore.pl", "$installDir/restore.pl");
  chmod( 0755, "$installDir/restore.pl");
  copy( "$scriptDir/restorefull.pl", "$installDir/restorefull.pl");
  chmod( 0755, "$installDir/restorefull.pl");

  copy( "$scriptDir/confixx_dump.conf", "$installDir/confixx_dump.conf");
  chmod( 0400, "$installDir/confixx_dump.conf");

  copy( "$scriptDir/atdomain.php","$installDir/atdomain.php");
  chmod ( 0644, "$installDir/atdomain.php" );

  print &ltext('install_do_file_copy', "$scriptDir/reset_admin_pw.pl", "$installDir/reset_admin_pw.pl");
  copy( "$scriptDir/reset_admin_pw.pl", "$installDir/reset_admin_pw.pl");
  chmod( 0755, "$installDir/reset_admin_pw.pl");

  print &ltext('install_do_file_copy', "$scriptDir/copy_libraries.pl", "$installDir/copy_libraries.pl");
  copy("$scriptDir/copy_libraries.pl", "$installDir/copy_libraries.pl");
  chmod(0755, "$installDir/copy_libraries.pl");

  print &ltext('install_do_file_copy', "$subs_include_sendmail", "$installDir/subs_include_sendmail.pl");
  copy($subs_include_sendmail, "$installDir/subs_include_sendmail.pl");
  chmod(0755, "$installDir/subs_include_sendmail.pl");
  print &ltext('install_do_file_copy', "$subs_include_qmail", "$installDir/subs_include_qmail.pl");
  copy($subs_include_qmail, "$installDir/subs_include_qmail.pl");
  chmod(0755, "$installDir/subs_include_qmail.pl");
  print &ltext('install_do_file_copy', "$subs_include_postfix", "$installDir/subs_include_postfix.pl");
  copy($subs_include_postfix, "$installDir/subs_include_postfix.pl");
  chmod(0755, "$installDir/subs_include_postfix.pl");

  print &ltext('install_do_file_copy', "$subs_include_majo", "$installDir/subs_include_majo.pl");
  copy($subs_include_majo, "$installDir/subs_include_majo.pl");
  chmod(0644, "$installDir/subs_include_majo.pl");

  print &ltext('install_do_file_copy', "$subs_include_IDN", "$installDir/subs_include_IDN.pl");
  copy($subs_include_IDN, "$installDir/subs_include_IDN.pl");
  chmod(0755, "$installDir/subs_include_IDN.pl");

  print &ltext('install_do_file_copy', "$subs_include_events", "$installDir/subs_include_events.pl");
  copy($subs_include_events, "$installDir/subs_include_events.pl");
  chmod(0644, "$installDir/subs_include_events.pl");

  print &ltext('install_do_file_copy', "$subs_include_quota", "$installDir/subs_include_quota.pl");
  copy($subs_include_quota, "$installDir/subs_include_quota.pl");
  chmod(0644, "$installDir/subs_include_quota.pl");

  print &ltext('install_do_file_copy', "$subs_include_writeConfig", "$installDir/subs_include_writeConfig.pl");
  copy($subs_include_writeConfig, "$installDir/subs_include_writeConfig.pl");
  $apache_root = $httpd_conf;
  ($apache_root =~ s/\/conf\/httpd\.conf$//) || ($apache_root =~ s/\/httpd\.conf$//);
  unless(-d "$apache_root/conf"){
    print &ltext('install_do_link', "$apache_root", "$apache_root/conf");
    symlink("$apache_root", "$apache_root/conf");
  }
  system("$bin_cp -vf $scriptDir/*.so $installDir");
  if((-e "$installDir/newserver.pl") && (-e "$contribDir/newserver.pl")){
    print &ltext('install_do_file_copy', "$contribDir/newserver.pl", "$installDir/newserver.pl");
    copy("$contribDir/newserver.pl", "$installDir/newserver.pl");
    chmod(0755, "$installDir/newserver.pl");
  }
  # create symlink for compatibility issues
  symlink("$installDir/confixx_updatescript.pl", "$installDir/confixx_counterscript.pl");
}

sub installModules
{
  my $wDir = $baseDir||shift;

	print &ltext('install_do_dir_copy', "$wDir/scripts/Modules", "$installDir/Modules");
	system( "$bin_cp -rf $wDir/scripts/Modules $installDir" );

}

sub installFTPTraffik{
  my (@Script);
  print &ltext('install_install_group', 'FTPTraffik-Script');
  print &ltext('install_do_file_copy', "$scriptDir/ftptraffik.pl", "$installDir/ftptraffik.pl");
  copy("$scriptDir/ftptraffik.pl", "$installDir/ftptraffik.pl");
  chmod(0755, "$installDir/ftptraffik.pl");
}


sub installHTTPDTraffik{
  my (@Script);
  my $time = localtime();
  print &ltext('install_install_group', 'HTTPDTraffik-Script');
  print &ltext('install_do_file_create', "$installDir/httpdtraffik.sh");
  open (FILE, ">$installDir/httpdtraffik.sh");

  print FILE << "SCRIPT";
#!/bin/sh
##
### Script zur Steuerung der HTTPD-Traffik-Ermittlung
########## created: $time ###
FIND="$bin{'find'}"
RM="$bin{'rm'}"
GREP="$bin{'grep'}"
PREFIX="$user_prefix";
HOMEDIR="$user_homeDir"
BACKUPDIR="$apacheBackupDir"
LOGEXPIRE="$apacheBackupExpire"
PIDFILE="$PIDDir/confixx_httpdtraffik.pid" # PID-File
SCRIPT="$installDir/httpdtraffik.pl" # Das Script, das den Traffik ermittelt anhand des ConfigFiles (und natuerlich Logfile;-)
ROTATESCRIPT="$installDir/rotate.pl" # Das Script, das die Logfiles packt...
CONF=".configs/webalizer.conf"
WEBALIZER="$bin_webalizer"
########################
if test "\$1" =  "DEBUG"  ; then
  DEBUG=1;
 else
  DEBUG=0;
fi

echo \$\$ > \$PIDFILE;
      for HOME in \$HOMEDIR/* ; do
        USER=\${HOME##\$HOMEDIR/}
        if ( echo -E "X\$USER" | \$GREP "^X\$PREFIX[0-9]\\+\$" >/dev/null )  ; then
          if test "\$DEBUG" = "1"; then
            echo "\$USER"
          fi
          if ((test "\$USER" != "*") && (test -e "\$HOME/log/access_log") && (test "1\$USER" != "1")); then
            if test "\$DEBUG" = "1"; then
              echo "\$SCRIPT \$USER"
            fi
            \$SCRIPT \$USER
            if ((test -e \$HOMEDIR/\$USER/\$CONF) && (test -G \$HOMEDIR/\$USER/\$CONF) && (test -O \$HOMEDIR/\$USER/\$CONF) && (test -x \$WEBALIZER)) ; then
              if test "\$DEBUG" = "1"; then
                echo "\$WEBALIZER -c \$HOMEDIR/\$USER/\$CONF"
              fi
              \$WEBALIZER -c \$HOMEDIR/\$USER/\$CONF
            fi
            if test "\$DEBUG" = "1"; then
              echo "\$ROTATESCRIPT \$USER access"
            fi
           \$ROTATESCRIPT \$USER access
            if(test -d \$BACKUPDIR/\$USER) ; then
              if test "\$DEBUG" = "1"; then
              echo "\$FIND \$BACKUPDIR/\$USER/ -atime +\$LOGEXPIRE -type f -exec rm -f {} \\;"
              fi
              \$FIND \$BACKUPDIR/\$USER/ -atime +\$LOGEXPIRE -type f -exec rm -f {} \\;
            fi
            if(test -d \$HOMEDIR/\$USER/log/old) ; then
              if test "\$DEBUG" = "1"; then
                echo "\$FIND \$HOMEDIR/\$USER/log/old/ -atime +\$LOGEXPIRE -type f -exec rm -f {} \\;"
              fi
              \$FIND \$HOMEDIR/\$USER/log/old/ -atime +\$LOGEXPIRE -type f -exec rm -f {} \\;
            fi
          fi
        fi
      done
rm \$PIDFILE; # Bin fertig, also PID-File loeschen...
SCRIPT

  close(FILE);

  chmod(0755, "$installDir/httpdtraffik.sh");
  print &ltext('install_do_file_copy', "$scriptDir/httpdtraffik.pl" ,"$installDir/httpdtraffik.pl");
  copy("$scriptDir/httpdtraffik.pl", "$installDir/httpdtraffik.pl");
  chmod(0755, "$installDir/httpdtraffik.pl");

  print &ltext('install_do_file_copy', "$scriptDir/rotate.pl" ,"$installDir/rotate.pl");
  copy("$scriptDir/rotate.pl", "$installDir/rotate.pl");
  chmod(0755, "$installDir/rotate.pl");

}


sub installWebalizer{
  my $time = localtime();
  print &ltext('install_do_file_create', "$installDir/runwebalizer.sh");
  open(FILE, ">$installDir/runwebalizer.sh");

  print FILE << "SCRIPT";
###### Confixx-Webalizer-Script
## zum abarbeiten aller Domains mit Webalizer
########## erstellt am $time ###
PIDFILE="$PIDDir/confixx_webalizer.pid" # PID-File
HOMEDIR="$user_homeDir"
CONF=".configs/webalizer.conf"
WEBALIZER="$bin_webalizer"
########################
echo \$\$ > \$PIDFILE;
      for HOME in \$HOMEDIR/* ; do
        USER=\${HOME##\$HOMEDIR/}
        if test "\$USER" != "*"; then
          if test -e \$HOMEDIR/\$USER/\$CONF ; then
            \$WEBALIZER -c \$HOMEDIR/\$USER/\$CONF
          fi
        fi
      done
rm \$PIDFILE; # Bin fertig, also PID-File löschen...
SCRIPT

  close(FILE);

  chmod(0755, "$installDir/runwebalizer.sh");
}


sub installAdmin{
  print &ltext('install_install_group', 'Admin-Script');
  unless(-d "$installDir/admin"){
    print &ltext('install_do_dir_create', "$installDir/admin");
    mkdir ("$installDir/admin", 0700);
  }
  my (@Script);

  print &ltext('install_do_file_copy', "$scriptDir/admin.pl", "$installDir/admin/admin.pl");
  copy("$scriptDir/admin.pl", "$installDir/admin/admin.pl");
  chmod(0755, "$installDir/admin/admin.pl");

  if ( -T "$baseDir/.config" ) { ## install mode
    print &ltext('install_do_dir_copy', "$baseDir/subs", "$installDir/admin/subs");
    system( "$bin_cp -rf $baseDir/subs $installDir/admin/" );
    print &ltext('install_do_dir_copy', "$baseDir/CPAN", "$installDir/admin/CPAN");
    system( "$bin_cp -rf $baseDir/CPAN $installDir/admin/" );
    print &ltext('install_do_dir_copy', "$baseDir/admin", "$installDir/admin/admin");
    system( "$bin_cp -rf $baseDir/scripts $installDir/admin/" );
    print &ltext('install_do_dir_copy', "$baseDir/cgis", "$installDir/admin/cgis");
    system( "$bin_cp -rf $baseDir/cgis $installDir/admin/" );
    print &ltext('install_do_dir_copy', "$baseDir/html", "$installDir/admin/html");
    system( "$bin_cp -rf $baseDir/html $installDir/admin/" );
    print &ltext('install_do_dir_copy', "$baseDir/languages", "$installDir/admin/languages");
    system( "$bin_cp -rf $baseDir/languages $installDir/admin/" );
  }
}

sub installInstall {
  my $wDir = $baseDir||shift;
    print &ltext('install_install_group', 'Install-Script');
#    if(-T "$baseDir/.config"){
	print &ltext('install_do_dir_copy', "$wDir/install", "$installDir/install");
	system( "$bin_cp -rf $wDir/install $installDir/" );
#    }
}

sub installPipe{
  print &ltext('install_install_group', 'PipeLog-Script');
  my $time = localtime();
  print &ltext('install_do_file_create', "$installDir/pipelog.pl");
  open(FILE, ">$installDir/pipelog.pl");

  print FILE << "SCRIPT";
#!/usr/bin/perl
###### Confixx-Apache-PipeLog
## zum Loggen der Webzugriffe pro User
########## erstellt am $time ###
\$logDir = "$apacheLogDir/domains/access";
\$stdLog = "$apacheLogDir/stdlog_access";
while(<STDIN>){
  (\$domain, \$log) = split(/:#?:/, \$_, 2);
  \$domain = lc(\$domain);
  \$logfile = "\$logDir/\$domain";
  \$worked = 0;
  if(-l \$logfile){
    \$target = readlink(\$logfile);
    unless(-l \$target){ 
      if(open(LOG, ">>\$logfile")){
        print LOG \$log;
        close(LOG);
        \$worked=1;
      }
    } 
  }
  unless(\$worked){
    open(LOG, ">>\$stdLog") or next;
    print LOG "\$domain :: \$log";
    close(LOG);
  }

}
SCRIPT

  close(FILE);

  chmod(0755, "$installDir/pipelog.pl");
}


sub installAutoresponder{

  my $scriptToInstall = shift || 'autoresponder.pl';
  my $scriptOwner = shift;

  $scriptToInstall =~ /^(\S+?)\./;
  my $scriptKey = $1;
  
  my($i, @Script, $default_uid);

  if ($scriptKey =~ /autorespond/){
    $scriptKey ='autorespond';
    print &ltext('install_install_group', 'Autoresponder-Script');
  } else {
		print &ltext('install_install_group', "$scriptKey-Script");
  }	

  unless( $mta_uid =~ /^\d+$/ && $mta_gid =~ /^\d+$/ ) {
		&configureMtaUidGid();
  }

  umask 077;
  open(FILE, "$scriptDir/$scriptToInstall");
  while (<FILE>){
    $_ =~ s/^\$db_address.*/\$db_address = \'$db_address'\;/;
    $_ =~ s/^\$dbUser.*/\$dbUser = \'$dbUser'\;/;
    $_ =~ s/^\$dbPw.*/\$dbPw = \'$dbPw'\;/;
    $_ =~ s/^\$SENDMAIL.*/\$SENDMAIL = \'$bin{'sendmail'}'\;/;
    $Script[$i++] = $_;
  }
  close(FILE);
  umask 022;

	no strict 'refs';

  my $ptrVar = "bin_$scriptKey";
  my $binCmd = $$ptrVar;

  if(($scriptToInstall =~ /autorespond/) && ($bin_autorespond ne "") && ($bin_autorespond =~ /^\/\S+\.pl$/)){
    $bin{$scriptKey} = $bin_autorespond;
  }else{
    if ($binCmd =~ /^\/\S+\.pl$/){
      $bin{$scriptKey} = $binCmd;
    }else{
      $bin{$scriptKey} = "/usr/bin/$scriptToInstall";
      $$ptrVar = $bin{$scriptKey};
    }
  }

	use strict 'refs';

  print &ltext('install_do_file_create', $bin{$scriptKey});
  open(FILE, ">$bin{$scriptKey}");
  
  print FILE @Script;
  close(FILE);
  ## WICHTIG!!

  if ( $mta eq 'postfix' ) {
#
# fuer postfix soll autoresponder.pl zu nobody gehoeren
#
    my $default_privs = 'nobody';
    if ( -f $MailConfigFile){
      if (open(CONF,"< $MailConfigFile")){
				while(<CONF>){
					chomp;
					unless (/^#/){
						if (/^\s*default_privs\s*=\s*(\S+)/){
							$default_privs=$1;
							last;
						}
					}
				}
      }
      close(CONF);
    }
    my ($privs_uid,$privs_gid)=(getpwnam($default_privs))[2,3];

    unless( $privs_uid ){
#
# der schlechste Fall
#
      $privs_uid = 99;
      $privs_gid = 99;
    }

    chown($privs_uid, $privs_gid, $bin{$scriptKey});

  } elsif( $scriptOwner ) {

    my ($privs_uid,$privs_gid) = (getpwnam($scriptOwner))[2,3];

    chown($privs_uid, $privs_gid, $bin{$scriptKey});

  } else{

    chown($mta_uid, $mta_gid, $bin{$scriptKey});

  }

  chmod(0550, $bin{$scriptKey});
  ##/ WICHTIG!!
	foreach my $smrshDir ('/etc/smrsh','/etc/mail/smrsh'){
		if(-d $smrshDir){
			if(!(-e "$smrshDir/$scriptToInstall")){
				symlink($bin{$scriptKey}, "$smrshDir/$scriptToInstall");
			}
		}
	}
}


sub installNewsletter{
  my($i, @Script);
  print &ltext('install_install_group', 'Newsletter-Script');
  print &ltext('install_do_file_copy', "$scriptDir/newsletter.pl", "$installDir/newsletter.pl");
  copy("$scriptDir/newsletter.pl", "$installDir/newsletter.pl");
  chmod(0750, "$installDir/newsletter.pl");
}


sub installUserManager{
  my($i, @Script);
  print &ltext('install_install_group', 'UserManager');

  if(-e "$installDir/confixx_useradd.pl"){
    unlink("$installDir/confixx_useradd.pl");
  }
  if(-e "$installDir/confixx_userdel.pl"){
    unlink("$installDir/confixx_userdel.pl");
  }
  if(-e "$installDir/confixx_passwd.pl"){
    unlink("$installDir/confixx_passwd.pl");
  }

  print &ltext('install_do_file_copy', "$scriptDir/confixx_passwd.pl", "$installDir/confixx_passwd.pl");
  copy("$scriptDir/confixx_passwd.pl", "$installDir/confixx_passwd.pl");
  chmod(0750, "$installDir/confixx_passwd.pl");

}


#
# add Shells used by Confixx to /etc/shells 
# to prevent "invalid shell" for ftp logins
#
sub invalidShell{
  my $file = '/etc/shells';
  my $bin_false = '/bin/false';
  my $bin_scp = $scponly_shell;
  
  if ( -T $file ) {
    if ( open(FILE, $file) ) {
			while(<FILE>){
				if($_ =~ /\/bin\/false/){
					$bin_false = '';
				}
				if($_ eq "$bin_scp\n"){
					$bin_scp = '';
				}
			}
			close(FILE);
		
			if ( $bin_false || $bin_scp ) {
				if ( open(FILE, '>>', $file) ) {
					print FILE $bin_false,"\n" if $bin_false;
					print FILE $bin_scp,"\n" if $bin_scp;
					close(FILE);
				} else {
					warn "Error: unable to open '$file': $!\n";
				}
			}
    } else {
			warn "Error: unable to open '$file': $!\n";
		}
  }
}
## /UNTERPROGRAMME



