#!/usr/bin/perl 

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


use File::Copy;

use lib_module_common;
use lib_module_db;

## UNTERPROGRAMME FEUR CONFIXX INSTALLATION & KONFIGURATION
sub UpdateAllConfig{
  my ($nobin) = @_;

  print "\n";

	unless($dns_server == 2 || $mail_server == 2){
		&RestoreBin unless $nobin;
	}

  &ReadMainConfigFile;

  &WriteMainConfigFile;

  unless($dns_server == 2 || $mail_server == 2){  ## launch only on primary server
    &WritePHPConfigFile;
  }
  if($::mail_server){ ## launch only on mail serevr
    # spamassassin depends on db configuration
    system("$installDir/subs/subs_includes_spamassassin.pl");
  }
}


sub UpdateMainConfig{
  print "\n";
  &ReadMainConfigFile;
  &WriteMainConfigFile;
}


sub checkVar{
 my ($var, $name) = @_;

 if($var eq ''){
   print "Variable \$$name is empty!\n";
   exit 1;
 }

}


sub WriteMainConfigFile{

	my $conf = &initConfig( $installDir );

	unless ( ref($conf) =~ /Config/ ) {
		die "Error: can't get global settings from '$installDir'\n";
	}

  &checkVar($version, 'version');
  if ( $mail_server != 2 && $dns_server != 2 ) { 
		&checkVar($user_homeDir, 'user_homeDir'); 
	}
  &checkVar($installDir, 'installDir');

  $mysqlUserPw = &escapeVar($mysqlUserPw);
  $dbPw = &escapeVar($dbPw);

	my $dstPath = "$installDir/confixx_main.conf";
	my $bakPath = "$installDir/confixx_main.conf.bak";

  my $time = localtime();
  print &ltext('install_do_file_create', $dstPath );

	if ( move( $dstPath, $bakPath ) ) {
  	chown( 0,0, $bakPath );
  	chmod( 0400, $bakPath );
	}

  unless ( open (FILE, '>', $dstPath ) ){
		die "Can't open file '$dstPath': $!\n";
	}

  print FILE << "CONFIG";
#### CONFIXX MAIN CONFIGFILE ####
#### created $time ###

## general

# e.g. Linux, FreeBSD
\$OSTYPE = '$OSTYPE';

# Confixx Version
\$version = '$version';

# location of webusers homedirs
\$user_homeDir = '$user_homeDir';

# directory where Confixx is installed
\$installDir = '$installDir';

# users with shell access get this shell
\$stdShell = '$stdShell';

# group of Confixx webusers
\$userGroup = '$userGroup';

# group of Confixx mailusers
\$popGroup = '$popGroup';

# uid of userGroup
\$giduser = '$giduser';

# uid of popGroup
\$gidpop = '$gidpop';

# location of passwd file
\$passwdDir = '$passwdDir';

# location of shadow file
\$shadowDir = '$shadowDir';

# location of group file
\$groupDir = '$groupDir';

# lowest uid for users created with Confixx
\$min_uid = '$min_uid';

# highest uid for users created with Confixx
\$max_uid = '$max_uid';

# local hostname
\$hostname = '$hostname';

# location of pidfiles for Confixx programs
\$PIDDir = '$PIDDir';

# prefix for all Confixx users
\$user_prefix = '$user_prefix';

# language for all shell based Confixx applications
\$language = '$language';

# compatible languagefiles need to be greater or equals
\$langfileversion = '$langfileversion';

# files used for DirectoryIndex if WAP is activated (seperated by :)
\$index_wap = '$index_wap';

# files used for DirectoryIndex if PHP is activated (seperated by :)
\$index_php = '$index_php';

# files used for DirectoryIndex if SSI is activated (seperated by :)
\$index_ssi = '$index_ssi';

# files used for DirectoryIndex (seperated by :)
\$index_html = '$index_html';

# show mail traffic in webinterface
\$show_emailtransfer = '$show_emailtransfer';

# max number of possible email recipients in webinterface
\$max_emailrcpts = '$max_emailrcpts';

# disable usage of md5 for passwords
\$disable_md5 = '$disable_md5';

# compatibility for Virtuozzo (default is 0)
\$virtuozzo = '$virtuozzo';

# create /home/www/web1/./ passwd entries (e.g. ssh-chroot)
\$dot_passwd = '$dot_passwd';

# check & restore permissions of user's files/dirs ( ~/html, ~/files)
\$restore_users_permissions = '$restore_users_permissions';

## process management

# pm_*_reload: full command to be used to reload daemon, if empty Confixx uses signals
# pm_*_start: full command to be used to stard daemon, if not running _after_ reload
# pm_*_user: username of process (used for finding process to send signal)
# pm_*_name: name of process (used for finding process to send signal)

\$pm_apache_reload = '$pm_apache_reload';
\$pm_apache_start = '$pm_apache_start';
\$pm_apache_user = '$pm_apache_user';
\$pm_apache_name = '$pm_apache_name';
\$pm_mail_reload = '$pm_mail_reload';
\$pm_mail_start = '$pm_mail_start';
\$pm_mail_user = '$pm_mail_user';
\$pm_mail_name = '$pm_mail_name';
\$pm_bind_reload = '$pm_bind_reload';
\$pm_bind_start = '$pm_bind_start';
\$pm_bind_user = '$pm_bind_user';
\$pm_bind_name = '$pm_bind_name';
\$pm_spamassassin_reload = '$pm_spamassassin_reload';
\$pm_spamassassin_start = '$pm_spamassassin_start';
\$pm_spamassassin_user = '$pm_spamassassin_user';
\$pm_spamassassin_name = '$pm_spamassassin_name';
\$pm_ftpd_noscript = '$pm_ftpd_noscript';
\$pm_ftpd_reload = '$pm_ftpd_reload';
\$pm_ftpd_start = '$pm_ftpd_start';

## apache

# group used by Apache (Group in httpd.conf!)
\$apacheGroup = '$apacheGroup';
\$apacheUser = '$apacheUser';

# rotate logfile if greater than value (kb) after analysis
\$apacheBackupSize = '$apacheBackupSize';

# day on which logfiles will be rotated, ignoring size on this day (0=Sun, set to 8 to disable)
\$apacheBackupDay = '$apacheBackupDay';

# 1: rotate logfiles in user's homedir, 0: rotate to \$apacheBackupDir
\$apacheBackupLocal = '$apacheBackupLocal';

# keep _old_ logfiles for X days
\$apacheBackupExpire = '$apacheBackupExpire';

# location where to keep rotated logfiles (if not user's homedir)
\$apacheBackupDir = '$apacheBackupDir';

# location of general Apache logfiles for Confixx and symlinks to user's logfiles
\$apacheLogDir = '$apacheLogDir';

# value used as <IfDefine value> for ssl entries in confixx_vhost.conf, defaults use <IfModule mod_ssl.c>
\$apacheDefSSL = '$apacheDefSSL';

# Confixx web pages user's homedir
\$confixx_homeDir = '$confixx_homeDir';

# location of Confixx web pages
\$confixx_htmlDir = '$confixx_htmlDir';

# location of Confixx web cgis
\$confixx_cgiDir = '$confixx_cgiDir';

# location of Confixx web pages temporary dir (e.g. php upload)
\$confixx_tmpDir = '$confixx_tmpDir';

# location of Confixx web pages bin dir
\$confixx_binDir = '$confixx_binDir';

# location of Confixx web pages sbin dir
\$confixx_sbinDir = '$confixx_sbinDir';

# location of Apache's httpd.conf
\$httpd_conf = '$httpd_conf';

# location of Confixx vhosts file for Apache (included by mhost.conf)
\$vhost_conf = '$vhost_conf';

# location of Confixx main Apache config file (included by httpd.conf)
\$mhost_conf = '$mhost_conf';

# uid of \$apacheGroup
\$gidapache = '$gidapache';

# uid of Confixx web pages user
\$confixx_uid = '$confixx_uid';

# gid of Confixx web pages user
\$confixx_gid = '$confixx_gid';

# name of Confixx web pages user
\$confixx_user = '$confixx_user';

# group of Confixx web pages user
\$confixx_group = '$confixx_group';

# IP for Confixx's web panel
\$confixx_IP = '$confixx_IP';

# location of ssl .key files
\$sslKeyDir = '$sslKeyDir';

# location of ssl .crt files
\$sslCrtDir = '$sslCrtDir';

# location if fpfake.conf (FrontPage Apache config file)
\$fpfake = '$fpfake';

# location of FrontPage installation
\$fp_homeDir = '$fp_homeDir';

# uid of FrontPage files
\$fp_uid = '$fp_uid';

# gid of FrontPage files
\$fp_gid = '$fp_gid';

# Apache base dir for config files (has subdirectory conf!)
\$apache_root = '$apache_root';

# have seperate /cgi-bin/ for subdomains
\$local_cgi = '$local_cgi';

# disable "AllowOverride All" for FrontPage webs (requires patched FrontPage)
\$secure_fp = '$secure_fp';

# do not write NameVirtualHost for list of ips (seperated by :)
\$excludeNVH = '$excludeNVH';

# number of bytes to be added to every entry in Apache logfile analysis (default is 0!)
\$httpbytes = '$httpbytes';

# type of webserver ( apache1.3 | apache2.0 )
\$httpd = '$httpd';


## email

# used mta ( sendmail | postfix | qmail )
\$mta = '$mta';

# location of mailspool directory
\$mailSpool = '$mailSpool';

# type of maildrop ( /var/spool/mail/USER | HOMEDIR/Mailbox | HOMEDIR/Maildir/ )
\$maildrop = '$maildrop';

# name of Mailbox file
\$mailBoxName = '$mailBoxName';

# location of email virtusertable file
\$virtUserTableDB = '$virtUserTableDB';

# location of email local domains file
\$localDomainsFile = '$localDomainsFile';

# location of makemap binary (sendmail only)
\$bin_makemap = '$bin{'makemap'}';

# location of postmap binary (postfix only)
\$bin_postmap = '$bin{'postmap'}';

# location of postfix binary (postfix only)
\$bin_postfix = '$bin{'postfix'}';

# location of newaliases binary (sendmail & postfix)
\$bin_newaliases = '$bin{'newaliases'}';

# location of mta main config file
\$MailConfigFile = '$MailConfigFile';

# location of mail users homedir
\$pop_homeDir = '$pop_homeDir';

# location of aliases binary (sendmail & postfix)
\$aliases = '$aliases';

# location of autoresponder.pl
\$bin_autorespond = '$bin{'autorespond'}';

# XXX
\$use_autorespond = '$use_autorespond';

# uid used by mta to run local scripts (e.g. autoresponder.pl)
\$mta_uid = '$mta_uid';

# gid used by mta to run local scripts (e.g. autoresponder.pl)
\$mta_gid = '$mta_gid';

# location of sendmail binary (to send mails from local)
\$bin_sendmail = '$bin{'sendmail'}';

# mail users get real homedir (ignoring \$maildrop)
\$mail_realHome = '$mail_realHome'; 

# 1: mta is on localhost, 0: mta is on remote host
\$mail_server = '$mail_server';

# 0: do not count mail disk usage, 1: add mail disk usage to user's disk usage value
\$append_mail_disk_space = '$append_mail_disk_space';

# XXX
\$bin_confixxevent = '$bin{'confixxevent'}';

# XXX
\$use_events = '$use_events';


## scponly

# shell used for scp/sftp feature
\$scponly_shell = '$scponly_shell';

# name of directory in \$user_homeDir with chroot-environment
\$scponly_chroot = '$scponly_chroot';


## maillist
# directory where majordomo is installed
\$majordomo_home = '$majordomo_home'; 

# location of majordomo wrapper binary
\$majordomo_wrapper = '$majordomo_wrapper';

# majordomo mailinglists dir
\$majordomo_ldir = '$majordomo_ldir';

# majordomo username
\$majordomo_user = '$majordomo_user';


## IDN support

# XXX
\$idn_shell =  '$idn_shell';

# XXX
\$idn_vendor = '$idn_vendor';

# XXX
\$iconv_shell = '$iconv_shell';
\$iconv_utf8 = '$iconv_utf8';

## spam protection

# XXX
\$spamassassin_support = '$spamassassin_support';

# path to spamassassin configuration file (local.cf)
\$spamassassinConfig = '$spamassassinConfig';

# set this argument to the uid under which you spamassassin daemon is running
# (check '-u' option of 'spamd')
# if no value specified, than it is supposed then your spamd is running 
# under the root user
\$spamassassinUid = '$spamassassinUid';

## cold fusiomn

# XXX
\$coldfusion_support = '$coldfusion_support';


## cronjobs

# XXX
\$cronjobs_support = '$cronjobs_support';

## bins

# location of find binary
\$bin_find = '$bin{'find'}';

# location of cp binary
\$bin_cp = '$bin{'cp'}';

# location of grep binary
\$bin_grep = '$bin{'grep'}';

# location of chown binary
\$bin_chown = '$bin{'chown'}';

# location of chmod binary
\$bin_chmod = '$bin{'chmod'}';

# location of rm binary
\$bin_rm = '$bin{'rm'}';

# location of du binary
\$bin_du = '$bin{'du'}';

# location of ifconfig binary
\$bin_ifconfig = '$bin{'ifconfig'}';

# location of webalizer binary
\$bin_webalizer = '$bin{'webalizer'}';

# location of FrontPage binary (fpsrvadm.exe for 2000, owsadm.exe for 2002)
\$bin_fpsrvadm = '$bin{'fpsrvadm'}';

# location of openssl binary
\$bin_openssl = '$bin{'openssl'}';

# location for psql binary (if PostgreSQL is used)
\$bin_psql = '$bin{'psql'}';

# location of mysql binary
\$bin_mysql = '$bin{'mysql'}';
\$bin_mysqldump = '$bin{'mysqldump'}';

# location of gzip binary
\$bin_gzip = '$bin{'gzip'}';

# location of tar binary
\$bin_tar = '$bin{'tar'}';

# location of unzip binary
\$bin_unzip = '$bin{'unzip'}';

# XXX
\$bin_iconv = '$bin{'iconv'}';

# XXX
\$bin_idn = '$bin{'idn'}';

# XXX
\$bin_su = '$bin{'su'}';

#quota
\$use_quota = '$use_quota';
\$mail_quota = '$mail_quota';
\$user_quota = '$user_quota';
\$majordomo_quota = '$majordomo_quota';
\$inode_std = '$inode_std';

# ftp
\$ftpDaemon = '$ftpDaemon';
\$ftpConfFile = '$ftpConfFile';
\$ftpLogFile = '$ftpLogFile';
\$ftpbytes = '$ftpbytes';
\$chrootUsers = '$chrootUsers';
\$ftpEmail = '$ftpEmail';

#
# DB settings for Confixx database
#

# Type of database (mysql|pgsql)
\$dbType = '$dbType';

#Host of the database server (IP or domain name)  
\$dbServer = '$dbServer';

# Port to connect to or path to mysql socket (mysql.sock)
\$dbPort = '$dbPort';

# Login information
\$dbUser = '$dbUser';
\$dbPw = '$dbPw';

#Confixx database name
\$dbDB = '$dbDB';

# Confixx db mysql version if$dbType == 'mysql'
\$dbMysqlVersion = '$dbMysqlVersion';

#
# MySQL DB settings for users' databases
#

#Host users' databases are stored on
\$mysqlUserServer = '$mysqlUserServer';

#Port to connect to or path to mysql socket (mysql.sock)
#mysql socket is used when users' database server is located on the localhost.
\$mysqlUserPort = '$mysqlUserPort';

#Login information
#it must be priveleged mysql user to create users' databases
\$mysqlUserUser = '$mysqlUserUser';
\$mysqlUserPw = '$mysqlUserPw';

#Host to connect FROM. 
#It is usually an ip or domain of the host confixx_updatescript.pl runs on
#This host will be stored in mysql.User and mysql.Db tables 
#to specify connections allowed from for users.
\$mysqlUserHost = '$mysqlUserHost';

#Version of the users' mysql database server
\$mysqlUserVersion ='$mysqlUserVersion';

\$mysql_homeDir = '$mysql_homeDir';
\$use_mysqlshell = '$use_mysqlshell';

# cgis
\$mail_pop3Server = '$mail_pop3Server';

# dns
\$dns_server = '$dns_server';
\$dns_type = 'bind';
\$dns_dir = '$dns_dir';
\$dns_extension = '.db';
\$dns_configure = '$dns_configure';
\$dns_serverid = '$dns_serverid';
\$dns_chroot = '$dns_chroot';
\$dns_copyconf = '$dns_copyconf';

\$rpm_version_flag = '$rpm_version_flag';
\$no_questions_mode = '$no_questions_mode';

##

\$no_pipelog_mode = '$no_pipelog_mode';

## confixx updates
\$new_version_url = '$new_version_url';

# disable backup
\$backup_off = '$backup_off';

     ### ENDE ####

CONFIG

	$db_address ||= &makeDSN( $dbType, $dbServer, $dbDB, $dbPort );
	print FILE "# DSN\n\$db_address = '$db_address';\n";

  close (FILE);
  chown(0,0, $dstPath );
  chmod(0400, $dstPath );

	$conf->Path( $dstPath, 'stat');

	return $conf;
}


sub ReadMainConfigFile{

	my $conf = &initConfig( $installDir );

	unless ( ref($conf) =~ /Config/ ) {
		die "Error: can't get global settings from '$installDir'\n";
	}

	if ($use_quota == 0) {
		$conf->Value( 'mail_quota', 0 );
		$conf->Value( 'user_quota', 0 );
		$conf->Value( 'majordomo_quota',0 );
	}

	unless( $max_emailrcpts =~ /^\d+$/ ) {
		$conf->Value( 'max_emailrcpts', 10 );
	}

	unless( defined( $disable_md5 ) ) {
		$conf->Value( 'disable_md5', 0 );
	}

	unless( defined( $virtuozzo ) ) {
		$conf->Value( 'virtuozzo', 0 );
	}

	unless( defined ($restore_users_permissions ) ) {
		$conf->Value( 'restore_users_permissions', 0 );
	}

	unless( defined( $dot_passwd ) ) {
		$conf->Value( 'dot_passwd', 0 );
	}

	unless ( $mail_server eq '0' ) {
		$conf->Value( 'mail_server', 1 );
	}

  unless ( defined( $append_mail_disk_space ) ) {
		$conf->Value( 'append_mail_disk_space', 0 );
  }

	unless ( $chrootUsers =~ /^\/\S+$/ ) {
		$conf->Value( 'chrootUsers', '/etc/chrootUsers' );
  }

  unless( defined( $dns_server ) ) {
		$conf->Value( 'dns_server', 0 );
  }

	$conf->Value( 'dns_type', 'bind') unless $dns_type eq 'bind';
	$conf->Value( 'dns_extension', '.db') unless $dns_extension eq '.db';

  unless( defined( $backup_off ) ) {
		$conf->Value( 'backup_off', 0 );
  }

	unless( $apacheBackupExpire ) {
		$conf->Value( 'apacheBackupExpire', 90 );					
	}	

	unless( $ftpbytes =~ /^\d+$/ ) {
		$conf->Value( 'ftpbytes', 0 );				
	}	

	unless( $apacheDefSSL ) {
		$conf->Value( 'apacheDefSSL', 'SSL' );				
	}

	unless( $httpd =~ /^apache(1\.3|2\.0)$/ ) {
		$conf->Value( 'httpd', 'apache1.3' );				
	}

	unless( $mail_pop3Server ) {
		$conf->Value( 'mail_pop3Server', 'localhost' );			
	}
}


sub WritePHPConfigFile{
  my $time = localtime();
  my ($apacheGID,$spamAssVersion);
  print &ltext('install_do_file_create', "$confixx_homeDir/settings.inc.php");

	if ( eval "require Mail::SpamAssassin" ) {
		$spamAssVersion = $Mail::SpamAssassin::VERSION;
	}


  open (FILE, ">$confixx_homeDir/settings.inc.php");

  print FILE <<"CONFIG";
<?
#### CONFIXX PHP CONFIG FILE ####
    ### created at $time ###

define( "MaxPwdLength", 12 );

\$installDir = '$installDir'; # directory where Confixx is installed
\$version = '$version';
\$langfileversion = '$langfileversion';
\$default_language = '$language';
\$user_prefix = '$user_prefix'; # do not edit!!
\$hostname = '$hostname';
\$bindir = '$confixx_binDir';
\$sbindir = '$confixx_sbinDir';
\$tmp_dir = '$confixx_tmpDir';
\$confixx_htmlDir = '$confixx_htmlDir';
\$confixx_user = '$confixx_user';

\$db_type = '$dbType';
\$db_db = '$dbDB';
\$db_port = '$dbPort';
\$db_host = '$dbServer';
\$db_user = '$dbUser';
\$db_pass = '$dbPw';
\$db_version = '$dbMysqlVersion';
\$mysql_user_host = '$mysqlUserServer';
\$mysql_user_user = '$mysqlUserUser';
\$mysql_user_pass = '$mysqlUserPw';
\$mysql_user_port = '$mysqlUserPort';
\$mysql_user_version = '$mysqlUserVersion';
\$mysql_host = '$mysqlUserHost';

\$iconv_utf8 = '$iconv_utf8';

\$mail_pop3Server = '$mail_pop3Server';
\$spamAssVersion = '$spamAssVersion';

\$fehlerfarbe = '#FF9900';
\$color_dark_grey = '#CCCCCC';
\$color_light_grey = '#EEEEEE';
\$color_blue = '#000066';
\$color_arrow = '#A0CCFF';
\$show_emailtransfer = '$show_emailtransfer';
\$max_emailrcpts = '$max_emailrcpts';
\$disable_md5 = '$disable_md5';

\$show_dotfiles = '1';
\$backup_off = '$backup_off';

     ### END ####
?>
CONFIG
  close (FILE);

  $apacheGID = getgrnam ( $apacheGroup );
  chown ( $confixx_uid, $apacheGID, "$confixx_homeDir/settings.inc.php");
  chmod (0440, "$confixx_homeDir/settings.inc.php");


  if("$confixx_htmlDir" ne "$confixx_homeDir"){
    print &ltext('install_do_file_create', "$confixx_htmlDir/settings.inc.php");
    open (FILE, ">$confixx_htmlDir/settings.inc.php");

    print FILE <<"CONFIG";
<?
include("$confixx_homeDir/settings.inc.php");
?>
CONFIG
    close (FILE);

    chown ($confixx_uid, $confixx_gid, "$confixx_htmlDir/settings.inc.php");
    chmod (0444, "$confixx_htmlDir/settings.inc.php");
  }

#
# events-support
#
  unless ($subs_include_events){
	$subs_include_events="$installDir/subs_include_events.pl";
  }	
  if (-f $subs_include_events){
	my @consts;
	open(EVENTS,"< $subs_include_events");
	while (<EVENTS>){
	  if (/^\s*sub\s+/){
		last;
	  }	  
	  if (/^\s*\$OBJECT_/ || /^\s*\$EVENT_/){
		push @consts, $_;
	  }
	}
	close(EVENTS);

    my $events_inc="$confixx_homeDir/events.inc.php";
	print &ltext('install_do_file_create', $events_inc);
	open (FILE, "> $events_inc");

	print FILE <<"CONFIG";
<?
#### CONFIXX EVENTS CONFIG FILE ####
#### created at $time ####

CONFIG
	foreach my $str (@consts) {
	  print FILE $str;
	}
	print FILE <<"CONFIG";

#### END ####
?>
CONFIG

	close (FILE);

	chown ($confixx_uid, $confixx_gid, $events_inc);
	chmod (0444, $events_inc);

        if("$confixx_htmlDir" ne "$confixx_homeDir"){
	  $events_inc="$confixx_htmlDir/events.inc.php";
  
	  print &ltext('install_do_file_create', $events_inc);
	  open (FILE, "> $events_inc");

	  print FILE <<"CONFIG";
<?
include("$confixx_homeDir/events.inc.php");
?>
CONFIG
	  close (FILE);

	  chown ($confixx_uid, $confixx_gid, $events_inc);
	  chmod (0444, $events_inc);
        }
  }
#
# /events-support
#  
}

sub writeHTTPDTraffik{
  my $time = localtime();
  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 -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");
}

#
# restoring binaries from SQL-base
#
# arguments:
#
# $dbh    - handle of connect to SQL-base
# $ptrBin - hash of binaries
# $grp    - kode of grop of binaries
#
sub RestoreBin{
  my %ret=();
  my ($ptrBin,$grp,$name,$path);
  my $myConnect=0;

  my $myDbh=shift;
  if (ref($myDbh) eq 'HASH'){
    $ptrBin=$myDbh;
    undef $myDbh;
  }elsif(ref($myDbh) !~/DBI/){
    $grp=$myDbh;
    undef $myDbh;
  }

  if (ref($myDbh) !~/DBI/ && ref($dbh) =~ /DBI/){
    $myDbh=$dbh;
  }

  unless (defined $ptrBin){
    $ptrBin = shift;
  }

  if (defined($ptrBin) &&  ref($ptrBin) ne 'HASH'){
    $grp=$ptrBin;
    undef $ptrBin;
  }

  if (ref($ptrBin) ne 'HASH' && (defined %bin)){
    $ptrBin =\%bin;
  }

  unless(defined ($grp)){
    $grp=shift || '';
  }


  unless($myDbh){
		$dbaddress = &makeDSN($dbType,$dbServer,$dbDB,$dbPort);
    $myDbh = DBI->connect($dbaddress, $dbUser, $dbPw)
      or die  "#2009: Unable to connect to SQL-server:  $DBI::errstr\n" ;
    $myConnect=1;
  }

  unless ( ref($ptrBin) eq 'HASH'){
    $ptrBin = \%ret;
  }

	my ($major);
	if($version =~ /^(\d+)/){
		$major = $1;
	}
	if($major>=3){
		my $sql='SELECT name,path FROM bin';
		if ($grp){
			$sql.=" where grp='$grp'";
		}
		my $sth=$myDbh->prepare($sql);
		if($sth->execute){ 
			while (($name,$path)=$sth->fetchrow){
				if (-x $path){
					$ptrBin->{$name}=$path;
				}
			}
			$sth->finish;
		}else{
			warn "#2020: Error execute sql: '$sql'\n$DBI::errstr\n";
		}
		if($myConnect){
			$myDbh->disconnect;
		}
  }

  return $ptrBin;
}

#
# storing binaries to SQL-base
#
# arguments:
#
# $dbh    - handle of connect to SQL-base
# $ptrBin - hash of binaries
# $grp    - kode of grop of binaries
#
sub StoreBin{
  my $ptrBin;
  my $grp;
  my $myConnect=0;
  my $myDbh;

  $myDbh=shift;
  if (ref($myDbh) eq 'HASH'){
    $ptrBin=$myDbh;
    undef $myDbh;
  }elsif(ref($myDbh) !~/DBI/){
    $grp=$myDbh;
    undef $myDbh;
  }

  if (ref($myDbh) !~/DBI/ && ref($dbh) =~ /DBI/){
    $myDbh=$::dbh;
  }

  unless (defined $ptrBin){
    $ptrBin = shift;
  }
  if (defined($ptrBin) &&  ref($ptrBin) ne 'HASH'){
    $grp=$ptrBin;
    undef $ptrBin;
  }

  if (ref($ptrBin) ne 'HASH' && (defined %bin)){
    $ptrBin =\%bin;
  }

  unless(defined ($grp)){
    $grp=shift || '';
  }

  unless($myDbh){
		$dbaddress = &makeDSN($dbType,$dbServer,$dbDB,$dbPort);
    $myDbh = DBI->connect($dbaddress, $dbUser, $dbPw)
      or die  "#2009: Unable to connect to SQL-server:  $DBI::errstr\n" ;
    $myConnect=1;
  }

  if (keys %$ptrBin){
    my (%matchedBin,$list,$sql,$sth);
    if($grp){
      $list = join(',',map{"'$_'"} keys %{$ptrBin});
      $sql = "select id,name from bin where not(grp in ('','$grp')) and (name in ($list))";
      $sth =$myDbh->prepare($sql);
      if ($sth->execute){
				my ($id,$name);
				while (($id,$name)=$sth->fetchrow){
					if($myDbh->do("update bin set grp='' where id=$id")){
						$name=~s/\s+$//;
						$name=~s/^\s+//;
						$matchedBin{$name}=$id;
					}
				}
				$sth->finish;
      }
    }
    $sql="SELECT id,name,path FROM bin";
    if ($grp){
      $sql.=" WHERE grp IN ('','$grp')";
    }
    $sth=$myDbh->prepare($sql);
    $sth->execute or warn "#2020: Error execute sql: '$sql'\n$DBI::errstr\n";
    my (%exbin,@row);
    while (@row=$sth->fetchrow){
      $row[1]=~s/\s+$//;
      $row[1]=~s/^\s+//;
      push @{$exbin{$row[1]}},$row[0];
      push @{$exbin{$row[1]}},$row[2];
    }

    $sth->finish;

    while (my($name,$path)=each(%$ptrBin)){
      next if exists $matchedBin{$name};
      unless (-x $path){
				next;
      }
      if (exists($exbin{$name})){
				my($id,$expath)=@{$exbin{$name}};
				unless ($expath eq $path ){
					$sql="UPDATE bin SET path='$path'";
					if ($grp){
						$sql.=",grp='$grp'";
					}
					$sql.=" WHERE id=$id";
					$myDbh->do($sql);
				}
      }else{
				$sql="INSERT INTO bin (name,path";
				if ($grp){
					$sql.=",grp";
				}
				$sql.=") VALUES('$name','$path'";
				if ($grp){
					$sql.=",'$grp'";
				}
				$sql.=")";
				$myDbh->do($sql) or 
					warn "#2020: Error execute sql: '$sql'\n$DBI::errstr\n";
      }
    }
  }
  if($myConnect){
    $myDbh->disconnect;
  }
}

sub StringToVar{
  my ($string) = @_;
  if($string =~ /^\$(\S+) = ["'](.*)["']/){
    my $key = $1;
    my $var = $2;
    $var =~ s/\\'/'/g;
    return($key, $var);
  }
  else{
    return(0,0);
  }
}

sub escapeVar{
  my $var = shift;
  $var =~ s/'/\\'/g;
  return ($var);
}

1;
## UNTERPROGRAMME FÜR CONFIXX INSTALLATION & KONFIGURATION
