#!/bin/sh

if [ -f $DTC_SAVED_INSTALL_CONFIG ] ; then
	. ${DTC_SAVED_INSTALL_CONFIG}
fi

. ${PATH_DTC_ADMIN}/install/minimal_chroot

LIST_CHROOT_DIRS="bin var lib sbin tmp usr dev etc"
if [ `uname -m` = "x86_64" ] ; then
	LIST_CHROOT_DIRS="$LIST_CHROOT_DIRS lib64"
fi

if [ -z "$MKTEMP" ] ; then
	MKTEMP="mktemp -t"
fi

if [ -z "$MX_MAIL" ] ; then
	if ! [ -z "$conf_mx_mail" ] ; then
		MX_MAIL=${conf_mx_mail}
	else
		MX_MAIL="mx"
	fi
fi

if [ -z ${PATH_BASH} ] ; then
	if [ -x /bin/bash ] ; then
		PATH_BASH=/bin/bash
	else
		if [ -x /usr/local/bin/bash ] ; then
			PATH_BASH=/usr/local/bin/bash
		else
			if [ -x ${LOCALBASE}/bin/bash ] ; then
				PATH_BASH=${LOCALBASE}/bin/bash
			fi
		fi
	fi
fi

if [ -z "$AMAVISD_USER" ] ; then
	AMAVISD_USER=amavis
fi

echoIfVerbose () {
	if [ ""$VERBOSE_INSTALL = "yes" ] ; then
		echo $1
	fi
}

createDTCuserAndGroup () {
	echoIfVerbose "===> Create DTC user and group"
	# This is for OSX
	if [ -x /usr/bin/niutil ] ; then
		NIUTIL=/usr/bin/niutil
		if [ ! $NIUTIL -list . /groups | grep ""${CONF_DTC_SYSTEM_GROUPNAME} ] ; then
			$NIUTIL -create . /groups/${CONF_DTC_SYSTEM_GROUPNAME}
		fi
		CONF_DTC_SYSTEM_GID=`$NIUTIL -list . /groups | grep ${CONF_DTC_SYSTEM_GROUPNAME} | cut -d" " -f1`
		
		if [ ! $NIUTIL -list . /users | grep ""${CONF_DTC_SYSTEM_USERNAME} ] ; then
			$NIUTIL -create . /users/${CONF_DTC_SYSTEM_USERNAME} gid ${CONF_DTC_SYSTEM_GID}
		fi
		CONF_DTC_SYSTEM_UID=`$NIUTIL -list . /users | grep ${CONF_DTC_SYSTEM_USERNAME} | cut -d" " -f1`
		$NIUTIL -createprop . /groups/${CONF_DTC_SYSTEM_GROUPNAME} gid ${CONF_DTC_SYSTEM_GID}
		$NIUTIL -createprop . /users/${CONF_DTC_SYSTEM_USERNAME} gid ${CONF_DTC_SYSTEM_GID}
		$NIUTIL -createprop . /users/${CONF_DTC_SYSTEM_USERNAME} uid ${CONF_DTC_SYSTEM_UID}
	else
		if [ -x /usr/compat/linux/usr/bin/getent ] ; then
			GETENT=/usr/compat/linux/usr/bin/getent
		else
			GETENT=getent
		fi
		if ${GETENT} group ${CONF_DTC_SYSTEM_GROUPNAME} >/dev/null ; then
			echoIfVerbose "-> Group ${CONF_DTC_SYSTEM_GROUPNAME} already exists: skipping creation!"
		else
			if [ -x /usr/sbin/groupadd ] ; then
				/usr/sbin/groupadd ${CONF_DTC_SYSTEM_GROUPNAME}
			else
				# This is for freebsd
				pw groupadd ${CONF_DTC_SYSTEM_GROUPNAME}
			fi
		fi
		CONF_DTC_SYSTEM_GID=`${GETENT} group ${CONF_DTC_SYSTEM_GROUPNAME} | cut -d':' -f3`
	
		if ${GETENT} passwd ${CONF_DTC_SYSTEM_USERNAME} >/dev/null ; then
			echoIfVerbose "-> User ${CONF_DTC_SYSTEM_USERNAME} already exists: skipping creation!"
		else
			if [ -x /usr/sbin/useradd ] ; then
				if [ -x ${PATH_BASH} ] ; then
					/usr/sbin/useradd -m -s ${PATH_BASH} -g ${CONF_DTC_SYSTEM_GROUPNAME} ${CONF_DTC_SYSTEM_USERNAME}
				else
					echo "Could not find a shell, please fix me here!!!"
				fi
			# This one is for freebsd
			else
				if [ -x /bin/sh ] ; then
					pw useradd ${CONF_DTC_SYSTEM_USERNAME} -g ${CONF_DTC_SYSTEM_GROUPNAME} -s /bin/sh
				else
					echo "Could not find a shell, please fix me here!!!"
				fi
			fi
		fi
		CONF_DTC_SYSTEM_UID=`${GETENT} passwd ${CONF_DTC_SYSTEM_USERNAME} | cut -d':' -f3`
	fi
	if [ -z ""$CONF_DTC_SYSTEM_UID ] ; then
		echo "No dtc system user: exiting"
		exit 1
	fi
	if [ -z ""$CONF_DTC_SYSTEM_GID ] ; then
		echo "No dtc system group: exiting"
		exit 1
	fi
	# Add the bind user to the dtcgrp group, and allow failure (if bind8, then there is no bind user,
	# and the operation might have been done before)
	if [ "$UNIX_TYPE" = "debian" ] ; then
		adduser bind dtcgrp >/dev/null 2>&1  || true
	fi
	if [ "$UNIX_TYPE" = "gentoo" ] ; then
		usermod -G ${CONF_DTC_SYSTEM_GROUPNAME} named >/dev/null 2>&1 || true
	fi
}

findHtpasswdBinary () {
	HTPASSWD=`which htpasswd 2>/dev/null`
	if [ -z "$HTPASSWD" ] ; then
		HTPASSWD=`which htpasswd2 2>/dev/null`;
	fi
	# This might be needed for FreeBSD if /usr/local/bin is not in the path
	if [ -z "$HTPASSWD" ] ; then
		if [ -x "/usr/bin/htpasswd" ] ; then
			HTPASSWD="/usr/bin/htpasswd"
		else
			if [ -x "/usr/bin/htpasswd2" ] ; then
				HTPASSWD="/usr/bin/htpasswd2"
			else
				if [ -x "/usr/local/bin/htpasswd" ] ; then
					HTPASSWD="/usr/local/bin/htpasswd"
				else
					if [ -x "/usr/local/bin/htpasswd2" ] ; then
						HTPASSWD="/usr/local/bin/htpasswd2"
					fi
				fi
			fi
		fi
	fi
}


searchPATH_PHP_CGI () {
	echoIfVerbose "===> Searching for php binary"
	if [ -e /usr/bin/php ] ; then
		PATH_PHP_CGI="/usr/bin/php"
	else
		if [ -x /usr/bin/php4 ] ; then
			PATH_PHP_CGI="/usr/bin/php4"
		else
			if [ -x /usr/bin/php5 ] ; then
				PATH_PHP_CGI="/usr/bin/php5"
			else
				if [ -x "/usr/local/bin/php" ] ; then
					PATH_PHP_CGI="/usr/local/bin/php"
				else
					echo "Could not find the php cli binary!!!"
					exit 1
				fi
			fi
		fi
	fi
}

# Do a test to check php version. Those fucking PHP guys had
# made things so simple that this test is not very short... :(
searchPHPversion () {
	echoIfVerbose "-> Searching for PATH_PHP_CGI"
	CNT=`${PATH_PHP_CGI} -v | wc -l`
	if [ $CNT -ge 2 ]
	then
		PHPVE=`${PATH_PHP_CGI} -v | head -n 1 | cut -f2 -d" "`
	else
		PHPVE=`${PATH_PHP_CGI} -v || true`
	fi

	PHPMAJOR=`echo $PHPVE | cut -f1 -d"."`
	PHPMINOR=`echo $PHPVE | cut -f2 -d"."`

	echoIfVerbose "The DTC installer has detected PHP version $PHPMAJOR release $PHPMINOR"
}

searchPATH_PHP_INI_CLI () {
	echoIfVerbose "-> Searching for PATH_PHP_INI_CLI"
	# This one is for FreeBSD
	if [ -f /usr/local/etc/php.ini ] ; then
		PATH_PHP_INI_CLI=/usr/local/etc/php.ini
	# This one for RedHat / CentOS
	elif [ -f /etc/php.ini ] ; then
		PATH_PHP_INI_CLI=/etc/php.ini
	# This one for Gentoo
	elif [ -f /etc/php/cli-php5/php.ini ] ; then
		PATH_PHP_INI_CLI=/etc/php/cli-php5/php.ini
	elif [ ""${PHPMAJOR} -lt 5 ] ; then
		if [ -f /etc/php4/cli/php.ini ] ; then
			PATH_PHP_INI_CLI=/etc/php4/cli/php.ini
		else
			echo "Cannot find php.ini path!"
			exit 1
		fi
	else
		if [ -f /etc/php5/cli/php.ini ] ; then
			PATH_PHP_INI_CLI=/etc/php5/cli/php.ini
		elif [ -f "$PATH_PHP_INI" ] ; then
			PATH_PHP_INI_CLI=$PATH_PHP_INI
		else
			echo "Cannot find php.ini path!"
			exit 1
		fi
	fi
}


searchDebianVersion () {
	if [ -f /etc/debian_version ] ; then
		echoIfVerbose "-> Searching for debian version"
		DEBIAN_VERSION=`cat /etc/debian_version`
	fi
}

searchPATH_PHP_INI_APACHE () {
	echoIfVerbose "-> Searching for php.ini for the apache $conf_apache_version module and php ${PHPMAJOR}"
	# If already set, don't do anything
	if [ -f "${PATH_PHP_INI_APACHE}" ] ; then
		echo -n ""
	# This one is for slackware
	elif [ -f "$PATH_PHP_INI" ] ; then
		PATH_PHP_INI_APACHE=$PATH_PHP_INI
	# This one is for FreeBSD
	elif [ -f /usr/local/etc/php.ini -o -f /usr/local/etc/php.ini-production ] ; then
		if [ ! -f /usr/local/etc/php.ini ] ; then
			cp /usr/local/etc/php.ini-production /usr/local/etc/php.ini
		fi
		PATH_PHP_INI_APACHE=/usr/local/etc/php.ini
	# This one for RedHat and Centos, and osx !
	elif [ -f /etc/php.ini -o -f /etc/php.ini.default ] ; then
		if [ ! -f /etc/php.ini ] ; then
			cp /etc/php.ini.default /etc/php.ini
		fi
		PATH_PHP_INI_APACHE=/etc/php.ini
	# This one for Gentoo
	elif [ -f /etc/php/apache2-php5/php.ini ] ; then
		PATH_PHP_INI_APACHE=/etc/php/apache2-php5/php.ini
	elif [ ""$conf_apache_version = "2" ] ; then
		if [ ""${PHPMAJOR} -lt 5 ] ; then
			if [ -f /etc/php4/apache2/php.ini ] ; then
				PATH_PHP_INI_APACHE=/etc/php4/apache2/php.ini
			else
				echo "Problem in your setup. You asked to setup apache2, the PHP cli version is 4 but there is no /etc/php4/apache2/php.ini";
				exit 1
			fi
		else
			if [ -f /etc/php5/apache2/php.ini ] ; then
				PATH_PHP_INI_APACHE=/etc/php5/apache2/php.ini
			else
				echo "Problem in your setup. You asked to setup apache2, the PHP cli version is 5 but there is no /etc/php5/apache2/php.ini";
				exit 1
			fi
		fi
	elif [ ""${PHPMAJOR} -lt 5 ] ; then
		if [ -f /etc/php4/apache/php.ini ] ; then
			PATH_PHP_INI_APACHE=/etc/php4/apache/php.ini
		else
			echo "Problem in your setup. You asked to setup apache 1.3, the PHP cli version is 4 but there is no /etc/php4/apache/php.ini";
			exit 1
		fi
	else
		if [ -f /etc/php5/apache/php.ini ] ; then
			PATH_PHP_INI_APACHE=/etc/php5/apache/php.ini
		else
			echo "Problem in your setup. You asked to setup apache 1.3, the PHP cli version is 5 but there is no /etc/php5/apache/php.ini";
			exit 1
		fi
	fi
}

searchPATH_SUDO () {
	echoIfVerbose "-> Searching for sudo path"
	# if we have a sudo binary around, then use it to create our chroot shell
	# check for some path defaults... 
	if [ -z "$PATH_SUDO" ] ; then
		PATH_SUDO=`which sudo`
		fi
	if [ -z "$PATH_CHROOT" ] ; then
		PATH_CHROOT=`which chrootuid`
	fi
	if [ -z "$PATH_SHELLS_CONF" ] ; then
		PATH_SHELLS_CONF=/etc/shells
	fi
	if [ -z "$PATH_SUDOERS_CONF" ] ; then
		PATH_SUDOERS_CONF=/etc/sudoers
	fi
}

# Try to restart a daemon using multiple techniques in order to have
# it working under many flavors of Unix
# @params: $1 name of the daemon to restart
restartDaemonMultiUnix () {
        if [ -x "/etc/init.d/${1}" ] ; then
        	# This one is the debian way
        	if [ -x /usr/sbin/invoke-rc.d ] ; then
        		/usr/sbin/invoke-rc.d ${1} restart
        	else
        		# Most unix will work this way
        		if [ -x "/etc/init.d/${1}" ] ; then
        			/etc/init.d/${1} restart
        		fi
        	fi
        else
        	# BSD like /usr/local
		if [ -x /usr/local/etc/rc.d/${1} ] ; then
			/usr/local/etc/rc.d/${1} restart
		# Most unix
       		elif [ -x "/etc/rc.d/${1}" ] ; then
			# Redhat / FC systems
			if [ -x /sbin/service ] ; then
				/sbin/service ${1} restart
			else
	       			/etc/rc.d/${1} restart
			fi
		# Slackware like
       		elif [ -x "/etc/rc.d/rc.${1}" ] ; then
       			/etc/rc.d/rc.${1} restart
       		fi
       	fi
}

# This part is debian specific because of a confirmed debian bug in sarge with php4-mysql
# leak in distribution. Whis is that not made by default ?
# Adding support for mysql for phpX-cgi
modifyPHP_INI_EXTENSIONS () {
	# Unactived in new debian (eg newer than sarge)
	if [ "$DEBIAN_VERSION" = "3.1" ] ; then
		echoIfVerbose "===> Modifying php.ini extensions"
		# The following is a code for sarge. Will be removed when Etch is out, not before.
		if [ -f ${PATH_PHP_INI_CLI} ] ; then
			if grep mysql.so ${PATH_PHP_INI_CLI} | grep extension= >/dev/null
			then
				echo -n ""
			else
				echo "extension=mysql.so" >>${PATH_PHP_INI_CLI}
			fi
		fi

		if [ -f /etc/php4/apache/php.ini ] ; then
			if grep mysql.so /etc/php4/apache/php.ini | grep extension= >/dev/null
			then
				echo -n ""
			else
				echo "extension=mysql.so" >>/etc/php4/cli/php.ini
			fi
		fi

		if [ -f /etc/php5/apache/php.ini ] ; then
			if grep mysql.so /etc/php5/apache/php.ini | grep extension= >/dev/null
			then
				echo -n ""
			else
				echo "extension=mysql.so" >>/etc/php5/cli/php.ini
			fi
		fi
	fi
}

changeMySQLPassword () {
	# Changing root password of mysql
	if [ "$conf_mysql_change_root" = "true" ] ; then
		echo "===> Changing MySQL root password"
	        echo "MySQL will now prompt your for the password to connect to"
	        echo "the database. This is the OLD password that was there before"
	        echo "you launched this script. If you didn't setup a root pass for"
	        echo "mysqld, just hit ENTER to use empty pass."
		mysql -u$conf_mysql_login -p -h$conf_mysql_host -Dmysql --execute="UPDATE user SET Password=PASSWORD('"$conf_mysql_pass"') WHERE User='root'; FLUSH PRIVILEGES;"
	fi
}

modifyResolvConf () {
	echoIfVerbose "===> Checking \"nameserver 127.0.0.1\" in /etc/resolv.conf"
	if grep "nameserver 127.0.0.1" /etc/resolv.conf >/dev/null
	then
		echoIfVerbose "/etc/resolv.conf seems to be OK !"
	else
		echoIfVerbose "Adding nameserver 127.0.0.1 to /etc/resolv.conf"
		TMP_FILE=`${MKTEMP} DTC_resolv.conf.XXXXXX` || exit 1
		if [ ! -f /etc/resolv.conf.DTC.Backup ]
		then
			echoIfVerbose "Backing up /etc/resolv.conf"
			cp /etc/resolv.conf /etc/resolv.conf.DTC.Backup
		fi
		if grep "search" /etc/resolv.conf >/dev/null ; then
			grep "search" /etc/resolv.conf > $TMP_FILE
		fi
		echo "nameserver 127.0.0.1" >> $TMP_FILE
		if grep "nameserver" /etc/resolv.conf ; then
			grep "nameserver" /etc/resolv.conf >> $TMP_FILE
		fi
		cat < $TMP_FILE >/etc/resolv.conf
		rm $TMP_FILE
	fi
}

chownSquirrelAndFastcgiToDtcUserAndGroup () {
	echoIfVerbose "===> Chgrp /var/lib/squirrelmail/data/ /var/spool/squirrelmail/attach and /var/lib/apache2/fastcgi"
	# Search for Squirrelmail folder to change it's GID so it works directly
	if [ -e /var/lib/squirrelmail/data/ ] ; then
		chgrp ${CONF_DTC_SYSTEM_GROUPNAME} /var/lib/squirrelmail/data/
	fi

	if [ -e /var/spool/squirrelmail/attach ] ; then
		chgrp ${CONF_DTC_SYSTEM_GROUPNAME} /var/spool/squirrelmail/attach
	fi

	if [ -e /var/lib/apache2/fastcgi ] ; then
		chown -R ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} /var/lib/apache2/fastcgi
	fi
	if [ -f /etc/phpmyadmin/blowfish_secret.inc.php ] ; then
		chgrp ${CONF_DTC_SYSTEM_GROUPNAME} /etc/phpmyadmin/blowfish_secret.inc.php
	fi
	if [ -f /var/lib/phpmyadmin/blowfish_secret.inc.php ] ; then
		chgrp ${CONF_DTC_SYSTEM_GROUPNAME} /var/lib/phpmyadmin/blowfish_secret.inc.php
	fi
	if [ -f /etc/phpmyadmin/htpasswd.setup ] ; then
		chgrp ${CONF_DTC_SYSTEM_GROUPNAME} /etc/phpmyadmin/htpasswd.setup
	fi

	if [ "${UNIX_TYPE}" = "redhat" -a -f /usr/share/phpmyadmin/config.inc.php ] ; then
		chgrp ${CONF_DTC_SYSTEM_GROUPNAME} /usr/share/phpmyadmin/config.inc.php
		gen_pass=`dd if=/dev/random bs=64 count=1 2>|/dev/null | md5sum | cut -d' ' -f1 | awk '{print substr($0,0,16)}'`
		sed -i "s/cfg\['blowfish_secret'\] = ''/cfg\['blowfish_secret'\] = '${gen_pass}'/" /usr/share/phpmyadmin/config.inc.php
		if [ -e /etc/httpd/conf.d/phpmyadmin.conf ] ; then
			sed -i "s/Allow from 127.0.0.1/Allow from all/" /etc/httpd/conf.d/phpmyadmin.conf
		fi
	fi

	if [ "${UNIX_TYPE}" = "freebsd" -a -f /usr/local/www/phpMyAdmin/config.inc.php ] ; then
		chgrp ${CONF_DTC_SYSTEM_GROUPNAME} /usr/local/www/phpMyAdmin/config.inc.php
	fi

	# Mailgraph stuffs...
	if [ -d /var/lib/mailgraph ] ; then
		chown ${CONF_DTC_SYSTEM_USERNAME} /var/lib/mailgraph
	fi
	if [ -f /var/lib/mailgraph/mailgraph.rrd ] ; then
		chown ${CONF_DTC_SYSTEM_USERNAME} /var/lib/mailgraph/mailgraph.rrd
	fi
	if [ -f /var/lib/mailgraph/mailgraph_virus.rrd ] ; then
		chown ${CONF_DTC_SYSTEM_USERNAME} /var/lib/mailgraph/mailgraph_virus.rrd
	fi
	# Roundcube
	if [ -d /var/log/roundcube ] ; then
		chown ${CONF_DTC_SYSTEM_USERNAME} /var/log/roundcube
	fi
	if [ -f /etc/roundcube/debian-db.php ] ; then
		chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} /etc/roundcube/debian-db.php
	fi
	if [ -f /etc/roundcube/main.inc.php ] ; then
		chgrp ${CONF_DTC_SYSTEM_GROUPNAME} /etc/roundcube/main.inc.php
	fi
	if [ -d /var/lib/dbconfig-common/sqlite/roundcube ] ; then
		chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} /var/lib/dbconfig-common/sqlite/roundcube
	fi
	if [ -f /var/lib/dbconfig-common/sqlite/roundcube/roundcube ] ; then
		chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} /var/lib/dbconfig-common/sqlite/roundcube/roundcube
	fi
	# PHP sessions for CentOS
	if [ -e /var/lib/php/session ] ; then
		chown -R ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} /var/lib/php/session
	fi

	# Fixes for CentOS (and maybe others)
#	if [ "$UNIX_TYPE" = "redhat" ] ; then
		if [ -e /etc/squirrelmail/config.php ] ; then
			chown ${CONF_DTC_SYSTEM_USERNAME} /etc/squirrelmail/config.php 
		fi
		if [ -e /etc/squirrelmail/default_pref ] ; then
			chown ${CONF_DTC_SYSTEM_USERNAME} /etc/squirrelmail/default_pref
		fi
		if [ -e /etc/squirrelmail/sqspell_config.php ] ; then
			# ${CONF_DTC_SYSTEM_USERNAME} was missing, added it *steveetm*
			chown ${CONF_DTC_SYSTEM_USERNAME} /etc/squirrelmail/sqspell_config.php
		fi
#	fi
	if [ -e /var/spool/squirrelmail/attach ] ; then
		chown ${CONF_DTC_SYSTEM_USERNAME} /var/spool/squirrelmail/attach
	fi
	if [ -e /var/lib/squirrelmail/prefs ] ; then
		chown ${CONF_DTC_SYSTEM_USERNAME} /var/lib/squirrelmail/prefs
	fi
}

# Do a search and replace in a file using sh
# Params:
# $1 - File where to search
# $2 - String to search
# $3 - String to replace
# $4 - MKTEMP binary and params
searchAndReplace () {
	if ! grep ${2} ${1} >/dev/null 2>&1 ; then
		TMP_FILE=`${MKTEMP} DTC_SAR_TEMP.XXXXXX` || exit 1
		sed "s/${2}/${3}/" ${1} >${TMP_FILE}
		cat ${TMP_FILE} >${1}
		rm ${TMP_FILE}
	fi
}

# Setup a specific Debian local
# $1 en_US
debianSetLocale (){
	echo -n "$1.UTF-8 "
	# Set the correct entry in /etc/locale.gen
	# only if the file exists (because it doesn't exist in Ubuntu, it seems)
	if [ -f /etc/locale.gen ] ; then
		TMP_FILE=`${MKTEMP} DTC_SET_LOCALE.XXXXXX` || exit 1
		grep -v "$1.UTF-8" /etc/locale.gen >${TMP_FILE}
		cat <${TMP_FILE} >/etc/locale.gen
		rm ${TMP_FILE}
		echo "$1.UTF-8 UTF-8" >>/etc/locale.gen
	fi
	# Ask for generation of the added locale
	localedef -i $1 -c -f UTF-8 -A /usr/share/locale/locale.alias $1.UTF-8
}

dtcGenDebianLocales () {
	if [ "$UNIX_TYPE" = "debian" ] ; then
		echo -n "Generating DTC's locale, this will take a while: "
		debianSetLocale en_US
		debianSetLocale fr_FR
		debianSetLocale it_IT
		debianSetLocale hu_HU
		debianSetLocale de_DE
		debianSetLocale ru_RU
		debianSetLocale nl_NL
		debianSetLocale zh_CN
		debianSetLocale zh_TW
		debianSetLocale pl_PL
		debianSetLocale sv_SE
		debianSetLocale sr_RS
		debianSetLocale pt_PT
		debianSetLocale pt_BR
		debianSetLocale es_ES
		debianSetLocale fi_FI
		debianSetLocale lv_LV
		debianSetLocale es_ES
		echo "done!"
	fi
}

# Patch a file using a patch file and checkings with 2 md5
# Params:
# $1 - Full path of the file to patch
# $2 - Path to the patch file (has to be a -P0 patch file)
# $3 - md5 of the original file
# $4 - md5 of the patched file
dtcPatchFile () {
	if [ -x /sbin/md5 ] ; then
		MD5="md5 -r"
	else
		MD5="md5sum"
	fi
	if [ -e ${1} ] ; then
		DEST_MD5_VAL=`${MD5} ${1} | cut -d" " -f1`
		# If it's the original file, patch it
		if [ "${DEST_MD5_VAL}" = "${3}" ] ; then
			cp ${1} ${1}.DTC.BEFORE-PATCH-BACKUP
			echo "Applying patch to ${1}"
			patch ${1} -p0 <${2}
		else
			# If the file is already patched, don't do anything
			if [ "${DEST_MD5_VAL}" = ${4} ] ; then
				echo "File ${1} already patched."
			# Else there's a problem!
			else
				echo "File ${1} doesn't patch any MD5 we have in: please patch manually using ${2} file."
			fi
		fi
	else
		echo "Can't find ${1}, did you install it?"
	fi
}

dtcUnpatchFile () {
	if [ -x /sbin/md5 ] ; then
		MD5="md5 -r"
	else
		MD5="md5sum"
	fi
	if [ -e ${1} ] ; then
		DEST_MD5_VAL=`${MD5} ${1} | cut -d" " -f1`
		# If we have the original file, don't do anything
		if [ "${DEST_MD5_VAL}" = "${3}" ] ; then
			echo "File ${1} was not patched, no need to unpatch."
		else
			# If it's the patched file, unpatch using our backup (check the backup first...)
			if [ "${DEST_MD5_VAL}" = "${4}" ] ; then
				BACKUP_MD5_VAL=`${MD5} ${1}.DTC.BEFORE-PATCH-BACKUP | cut -d" " -f1`
				# If backup is original, let's use it as replacement !
				if [ "${BACKUP_MD5_VAL}" = "${3}" ] ; then
					cp ${1}.DTC.BEFORE-PATCH-BACKUP ${1}
					echo "Reverted patch for ${1}"
				# We have a problem, the backup file doesn't match our md5!
				else
					echo "Can't reverse patch for ${1}, please do manually!"
				fi
			# We have a problem, we can't reverse, as the original file has been edited!
			else
				echo "Can't reverse patch for ${1}, please do manually!"
			fi
		fi
	else
		echo "Can't find ${1}, did you install it?"
	fi
}


searchMYSQL_DB_SOCKET_PATH () {
	echoIfVerbose "-> Searching for mysql.sock"
	if [ -z ""$MYSQL_DB_SOCKET_PATH ] ; then
		if [ "$UNIX_TYPE" = "freebsd" -o "$UNIX_TYPE" = "osx" ] ; then
			MYSQL_DB_SOCKET_PATH="/tmp/mysql.sock"
		else
			MYSQL_DB_SOCKET_PATH="/var/run/mysqld/mysqld.sock"
		fi
	fi
}

# Param:
#      $1 = subdomain to create
createSubdomainDirAndFiles () {
	# Copy newly created chroot tree to the 3 vhosts created with this installer (mx and ns don't have apache vhosts generated)
	echoIfVerbose "===> Installing chroot file environment for "$1"."$main_domain_name
	TMP_PATH=$conf_hosting_path"/"$conf_adm_login"/"$main_domain_name"/subdomains/"$1
	for i in html logs cgi-bin ; do
		mkdir -p $TMP_PATH"/"${i}
		chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $TMP_PATH"/"${i}
	done
	chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $TMP_PATH
	# As this sometimes fails (rarely) when files exists, we happen a || true
	# as this is not 100% needed when files are already there...
	if [ "$UNIX_TYPE" = "freebsd" -o "$UNIX_TYPE" = "osx" ] ; then
		cp -fpR  $conf_chroot_path/* $TMP_PATH"/" || true
	else
		cp -fupR  $conf_chroot_path/* $TMP_PATH"/" || true
	fi
	for i in $LIST_CHROOT_DIRS etc ; do
		if [ -e $TMP_PATH"/"${i} ] ; then
			chown -R ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $TMP_PATH"/"${i}
		fi
	done
}

createHostingDirAndFiles () {
	# Create hosting directories for main site
	echoIfVerbose "===> Creating directory for hosting "$main_domain_name
	DOMAIN_FOLDER=$conf_hosting_path"/"$conf_adm_login"/"$main_domain_name
	for i in Mailboxs mysql subdomains ; do
		mkdir -p $DOMAIN_FOLDER"/"${i}
	done
	for i in $conf_hosting_path $conf_hosting_path"/"$conf_adm_login $DOMAIN_FOLDER $DOMAIN_FOLDER"/Mailboxs" $DOMAIN_FOLDER"/mysql" $DOMAIN_FOLDER"/subdomains" ; do
		chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} ${i}
	done
	for i in $dtc_admin_subdomain www 404 ; do
		createSubdomainDirAndFiles ${i}
	done
	ADMIN_HOME=$DOMAIN_FOLDER"/subdomains/"$dtc_admin_subdomain"/html"
	if ! [ -e "$ADMIN_HOME"/index.php -o -e "$ADMIN_HOME"/index.html -o -e "$ADMIN_HOME"/index.htm ] ; then
		cp $PATH_DTC_SHARED"/shared/default_admin_site.php" $ADMIN_HOME"/index.php"
		chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $ADMIN_HOME"/index.php"
		if ! [ -f $ADMIN_HOME"/dtclogo.png" ] ; then
			cp $PATH_DTC_SHARED"/shared/template/dtclogo.png" $ADMIN_HOME
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $ADMIN_HOME"/dtclogo.png"
		fi
		if ! [ -f $ADMIN_HOME"/favicon.ico" ] ; then
			cp $PATH_DTC_SHARED"/shared/template/favicon.ico" $ADMIN_HOME
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $ADMIN_HOME"/favicon.ico"
		fi
	fi
	# Copy a template site to the new main site
	MAINSITE_HOME=$DOMAIN_FOLDER"/subdomains/www/html"
	if ! [ -e $MAINSITE_HOME/index.php -o -e $MAINSITE_HOME/index.html -o -e $MAINSITE_HOME/index.htm ] ; then
		cp $PATH_DTC_SHARED"/shared/template/index.php" $MAINSITE_HOME
		chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $MAINSITE_HOME/index.php
		if ! [ -e $MAINSITE_HOME"/dtc_logo.gif" ] ; then
			cp $PATH_DTC_SHARED"/shared/template/dtclogo.png" $MAINSITE_HOME
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $MAINSITE_HOME/dtclogo.png
		fi
	fi

	# symlink directories so that users can login with ssh to the admin account directory
	for i in $LIST_CHROOT_DIRS ; do
		if [ ! -e $conf_hosting_path/$conf_adm_login/${i} ] ; then
			ln -s $main_domain_name/subdomains/www/${i} $conf_hosting_path/$conf_adm_login/${i}
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $conf_hosting_path/$conf_adm_login/${i}
		fi
	done
	# need this for freebsd: KC
	if [ ! -e $conf_hosting_path/$conf_adm_login/libexec ] ; then
		ln -s $main_domain_name/subdomains/www/libexec $conf_hosting_path/$conf_adm_login/libexec
		chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $conf_hosting_path/$conf_adm_login/libexec
	fi

	# also, so the user can login to the main domain names base directory
	for i in $LIST_CHROOT_DIRS ; do
		if [ ! -e $conf_hosting_path/$conf_adm_login/$main_domain_name/${i} ] ; then
			ln -s subdomains/www/${i} $conf_hosting_path/$conf_adm_login/$main_domain_name/${i}
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $conf_hosting_path/$conf_adm_login/$main_domain_name/${i}
		fi
	done

	# need for freebsd: KC
	if [ ! -e $conf_hosting_path/$conf_adm_login/$main_domain_name/libexec ] ; then
		ln -s subdomains/www/libexec  $conf_hosting_path/$conf_adm_login/$main_domain_name/libexec
		chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $conf_hosting_path/$conf_adm_login/$main_domain_name/libexec
	fi

	# copy the 404 index.php file if none is found.
	the_404_path="$conf_hosting_path/$conf_adm_login/$main_domain_name/subdomains/404/html"
	if ! [ -e $the_404_path/index.html -o -e $the_404_path/index.php -o -e $the_404_path/index.htm ] ; then
		if [ -e $PATH_DTC_SHARED/shared/404_template/index.php ] ; then
			cp $PATH_DTC_SHARED/shared/404_template/index.php $the_404_path
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $the_404_path/index.php
		fi
	fi
	# Copy the 404 logo file
	if ! [ -e $conf_hosting_path/$conf_adm_login/$main_domain_name/subdomains/404/html/logo.png ] ; then
		if [ -e $PATH_DTC_SHARED/shared/404_template/logo.png ] ; then
			cp $PATH_DTC_SHARED/shared/404_template/logo.png $the_404_path
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $the_404_path/logo.png
		fi
	fi

	# copy the Error 404 document
	if ! [ -e $the_404_path/404.php ] ; then
		if [ -e $PATH_DTC_SHARED/shared/404_template/404.php ] ; then 
			cp $PATH_DTC_SHARED/shared/404_template/404.php $the_404_path
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $the_404_path/404.php
		fi
	fi

	# copy the expired.php to the destination folder
	if ! [ -e $PATH_DTC_ETC/expired_site ] ; then
		mkdir -p $PATH_DTC_ETC/expired_site
	fi
	if ! [ -e $PATH_DTC_ETC/expired_site/index.* ] ; then
		cp $PATH_DTC_SHARED/shared/404_template/expired.php $PATH_DTC_ETC/expired_site/index.php
	fi
	if ! [ -e $PATH_DTC_ETC"/expired_site/logo.png" ] ; then
		cp $PATH_DTC_SHARED/shared/404_template/logo.png $PATH_DTC_ETC"/expired_site/"
	fi

	# also copy it to the dtc404 and 406 directory
	if ! [ -e $PATH_DTC_ETC/dtc404/404.php ] ; then
		mkdir -p $PATH_DTC_ETC/dtc404/
		cp $PATH_DTC_SHARED/shared/404_template/404.php $PATH_DTC_ETC"/dtc404/"
		cp $PATH_DTC_SHARED/shared/404_template/406.php $PATH_DTC_ETC"/dtc404/"
	fi
	if ! [ -e $PATH_DTC_ETC"/dtc404/logo.png" ] ; then
		cp $PATH_DTC_SHARED/shared/404_template/logo.png $PATH_DTC_ETC"/dtc404/"
	fi

	# copy the dtc_stats_index.php
	if ! [ -e $PATH_DTC_ETC/dtc_stats_index.php ] ; then
		cp $PATH_DTC_SHARED/shared/dtc_stats_index.php $PATH_DTC_ETC/dtc_stats_index.php
	fi

	# Repair the original 404 page from old versions against XSS attack
	if [ "$UNIX_TYPE" = "freebsd" ] ; then
		dtc404md5sum=`md5 $PATH_DTC_ETC/dtc404/404.php|cut -d " " -f4`
	else
		dtc404md5sum=`md5sum $PATH_DTC_ETC/dtc404/404.php|cut -d " " -f1`
	fi
	dtcOrigianMD5sum="14285fd356b0bfdef4cfd7579da161c0"
	if [ $dtcOrigianMD5sum = $dtc404md5sum ] ; then
		cp $PATH_DTC_SHARED/shared/404_template/404.php $PATH_DTC_ETC/dtc404/
	fi

	# copy the template directory from shared to etc, so we can edit it without worry of being purged on each install
	# only copy the directory, if it doesn't already exist in the etc path
	if [ -e "$PATH_DTC_SHARED/shared/template" ] ; then
		if [ ! -e "$PATH_DTC_ETC/template" ] ; then
			cp -r $PATH_DTC_SHARED/shared/template $PATH_DTC_ETC
		fi
		chown -R ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $PATH_DTC_ETC/template
		chmod -R 775 $PATH_DTC_ETC/template
	fi

	chown -R ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} ${PATH_DTC_ETC}

#	echoIfVerbose "chown -R ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $conf_hosting_path"
#	chown -R ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $conf_hosting_path || true

}

setDtcdbPassword () {
	echoIfVerbose "-> Setting up dtcdaemons password"
	# Add a dtc user to the mysql db, generate a password randomly if no password is there already
	# Using a file to remember password...
	if [ "$UNIX_TYPE" = "freebsd" -o "$UNIX_TYPE" = "osx" ] ; then
                TMP_FILE=`${MKTEMP} ""`
                gen_pass=`echo $TMP_FILE | cut -d'.' -f2`
                rm -f ${TMP_FILE}
                TMP_FILE=`${MKTEMP} ""`
                gen_pass=${gen_pass}`echo $TMP_FILE | cut -d'.' -f2`
                rm -f ${TMP_FILE}
	else
		# This new one works as well with sh!
		gen_pass=`dd if=/dev/random bs=64 count=1 2>|/dev/null | md5sum | cut -d' ' -f1 | awk '{print substr($0,0,16)}'`
#		gen_pass=${RANDOM}${RANDOM}
	fi
	PATH_DB_PWD_FILE=${PATH_DTC_ETC}/dtcdb_passwd
	if ! [ -e ""${PATH_DB_PWD_FILE} ] ; then
		MYSQL_DTCDAEMONS_PASS=`echo ${gen_pass}`
		echo ${MYSQL_DTCDAEMONS_PASS} >${PATH_DB_PWD_FILE}
	else
		MYSQL_DTCDAEMONS_PASS=`cat <${PATH_DB_PWD_FILE}`
	fi
	if [ -z "${MYSQL_DTCDAEMONS_PASS}" ] ; then
		MYSQL_DTCDAEMONS_PASS=${gen_pass}
		echo ${MYSQL_DTCDAEMONS_PASS} >${PATH_DB_PWD_FILE}
	fi

	chmod 600 ${PATH_DB_PWD_FILE}
}

setupDTCDatabase () {
	echoIfVerbose "===> DTC is now creating its database:"

	if [ ""$conf_mysql_cli_path = "" ] ; then
		echoIfVerbose "->mysql_cli_path is not set"
		conf_mysql_cli_path="mysql";
	fi
	if [ ""$conf_mysqlshow_cli_path = "" ] ; then
		echoIfVerbose "mysqlshow_cli_path is not set"
		conf_mysqlshow_cli_path="mysqlshow";
	fi
	if [ "$conf_mysql_pass" = "" ] ; then
		echoIfVerbose "Setting up mysql cli "$conf_mysql_cli_path" without password"
	        MYSQL=""$conf_mysql_cli_path
		MYSQLSHOW=$conf_mysqlshow_cli_path
	else
		echoIfVerbose "Setting up mysql cli with password"
		MYSQL=$conf_mysql_cli_path" -p${conf_mysql_pass}"
		MYSQLSHOW=$conf_mysqlshow_cli_path" -p${conf_mysql_pass}"
	fi

	# fix the group id for nobody group
	sed -i -e "s/CONF_DTC_SYSTEM_UID/${CONF_DTC_SYSTEM_UID}/" ${PATH_DTC_SHARED}/admin/dtc_db.php
	sed -i -e "s/CONF_DTC_SYSTEM_GID/${CONF_DTC_SYSTEM_GID}/" ${PATH_DTC_SHARED}/admin/dtc_db.php

	curdir=`pwd`

	if [ -f "/etc/debian_version" -a "${conf_mysqlautoconfig}" = "true" ] ; then
		mysql --defaults-file=/etc/mysql/debian.cnf -h${conf_mysql_host} -Dmysql --execute="INSERT IGNORE INTO user (Host,User,Password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,Create_tmp_table_priv,Lock_tables_priv,Execute_priv,Repl_slave_priv,Repl_client_priv,Create_view_priv,Show_view_priv,Create_routine_priv,Alter_routine_priv,Create_user_priv) VALUES ('localhost','${conf_mysql_login}',PASSWORD('${conf_mysql_pass}'),'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y')"
		mysql --defaults-file=/etc/mysql/debian.cnf -h${conf_mysql_host} -Dmysql --execute="INSERT IGNORE INTO user (Host,User,Password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,Create_tmp_table_priv,Lock_tables_priv,Execute_priv,Repl_slave_priv,Repl_client_priv,Create_view_priv,Show_view_priv,Create_routine_priv,Alter_routine_priv,Create_user_priv) VALUES ('%','${conf_mysql_login}',PASSWORD('${conf_mysql_pass}'),'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y')"
		mysql --defaults-file=/etc/mysql/debian.cnf -h${conf_mysql_host} -Dmysql --execute="UPDATE user SET Password=PASSWORD('${conf_mysql_pass}'),Select_priv='Y',Insert_priv='Y',Update_priv='Y',Delete_priv='Y',Create_priv='Y',Drop_priv='Y',Reload_priv='Y',Shutdown_priv='Y',Process_priv='Y',File_priv='Y',Grant_priv='Y',References_priv='Y',Index_priv='Y',Alter_priv='Y',Show_db_priv='Y',Super_priv='Y',Create_tmp_table_priv='Y',Lock_tables_priv='Y',Execute_priv='Y',Repl_slave_priv='Y',Repl_client_priv='Y',Create_view_priv='Y',Show_view_priv='Y',Create_routine_priv='Y',Alter_routine_priv='Y',Create_user_priv='Y' WHERE Host='%' AND User='${conf_mysql_login}'"
		mysql --defaults-file=/etc/mysql/debian.cnf -h${conf_mysql_host} -Dmysql --execute="UPDATE user SET Password=PASSWORD('${conf_mysql_pass}'),Select_priv='Y',Insert_priv='Y',Update_priv='Y',Delete_priv='Y',Create_priv='Y',Drop_priv='Y',Reload_priv='Y',Shutdown_priv='Y',Process_priv='Y',File_priv='Y',Grant_priv='Y',References_priv='Y',Index_priv='Y',Alter_priv='Y',Show_db_priv='Y',Super_priv='Y',Create_tmp_table_priv='Y',Lock_tables_priv='Y',Execute_priv='Y',Repl_slave_priv='Y',Repl_client_priv='Y',Create_view_priv='Y',Show_view_priv='Y',Create_routine_priv='Y',Alter_routine_priv='Y',Create_user_priv='Y' WHERE Host='localhost' AND User='${conf_mysql_login}'"
		mysql --defaults-file=/etc/mysql/debian.cnf -h${conf_mysql_host} -Dmysql --execute="FLUSH PRIVILEGES"
	fi

	echoIfVerbose "-> Creating db if not exists: ${conf_mysql_db}"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host --execute="CREATE DATABASE IF NOT EXISTS "${conf_mysql_db}

	echoIfVerbose "-> Checking version of mysql installed..."
	# mysql  Ver 14.7 Distrib 4.1.20, for pc-linux-gnu (i386) using readline 5.1
	MYSQL_VERSION=`mysql -V`
	MYSQL_VER=30
	case $MYSQL_VERSION in
		*Distrib\ 3.*)
			echoIfVerbose "Found version 3.x ..."
			MYSQL_VER=30
			;;
		*Distrib\ 4.0*)
			echoIfVerbose "Found version 4.0.x ..."
			MYSQL_VER=40
			;;
		*Distrib\ 4.1*)
			echoIfVerbose "Found version 4.1.x ..."
			MYSQL_VER=41
			;;
		*Distrib\ 5.*)
			echoIfVerbose "Found version 5.x ..."
			MYSQL_VER=50
			;;
	esac

	if [ ""$MYSQL_VER -gt 40 ] ; then
		echoIfVerbose "Modifying DTC db character set to latin1..."
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host --execute="ALTER DATABASE \`$conf_mysql_db\` DEFAULT CHARACTER SET latin1 COLLATE latin1_bin;"
	fi

	echoIfVerbose "Creating apachelogs db"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host --execute="CREATE DATABASE IF NOT EXISTS apachelogs"
	if [ ""$MYSQL_VER -gt 40 ] ; then
			$MYSQL -u$conf_mysql_login -h$conf_mysql_host --execute="ALTER DATABASE apachelogs DEFAULT CHARACTER SET latin1 COLLATE latin1_bin;"
	fi

	#echo $PATH_PHP_CGI $PATH_DTC_ADMIN/restor_db.php -u $conf_mysql_login -h $conf_mysql_host -d $conf_mysql_db $conf_mysql_pass
	if [ ""$VERBOSE_INSTALL = "yes" ] ; then
		cd $PATH_DTC_ADMIN; $PATH_PHP_CGI $PATH_DTC_ADMIN/restor_db.php -u $conf_mysql_login -h $conf_mysql_host -d $conf_mysql_db "$conf_mysql_pass"
	else
		cd $PATH_DTC_ADMIN; $PATH_PHP_CGI $PATH_DTC_ADMIN/restor_db.php -u $conf_mysql_login -h $conf_mysql_host -d $conf_mysql_db "$conf_mysql_pass" >/dev/null
	fi

	# fix some tables for 4.1
	if [ ""$MYSQL_VER -gt 40 ] ; then
			$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="ALTER TABLE fetchmail DEFAULT CHARACTER SET latin1 COLLATE latin1_bin;"
	fi

	cd $curdir
	echoIfVerbose "===> Inserting values in MySQL for hosting "$main_domain_name
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO groups (members) VALUES ('zigo')"
	if [ "${conf_enforce_adm_encryption}" = "true" ] ; then
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO admin (adm_login,adm_pass,path) VALUES ('"$conf_adm_login"',SHA1('"$conf_adm_pass"'),'"$conf_hosting_path"/"$conf_adm_login"')"
	else
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO admin (adm_login,adm_pass,path) VALUES ('"$conf_adm_login"','"$conf_adm_pass"','"$conf_hosting_path"/"$conf_adm_login"')"
	fi
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO admin (adm_login,adm_pass,path) VALUES ('"$conf_adm_login"','"$conf_adm_pass"','"$conf_hosting_path"/"$conf_adm_login"')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO domain (name,owner,default_subdomain,generate_flag,ip_addr) VALUES ('"$main_domain_name"','"$conf_adm_login"','www','yes','"$conf_ip_addr"')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO subdomain (domain_name,subdomain_name,path) VALUES ('"$main_domain_name"','www','www')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO subdomain (domain_name,subdomain_name,path) VALUES ('"$main_domain_name"','404','404')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO subdomain(domain_name,subdomain_name,ip) VALUES ('"$main_domain_name"','ns1','$conf_ip_addr')"
	# If mx == subdomain for the panel, then we still want to create a vhost for that entry
	# so we can't set the IP for the MX (which would avoid generating the vhost, and then
	# make the panel URL not working)
	if [ "${MX_MAIL}" = "$dtc_admin_subdomain" ] ; then
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO subdomain (domain_name,subdomain_name) VALUES ('"$main_domain_name"','"${MX_MAIL}"')"
	else
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO subdomain (domain_name,subdomain_name,ip) VALUES ('"$main_domain_name"','"${MX_MAIL}"','default')"
	fi
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO subdomain (domain_name,subdomain_name,path) VALUES ('"$main_domain_name"','"$dtc_admin_subdomain"','www')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO config (unicrow,demo_version,main_site_ip,site_addrs,addr_mail_server,webmaster_email_addr,addr_primary_dns,administrative_site,site_root_host_path,generated_file_path,dtcshared_path,dtcadmin_path,dtcclient_path,mta_type,main_domain,404_subdomain) VALUES('1','no','"$conf_ip_addr"','"$conf_ip_addr"','"${MX_MAIL}"."$main_domain_name"','webmaster@"$main_domain_name"','ns1."$main_domain_name"','"$dtc_admin_subdomain"."$main_domain_name"','"$conf_hosting_path"','"$PATH_DTC_ETC"','"$PATH_DTC_SHARED"','"$PATH_DTC_ADMIN"','"$PATH_DTC_CLIENT"','"$conf_mta_type"','"$main_domain_name"','404')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO cron_job (unicrow,reload_named,restart_apache,gen_vhosts,gen_named) VALUES ('1','yes','yes','yes','yes')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO secpayconf (unicrow,use_paypal,paypal_rate,paypal_flat,paypal_autovalidate,paypal_email) VALUES ('1','yes','3.21','0.50','no','webmaster@"$main_domain_name"')"

	# Regenerate the "main" domain on each installs...
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE domain SET generate_flag='yes' WHERE name='"$main_domain_name"'"

	# This one is in case of reinstalltion, so the installer has prority to old values
	if [ ""$conf_use_cyrus  = "true" ] ; then
		use_cyrus=yes
	else
		use_cyrus=no
	fi
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET main_site_ip='"$conf_ip_addr"',administrative_site='"$dtc_admin_subdomain"."$main_domain_name"',site_root_host_path='"$conf_hosting_path"',generated_file_path='"$PATH_DTC_ETC"',mta_type='"$conf_mta_type"',main_domain='"$main_domain_name"',404_subdomain='404',apache_version='"$conf_apache_version"',use_cyrus='"$use_cyrus"',chroot_path='$conf_chroot_path' WHERE 1"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET php_library_path='/usr/lib/php:/tmp:/usr/share/pear:$PATH_DTC_ETC/dtc404:/usr/share/php', dtc_system_uid='$CONF_DTC_SYSTEM_UID', dtc_system_username='$CONF_DTC_SYSTEM_USERNAME', dtc_system_gid='$CONF_DTC_SYSTEM_GID',dtc_system_groupname='$CONF_DTC_SYSTEM_GROUPNAME',generated_file_path='${PATH_DTC_ETC}' WHERE 1"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE domain SET ip_addr='"$conf_ip_addr"', generate_flag='yes' WHERE name='"$main_domain_name"'"

	# Fix the recipient_delimiter value
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET recipient_delimiter='\\${conf_recipient_delim}' WHERE 1"

	# Fix the path of the htpasswd binary
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET htpasswd_path='"$HTPASSWD"' WHERE 1"

	# Fix the path of the qmail-newu binary
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET qmail_newu_path='"$PATH_QMAIL_NEWU"' WHERE 1"

	# Fix the rights for the UIDs in tables
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE ftp_access SET uid='$CONF_DTC_SYSTEM_UID',gid='$CONF_DTC_SYSTEM_GID' WHERE 1"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE pop_access SET uid='$CONF_DTC_SYSTEM_UID',gid='$CONF_DTC_SYSTEM_GID' WHERE 1"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE ssh_access SET uid='$CONF_DTC_SYSTEM_UID',gid='$CONF_DTC_SYSTEM_GID' WHERE 1"

	# CL: Update crypted passwords only if there is a plaintext password present
	# else sytems runing without plaintext (like mine) will have some big problems
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE pop_access SET crypt=ENCRYPT(passwd,CONCAT(\"\$1\$\",SUBSTRING(crypt,4,8))) where passwd <>''"

	# Add dtc userspace info to mysql db if it's not there
	TMP_FILE=`${MKTEMP} dtc_downer_grep.XXXXXXXX`  || exit 1
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -Dmysql --execute="DESCRIBE user dtcowner" >${TMP_FILE}
	if ! grep dtcowner ${TMP_FILE} >/dev/null 2>&1 ; then
		echoIfVerbose "-> Adding dtcowner column to mysql.user"
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="ALTER IGNORE TABLE mysql.user ADD dtcowner varchar (255) DEFAULT 'none' NOT NULL"
	fi
	if [ -e ${TMP_FILE} ] ; then
		rm ${TMP_FILE}
	fi

	# Inserting the user
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv) VALUES ('%', 'dtcdaemons', PASSWORD('"${MYSQL_DTCDAEMONS_PASS}"'), 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv) VALUES ('localhost', 'dtcdaemons', PASSWORD('"${MYSQL_DTCDAEMONS_PASS}"'), 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N')"

	# Update the password in case of (bad) reinstallation case
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE mysql.user SET Password=PASSWORD('"${MYSQL_DTCDAEMONS_PASS}"') WHERE User='dtcdaemons'"

	# grant Select,Insert,Update,Delete,References,Index to ftp_access
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'ftp_access', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', 'Select')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'ftp_access', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', 'Select')"

	# grant Select,Insert,Update,Delete,References,Index to groups
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'groups', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', 'Select')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'groups', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', 'Select')"

	# grant Select,Insert,Update,Delete,References,Index to ftp_logs
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'ftp_logs', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', '')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'ftp_logs', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', '')"

	# grant Select,Insert,Update,Delete,References,Index to ftp_accounting
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'ftp_accounting', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', '')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'ftp_accounting', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', '')"

	# grant Select,Insert,Update,Delete,References,Index to http_accounting
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'http_accounting', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', '')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'http_accounting', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', '')"

	# grant all to apachelogs
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv) VALUES ('%', 'apachelogs', 'dtcdaemons', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'N', 'Y', 'Y', 'Y')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv) VALUES ('localhost', 'apachelogs', 'dtcdaemons', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'N', 'Y', 'Y', 'Y')"

	# grant select to pop_access 
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'pop_access', '', NOW(NULL), 'Select,Update', 'Select,Update')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'pop_access', '', NOW(NULL), 'Select,Update', 'Select,Update')"

	# update in case of old installations
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE IGNORE mysql.tables_priv SET Timestamp = NOW(NULL) , Table_priv = 'Select,Update', Column_priv = 'Select,Update' WHERE Host = 'localhost' AND Db = '"$conf_mysql_db"' AND User = 'dtcdaemons' AND Table_name = 'pop_access' LIMIT 1 "

	#$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="GRANT SELECT , UPDATE ( crypt , passwd ) ON dtc.pop_access TO 'dtcdaemons'@'localhost'"

	# grant select to ssh_access 
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'ssh_access', '', NOW(NULL), 'Select,Update', 'Select,Update')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'ssh_access', '', NOW(NULL), 'Select,Update', 'Select,Update')"

	# grant select to ssh_groups
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'ssh_groups', '', NOW(NULL), 'Select,Update', 'Select,Update')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'ssh_groups', '', NOW(NULL), 'Select,Update', 'Select,Update')"

	# grant select to ssh_user_group
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'ssh_user_group', '', NOW(NULL), 'Select,Update', 'Select,Update')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'ssh_user_group', '', NOW(NULL), 'Select,Update', 'Select,Update')"

	# populate some data into the ssh_groups table, so that it works correctly
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO ssh_groups (group_id, group_name, status, group_password, gid) VALUES (NULL, 'root', 'A', 'x', 0), (NULL, 'nobody', 'A', 'x', 99), (NULL, 'nobody', 'A', 'x', 65534);"

	# grant Select,Insert,Update,Delete,References,Index to smtp_logs
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'smtp_logs', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', '')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'smtp_logs', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', '')"

	# grant select to whitelist
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'whitelist', '', NOW(NULL), 'Select', 'Select')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('localhost', '"$conf_mysql_db"', 'dtcdaemons', 'whitelist', '', NOW(NULL), 'Select', 'Select')"

	# grant select to fetchmail
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'fetchmail', '', NOW(NULL), 'Select', 'Select')"

	# grant rights for mysqmail
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'domain', '', NOW(NULL), 'Select', 'Select')"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO mysql.tables_priv (Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, Column_priv) VALUES ('%', '"$conf_mysql_db"', 'dtcdaemons', 'email_accounting', '', NOW(NULL), 'Select,Insert,Update,Delete,References,Index', 'Select')"

	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="FLUSH PRIVILEGES"

	# Setup good values depending on Unix distribution
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET dtcadmin_path='${PATH_DTC_ADMIN}', dtcclient_path='${PATH_DTC_CLIENT}', dtcdoc_path='${PATH_DTC_SHARED}/doc', dtcemail_path='${PATH_DTC_SHARED}/email' WHERE 1"

	# Adjust dtcdoc path to correct value for FreeBSD
	if [ $UNIX_TYPE = freebsd ] ; then
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET dtcdoc_path='/usr/local/share/doc/dtc' WHERE 1"
	fi

	# Add the config for nated vhosts if needed
	if [ "$conf_use_nated_vhosts" = "yes" -o "$conf_use_nated_vhosts" = "true" ] ; then
		echoIfVerbose "Setting-up values in MySQL for using NAT"
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET use_nated_vhost='yes'"
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET nated_vhost_ip='"${conf_nated_vhosts_ip}"'"
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET use_multiple_ip='no'"
	else
		echoIfVerbose "Setting-up values in MySQL NOT using NAT"
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET use_nated_vhost='no'"
	fi

	# Update the encryption enforcement value
	if [ "${conf_enforce_adm_encryption}" = "true" ] ; then
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET enforce_adm_encryption='yes'"
	else
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET enforce_adm_encryption='no'"
	fi

	# Set the value to use SSL directly...
	if [ ""$conf_gen_ssl_cert = "true" ] ; then
		echoIfVerbose "Adding the use of SSL directly!"
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET use_ssl='yes'"
	fi

	if [ -z ""$conf_cyrus_pass ] ; then
		conf_cyrus_pass=${MYSQL_DTCDAEMONS_PASS};
	fi
	# Insert the cyrus user so we can use cyradm
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO pop_access (id,fullemail,passwd,crypt) VALUES('cyrus','cyrus@"${MX_MAIL}.${main_domain_name}"','"${conf_cyrus_pass}"',ENCRYPT('"${conf_cyrus_pass}"'))"
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO pop_access (id,fullemail,passwd,crypt) VALUES('cyradm','cyrus','"${conf_cyrus_pass}"',ENCRYPT('"${conf_cyrus_pass}"'))"

	# Set the first admin password
	if [ "${conf_enforce_adm_encryption}" = "true" ] ; then
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO tik_admins (id,pseudo,tikadm_pass) VALUES('','${conf_adm_login}',SHA1('${conf_adm_pass}'))"
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE tik_admins SET tikadm_pass=SHA1('${conf_adm_pass}') WHERE pseudo='${conf_adm_login}'"
	else
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO tik_admins (id,pseudo,tikadm_pass) VALUES('','${conf_adm_login}','${conf_adm_pass}')"
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE tik_admins SET tikadm_pass='${conf_adm_pass}' WHERE pseudo='${conf_adm_login}'"
	fi

	if [ "${UNIX_TYPE}" = "redhat" ] ; then
		$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE config SET domainkey_publickey_filepath='/etc/pki/tls/certs/dkimproxy.crt'"
	fi
}

generateMySQLConfigPHPfile () {
	echoIfVerbose "-> Generating mysql_config.php"
	# The panel needs root access (it does database management)
	echo "<?php" > $PATH_DTC_SHARED"/shared/mysql_config.php"
	echo "\$conf_mysql_host=\""$conf_mysql_host"\";" >> $PATH_DTC_SHARED"/shared/mysql_config.php"
	echo "\$conf_mysql_login=\""$conf_mysql_login"\";" >> $PATH_DTC_SHARED"/shared/mysql_config.php"
	echo "\$conf_mysql_pass=\""$conf_mysql_pass"\";" >> $PATH_DTC_SHARED"/shared/mysql_config.php"
	echo "\$conf_mysql_db=\""$conf_mysql_db"\";" >> $PATH_DTC_SHARED"/shared/mysql_config.php"
	echo "\$conf_mysql_conf_ok=\"yes\";" >> $PATH_DTC_SHARED"/shared/mysql_config.php"
	echo "?>" >> $PATH_DTC_SHARED"/shared/mysql_config.php"
	chmod 600 $PATH_DTC_SHARED"/shared/mysql_config.php"
	chown ${CONF_DTC_SYSTEM_USERNAME} $PATH_DTC_SHARED"/shared/mysql_config.php"
}


createDTCRootShellScript () {
	echoIfVerbose "-> Creating dtc-chroot-shell script with sudo path $PATH_SUDO."
	if [ -n "$PATH_SUDO" ] ; then
		if [ "$UNIX_TYPE" != "debian" ] ; then
		        CHROOT_SHELL=${LOCALBASE}/bin/dtc-chroot-shell
			echoIfVerbose "Creating non-debian chroot shell  with path $CHROOT_SHELL."
		        echo '#!/bin/sh' > $CHROOT_SHELL
			echo "# This shell script is used by DTC, please do not remove" >> $CHROOT_SHELL
		        echo "$PATH_SUDO -H $PATH_CHROOT \$HOME \$USER" ${PATH_BASH} \"\$@\" >> $CHROOT_SHELL
		        chmod 755 $CHROOT_SHELL
		fi
	fi
}

modifySUODERS_DOT_CONF () {
	echoIfVerbose "===> Modifying /etc/sudoers"
	if [ -n "$PATH_SUDO" ] ; then
	        # fix sudoers
		if grep "Configured by DTC" $PATH_SUDOERS_CONF >/dev/null
		then
			echoIfVerbose "$PATH_SUDOERS_CONF has been configured before..."
		else
			if ! [ -f $PATH_SUDOERS_CONF.DTC.backup ]
			then
				echoIfVerbose "===> Backuping "$PATH_SUDOERS_CONF
				cp -f "$PATH_SUDOERS_CONF" "$PATH_SUDOERS_CONF.DTC.backup"
			fi
			TMP_FILE=`${MKTEMP} DTC_install.sudoers.XXXXXX` || exit 1
			echo "# Configured by DTC 0.21 : please do not touch this line !" >> $TMP_FILE
			echo "Defaults:${CONF_DTC_SYSTEM_USERNAME} !set_logname" >> $TMP_FILE
			echo "${CONF_DTC_SYSTEM_USERNAME}      ALL= NOPASSWD: /usr/bin/dtc-chroot-wrapper" >> $TMP_FILE
			echo "# End of DTC configuration : please don't touch this line !" >> $TMP_FILE
			cat <$TMP_FILE >>$PATH_SUDOERS_CONF
			rm -r $TMP_FILE
		fi
	        # fix /etc/shells
		if grep "Configured by DTC" $PATH_SHELLS_CONF >/dev/null
		then
			echoIfVerbose "$PATH_SHELLS_CONF has been configured before..."
		else
			if ! [ -f $PATH_SHELLS_CONF.DTC.backup ]
			then
				echoIfVerbose "===> Backuping "$PATH_SHELLS_CONF
				cp -f "$PATH_SHELLS_CONF" "$PATH_SHELLS_CONF.DTC.backup"
			fi
			TMP_FILE=`${MKTEMP} DTC_install.shells.XXXXXX` || exit 1
			echo "# Configured by DTC 0.21 : please do not touch this line !" >> $TMP_FILE
			echo "${LOCALBASE}/usr/bin/dtc-chroot-shell" >> $TMP_FILE
			echo "# End of DTC configuration : please don't touch this line !" >> $TMP_FILE
			cat <$TMP_FILE >>$PATH_SHELLS_CONF
			rm $TMP_FILE
		fi
	fi
}

increasePhpIniMemAndExecTime () {
	echoIfVerbose "===> Customizing php.ini"
	if ! [ -z ""$PATH_PHP_INI_APACHE ] ; then
		searchAndReplace $PATH_PHP_INI_APACHE memory_limit\ =\ 8M memory_limit\ =\ 64M
		searchAndReplace $PATH_PHP_INI_APACHE memory_limit\ =\ 16M memory_limit\ =\ 64M
	fi
	if ! [ -z ""$PATH_PHP_INI_CLI ] ; then
		searchAndReplace $PATH_PHP_INI_CLI max_execution_time\ =\ 30 max_execution_time\ =\ 1200
		searchAndReplace $PATH_PHP_INI_CLI memory_limit\ =\ 8M memory_limit\ =\ 64M
		searchAndReplace $PATH_PHP_INI_CLI memory_limit\ =\ 16M memory_limit\ =\ 64M
	fi
}

changeApacheUserAndGroup () {
	echoIfVerbose "===> Verifying User and Group directive"

	# This is from upgrades from older versions using nobody
	if grep "User nobody" $PATH_HTTPD_CONF >/dev/null 2>&1
	then
		echo "User nobody -> User ${CONF_DTC_SYSTEM_USERNAME}"
		sed "s/User nobody/User ${CONF_DTC_SYSTEM_USERNAME}/" $PATH_HTTPD_CONF >$TMP_FILE
		cat <$TMP_FILE >$PATH_HTTPD_CONF
	fi
	if grep "Group nogroup" $PATH_HTTPD_CONF >/dev/null 2>&1
	then
		echo "Group nobody -> User ${CONF_DTC_SYSTEM_GROUPNAME}"
		sed "s/Group nogroup/Group ${CONF_DTC_SYSTEM_GROUPNAME}/" $PATH_HTTPD_CONF >$TMP_FILE
		cat <$TMP_FILE >$PATH_HTTPD_CONF
	fi

	# Those 2 are for debian prior Lenny
	if grep "User www-data" $PATH_HTTPD_CONF >/dev/null 2>&1
	then
		echo "User www-data -> User ${CONF_DTC_SYSTEM_USERNAME}"
		sed "s/User www-data/User ${CONF_DTC_SYSTEM_USERNAME}/" $PATH_HTTPD_CONF >$TMP_FILE
		cat <$TMP_FILE >$PATH_HTTPD_CONF
	fi

	if grep "Group www-data" $PATH_HTTPD_CONF >/dev/null 2>&1
	then
		echo "Group www-data -> Group ${CONF_DTC_SYSTEM_GROUPNAME}"
		sed "s/Group www-data/Group ${CONF_DTC_SYSTEM_GROUPNAME}/" $PATH_HTTPD_CONF >$TMP_FILE
		cat <$TMP_FILE >$PATH_HTTPD_CONF
	fi

	# These 2 are for Debian >= Lenny (including Ubuntu)
	if [ -f /etc/apache2/envvars ] ; then
		if grep "export APACHE_RUN_USER=www-data" /etc/apache2/envvars >/dev/null 2>&1
		then
			echo "User www-data -> User ${CONF_DTC_SYSTEM_USERNAME}"
			sed -i "s/export APACHE_RUN_USER=www-data/export APACHE_RUN_USER=${CONF_DTC_SYSTEM_USERNAME}/" /etc/apache2/envvars
		fi

		if grep "export APACHE_RUN_GROUP=www-data" /etc/apache2/envvars >/dev/null 2>&1
		then
			echo "Group www-data -> Group ${CONF_DTC_SYSTEM_GROUPNAME}"
			sed -i "s/export APACHE_RUN_GROUP=www-data/export APACHE_RUN_GROUP=${CONF_DTC_SYSTEM_GROUPNAME}/" /etc/apache2/envvars
		fi
	fi

	# Those 2 are for BSD
	if grep "User www" $PATH_HTTPD_CONF >/dev/null 2>&1
	then
		echo "User www -> User ${CONF_DTC_SYSTEM_USERNAME}"
		sed "s/User www/User ${CONF_DTC_SYSTEM_USERNAME}/" $PATH_HTTPD_CONF >$TMP_FILE
		cat <$TMP_FILE >$PATH_HTTPD_CONF
	fi
	if grep "Group www" $PATH_HTTPD_CONF >/dev/null 2>&1
	then
		echo "Group www -> Group ${CONF_DTC_SYSTEM_GROUPNAME}"
		sed "s/Group www/Group ${CONF_DTC_SYSTEM_GROUPNAME}/" $PATH_HTTPD_CONF >$TMP_FILE
		cat <$TMP_FILE >$PATH_HTTPD_CONF
	fi
	# Those 2 are for RedHat
	if grep "User apache" $PATH_HTTPD_CONF >/dev/null 2>&1
	then
		echo "User apache -> User ${CONF_DTC_SYSTEM_USERNAME}"
		sed "s/User apache/User ${CONF_DTC_SYSTEM_USERNAME}/" $PATH_HTTPD_CONF >$TMP_FILE
		cat <$TMP_FILE >$PATH_HTTPD_CONF
	fi
	if grep "Group apache" $PATH_HTTPD_CONF >/dev/null 2>&1
	then
		echo "Group apache -> Group ${CONF_DTC_SYSTEM_GROUPNAME}"
		sed "s/Group apache/Group ${CONF_DTC_SYSTEM_GROUPNAME}/" $PATH_HTTPD_CONF >$TMP_FILE
		cat <$TMP_FILE >$PATH_HTTPD_CONF
	fi
	rm -f ${TMP_FILE}
}

createApachePIDSymLink () {
	echoIfVerbose "===> Searching and symlinking to apache.pid file"
	# If the variable is not set prior to calling this sript, then search for it!
	if [ -z "$PATH_APACHE_PID_FILE" ] ; then
		# symlink the PidFile to our dtc location, so we can check it in our scripts
		PATH_APACHE_PID_FILE=`grep ^PidFile $PATH_HTTPD_CONF | cut -f2 -d' '`
		## strip the pid of " characters if they exist
		PATH_APACHE_PID_FILE=${PATH_APACHE_PID_FILE##\"}
		PATH_APACHE_PID_FILE=${PATH_APACHE_PID_FILE%%\"}

		if [ "${PATH_APACHE_PID_FILE}" = "\${APACHE_PID_FILE}" ] ; then
			PATH_APACHE_PID_FILE=`cat /etc/apache2/envvars  | grep APACHE_PID_FILE | cut -d'=' -f2 | tail -n 1`
		fi
	
		# in case the specified pid file doesn't exist, try and find it
		if [ ! -e $PATH_APACHE_PID_FILE ] ; then
			if [ -e /etc/httpd/$PATH_APACHE_PID_FILE ] ; then
				PATH_APACHE_PID_FILE=/etc/httpd/$PATH_APACHE_PID_FILE	
			fi
			if [ -e /var/$PATH_APACHE_PID_FILE ] ; then
				PATH_APACHE_PID_FILE=/var/$PATH_APACHE_PID_FILE	
			fi
			if [ -e /var/run/$PATH_APACHE_PID_FILE ] ; then
				PATH_APACHE_PID_FILE=/var/run/$PATH_APACHE_PID_FILE	
			fi
		fi
	fi
	rm -f $PATH_DTC_ETC/apache.pid
	ln -s $PATH_APACHE_PID_FILE $PATH_DTC_ETC/apache.pid
	if [ ! -f $PATH_APACHE_PID_FILE ] ; then
		if ps -e | grep apache$ > /dev/null; then
			ps -e | grep apache$ | head -n 1 | cut -f1 -d' ' >> $PATH_APACHE_PID_FILE
		fi
	fi
}

enableApache2Modules () {
	if [ ""$conf_apache_version = "2" ] ; then
		echoIfVerbose "-> Enabling mod rewrite and modssl for apache 2"
		# Activate mod_rewrite
		if [ -f /etc/apache2/mods-available/rewrite.load ] ; then
			if [ -d /etc/apache2/mods-enabled ] ; then
				if ! [ -e /etc/apache2/mods-enabled/rewrite.load ] ; then
					if [ -x /usr/sbin/a2enmod ] ; then
						a2enmod rewrite || true
					else
						ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load
					fi
				fi
			fi
		fi
		# Activate mod_actions
		if [ -f /etc/apache2/mods-available/actions.load ] ; then
			if [ -d /etc/apache2/mods-enabled ] ; then
				if ! [ -e /etc/apache2/mods-enabled/actions.load ] ; then
					if [ -x /usr/sbin/a2enmod ] ; then
						a2enmod actions || true
					else
						ln -s /etc/apache2/mods-available/actions.load /etc/apache2/mods-enabled/actions.load
					fi
				fi
			fi
		fi
		# Activate mod_ssl
		if [ -f /etc/apache2/mods-available/ssl.load ] ; then
			if [ -d /etc/apache2/mods-enabled ] ; then
				if ! [ -e /etc/apache2/mods-enabled/ssl.load ] ; then
					if [ -x /usr/sbin/a2enmod ] ; then
						a2enmod ssl || true
					else
						ln -s ../mods-available/ssl.load /etc/apache2/mods-enabled/ssl.load
					fi
				fi
			fi
		fi
		# Desactivate mod_php5
		if [ -f /etc/apache2/mods-available/php5.load ] ; then
			if [ -d /etc/apache2/mods-enabled ] ; then
				if [ -e /etc/apache2/mods-enabled/php5.load ] ; then
					if [ -x /usr/sbin/a2enmod ] ; then
						a2dismod php5 || true
					else
						rm -f /etc/apache2/mods-enabled/php5.load
						rm -f /etc/apache2/mods-enabled/php5.conf
					fi
				fi
			fi
		fi
		# Remove the default vhost shipped by default in Apache
		if [ -e /etc/apache2/sites-available/default ] ; then
			if [ -d /etc/apache2/sites-enabled ] ; then
				if [ -e /etc/apache2/sites-enabled/000-default ] ; then
					if [ -x /usr/sbin/a2dissite ] ; then
						a2dissite default || true
					else
						rm -f /etc/apache2/sites-enabled/000-default
					fi
				fi
			fi
		fi
	fi
}

createApacheAdminProtectedDir () {
	echoIfVerbose "Creating "$PATH_DTC_ADMIN"/.htaccess file."
	echo "<Files *>
	Order deny,allow
	deny from all
</Files>

<FilesMatch \"^\$\">
	Order allow,deny
	allow from all
</FilesMatch>

<FilesMatch \"\\.(|gif|jpg|jpeg|png|ico|css|js)\$\">
	Order allow,deny
	allow from all
</FilesMatch>

<FilesMatch ^(index\\.php|logPushlet\\.php|bw_per_month\\.php|deamons_state\\.php|vm-cpu\\.php|vm-net-all\\.php|vps_stats_hdd\\.php|cpugraph\\.php|logPushlet\\.php|memgraph\\.php|view_waitingusers\\.php|vm-io-all\\.php|vm-net\\.php|vps_stats_network\\.php|mailgraph\\.php|netusegraph\\.php|active_prods_graph\\.php|vm-cpu-all\\.php|vm-io\\.php|vps_stats_cpu\\.php|vps_stats_swap\\.php)\$>
	Order allow,deny
	allow from all
</FilesMatch>
" >$PATH_DTC_ADMIN/.htaccess
}

modifyHTTPD_CONF () {
	#
	# Include $PATH_DTC_ETC/vhosts.conf in $PATH_HTTPD_CONF
	#
	echoIfVerbose "===> Modifying httpd.conf"

	if grep "Configured by DTC" $PATH_HTTPD_CONF >/dev/null ; then
		echoIfVerbose "httpd.conf has been configured before : skipping include inssertion !"
	else
		if [ $UNIX_TYPE = freebsd ] ; then
			if grep apache22_enable /etc/rc.conf >/dev/null ; then
				echo "Apache already enabled in /etc/rc.conf"
			else
				if grep "Configured by DTC" /etc/rc.conf >/dev/null ; then
					## Configure already echoed
					echo -n ""
				else
					echo "### Configured by DTC 0.31 - please do not remove" >>/etc/rc.conf
				fi
				echo "Activating apache on /etc/rc.conf"
				echo "apache22_enable=\"YES\"" >>/etc/rc.conf
			fi
			cp $PATH_DTC_ADMIN/install/bsdsquirrelmail.conf `dirname $PATH_HTTPD_CONF`/Includes
			cp $PATH_DTC_ADMIN/install/bsdphpmyadmin.conf `dirname $PATH_HTTPD_CONF`/Includes
			cp $PATH_DTC_ADMIN/install/bsddtcdoc.conf `dirname $PATH_HTTPD_CONF`/Includes
		fi
		if ! [ -f $PATH_HTTPD_CONF.DTC.backup ]
		then
			echoIfVerbose "===> Backuping "$PATH_HTTPD_CONF
			cp -f "$PATH_HTTPD_CONF" "$PATH_HTTPD_CONF.DTC.backup"
		fi

		echoIfVerbose "Checking for AllowOverride..."
		searchAndReplace $PATH_HTTPD_CONF AllowOverride\ None AllowOverride\ AuthConfig\ FileInfo\ Limit\ Indexes
		searchAndReplace $PATH_HTTPD_CONF Options\ None Options\ FollowSymLinks

		# It seems redhat has already the Listen directives...
		# detect whether we already have Listen directives, and comment them out	# and replace with Listen 127.0.0.1:80 and 127.0.0.1:443
		# the other IPs will be created in vhosts.conf
		if grep "^Listen" $PATH_HTTPD_CONF >/dev/null
		then
			perl -i -p -e 's/^Listen/#Listen/' $PATH_HTTPD_CONF	
		fi
		if grep "^BindAddress" $PATH_HTTPD_CONF >/dev/null
		then
			perl -i -p -e 's/^BindAddress/#BindAddress/' $PATH_HTTPD_CONF	
		fi

		# if we have a modules.d folder, we need to check to see if there are any Listen or BindAddress there too
		if [ -e /etc/apache*/modules.d/ ] ; then
			# first Listen
			for i in `grep -l ^Listen /etc/apache*/modules.d/*`; do
				perl -i -p -e 's/^Listen/#Listen/' $i	
			done
			# then BindAddress
			for i in `grep -l ^BindAddress /etc/apache*/modules.d/*`; do
				perl -i -p -e 's/^BindAddress/#BindAddress/' $i	
			done
		fi


		# annoyingly redhat has a different Listen for the ssl.conf
		# comment that out too
		if [ "$UNIX_TYPE" = "redhat" ] ; then
			perl -i -p -e 's/^Listen/#Listen/' /etc/httpd/conf.d/ssl.conf
		fi

		echoIfVerbose "-> Adding DTC's directives to httpd.conf end"
		echo "# Configured by DTC v0.12 : please do not touch this line !
" >>$PATH_HTTPD_CONF
		if [ "$UNIX_TYPE" = "freebsd" ] ; then
			# Insert the missing things as per default in FreeBSD
			echo "LoadModule log_sql_module libexec/apache22/mod_log_sql.so
LoadModule log_sql_mysql_module libexec/apache22/mod_log_sql_mysql.so
MIMEMagicFile etc/apache22/magic
AddType application/x-httpd-php .php
" >>$PATH_HTTPD_CONF
		fi
		echo "ScriptAlias /cgi-bin $PATH_CGIBIN
" >>$PATH_HTTPD_CONF
		echo "
Include $PATH_DTC_ETC/vhosts.conf
" >>$PATH_HTTPD_CONF

		if ! [ ""$conf_omit_dev_mknod = "true" ] ; then
			echo "Listen 127.0.0.1:80
Listen 127.0.0.1:443" >>$PATH_HTTPD_CONF
		fi

		# Since it will contain the password to MySQL, we don't want the file to be world readable.
		chmod 640 ${PATH_HTTPD_CONF}
		if [ -z ${MYSQL_DTCDAEMONS_PASS} ] ; then
			echo "LogSQLLoginInfo mysql://dtcdaemons@${conf_mysql_host}/apachelogs " >>$PATH_HTTPD_CONF
		else
			echo "LogSQLLoginInfo mysql://dtcdaemons:${MYSQL_DTCDAEMONS_PASS}@${conf_mysql_host}/apachelogs " >>$PATH_HTTPD_CONF
		fi
		if [ "${conf_mysql_host}" = "localhost" ] ; then
			echo "LogSQLSocketFile ${MYSQL_DB_SOCKET_PATH}" >>$PATH_HTTPD_CONF
		else
			echo "LogSQLDBParam port 3306" >>$PATH_HTTPD_CONF
		fi
		echo "LogSQLDatabase apachelogs
LogSQLCreateTables On
LogSQLTransferLogFormat IAbhRrSsU
Alias /dtc404/	$PATH_DTC_ETC/dtc404/
ErrorDocument 404 /dtc404/404.php
ErrorDocument 400 /dtc404/406.php
ErrorDocument 406 /dtc404/406.php
ErrorDocument 500 /dtc404/406.php
ErrorDocument 501 /dtc404/406.php
<IfModule mod_security2.c>
	Include $PATH_DTC_ADMIN/mod-security/modsecurity_crs_10_config.conf
	Include $PATH_DTC_ADMIN/mod-security/modsecurity_crs_20_protocol_violations.conf
	Include $PATH_DTC_ADMIN/mod-security/modsecurity_crs_21_protocol_anomalies.conf
	Include $PATH_DTC_ADMIN/mod-security/modsecurity_crs_23_request_limits.conf
	Include $PATH_DTC_ADMIN/mod-security/modsecurity_crs_30_http_policy.conf     
	Include $PATH_DTC_ADMIN/mod-security/modsecurity_crs_35_bad_robots.conf      
	Include $PATH_DTC_ADMIN/mod-security/modsecurity_crs_40_generic_attacks.conf
	Include $PATH_DTC_ADMIN/mod-security/modsecurity_crs_45_trojans.conf
	Include $PATH_DTC_ADMIN/mod-security/modsecurity_dtc_web_apps.conf
</IfModule>
" >>$PATH_HTTPD_CONF
		echo "# End of DTC configuration v0.12 : please don't touch this line !" >>$PATH_HTTPD_CONF
	fi

	if [ -e /etc/apache2/ports.conf ] ; then
		echoIfVerbose "Founded ports.conf: will remove it's directive"
		if [ -e /etc/apache2/ports.conf.DTC_backup ] ; then
			echo -n "";
		else
			cp /etc/apache2/ports.conf /etc/apache2/ports.conf.DTC_backup
		fi
		echo "" >/etc/apache2/ports.conf
	fi

	if [ "$UNIX_TYPE" = "redhat" -a -f /etc/httpd/conf.d/mod_log_sql.conf ] ; then
		sed -i "s/#LoadModule log_sql_module modules\/mod_log_sql.so/LoadModule log_sql_module modules\/mod_log_sql.so/" /etc/httpd/conf.d/mod_log_sql.conf
		sed -i "s/#LoadModule log_sql_mysql_module modules\/mod_log_sql_mysql.so/LoadModule log_sql_mysql_module modules\/mod_log_sql_mysql.so/" /etc/httpd/conf.d/mod_log_sql.conf
	fi

	touch ${PATH_DTC_ETC}/logrotate
	chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} ${PATH_DTC_ETC}/logrotate
	# The cband folder containing score boards for all users
	mkdir -p ${PATH_DTC_ETC}/cband_scores
	chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} ${PATH_DTC_ETC}/cband_scores
}

# need to make sure we are loading LOG_SQL in the /etc/conf.d/apache2 if that file exists
# this is especially true for gentoo
modifyETC_CONFD_APACHE2 () {
	APACHE2_CONFD="/etc/conf.d/apache2"
	if [ -e ${APACHE2_CONFD} ] ; then
		echoIfVerbose "Customizing ${APACHE2_CONFD}"
		if grep "Configured by DTC" $APACHE2_CONFD >/dev/null
		then
			echoIfVerbose "$APACHE2_CONFD has been configured before : skipping include inssertion !"
		else
			if ! [ -f $APACHE2_CONFD.DTC.backup ]
			then
				echoIfVerbose "===> Backing up "$APACHE2_CONFD
				if [ ! -e $APACHE2_CONFD".DTC.backup" ] ; then
					cp -f "$APACHE2_CONFD" "$APACHE2_CONFD.DTC.backup"
				fi
			fi

			TMP_FILE=`${MKTEMP} DTC_install_conf.d_apache2.XXXXXX` || exit 1
			echo "# Configured by DTC $VERSION" >> $TMP_FILE
			echo "# This overrides all APACHE2_OPTS, if you wish to modify these options," >> $TMP_FILE
			echo "# please add the following line to the end of the file" >> $TMP_FILE
			echo "# and replace <your defines> with the obvious" >> $TMP_FILE
			echo "# APACHE2_OPTS=\"\$APACHE2_OPTS <your defines>\"" >> $TMP_FILE
			echo "APACHE2_OPTS=\"-D PHP5 -D SSL -D MOD_LOG -D LOG_SQL\"" >> $TMP_FILE
			echo "# End of DTC configuration $VERSION" >> $TMP_FILE

			# now to insert it at the end of the actual $APACHE2_CONFD
			cat < $TMP_FILE >>$APACHE2_CONFD
			rm ${TMP_FILE}
		fi
	fi
}

generateOpenSSLApacheCert () {
	echoIfVerbose "===> Generating SSL certificate"
	# Generate the OpenSSL test certificate if it does not exists
	if [ ""$conf_gen_ssl_cert = "true" ] ; then
		if [ ! -e $PATH_DTC_ETC"/ssl" ] ; then
			mkdir -p $PATH_DTC_ETC"/ssl"
		fi
		cwd=`pwd`
		cd $PATH_DTC_ETC"/ssl"
		if [ ! -e "./"new.cert.csr ] ; then
			if [ ! -e "./"new.cert.cert ] ; then
				if [ ! -e "./"new.cert.key ] ; then
					if [ -z "${conf_cert_statecode}" ] ; then
						conf_cert_statecode="the state"
					fi
					CERTPASS_TMP_FILE=`${MKTEMP} certfilepass.XXXXXX` || exit 1
					echo $conf_gen_ssl_cert"" >$CERTPASS_TMP_FILE
					( echo $conf_cert_countrycode;
					echo ""$conf_cert_statecode;
					echo ""$conf_cert_locality;
					echo ""$conf_cert_organization;
					echo ""$conf_cert_unit;
					echo $dtc_admin_subdomain"."$main_domain_name;
					echo ""$conf_cert_email;
					echo ""$conf_cert_challenge_pass;
					echo ""$conf_cert_organization; ) | openssl req -passout file:$CERTPASS_TMP_FILE -new > new.cert.csr
					openssl rsa -passin file:$CERTPASS_TMP_FILE -in privkey.pem -out new.cert.key
					openssl x509 -in new.cert.csr -out new.cert.cert -req -signkey new.cert.key -days 3650
					rm $CERTPASS_TMP_FILE
					echo "To make use of certificate chains as described in http://www.modssl.org/docs/2.8/ssl_reference.html#ToC12, place the chain certificate file into this directory and name it new.cert.ca. It will then be included through a SSLCertificateChainFile directive." >certificate-chain-file.readme 
					# Copy the certificates to make them available for qmail
					if [ -d /var/qmail/control ] ; then
						if ! [ -e /var/qmail/control/servercert.pem ] ; then
							cat $PATH_DTC_ETC/ssl/new.cert.key $PATH_DTC_ETC/ssl/new.cert.cert >/var/qmail/control/servercert.pem
							chown qmaild:qmail /var/qmail/control/servercert.pem
							chmod 400 /var/qmail/control/servercert.pem
						fi
					fi
				fi
			fi
		fi
		chmod 400 new.cert.csr new.cert.cert new.cert.key privkey.pem
		cd $cwd
	fi
}

createCyrusAuthPhp () {
	echoIfVerbose "===> Creating cyrus.php"
	
	cyrus_auth_php="$PATH_DTC_SHARED/shared/cyrus.php"
	
	if [ ""$conf_use_cyrus = "true" ] ; then
		if [ -z ""$conf_cyrus_pass ] ; then
			conf_cyrus_pass=${MYSQL_DTCDAEMONS_PASS};
		fi	
		echo "<?php
\$CYRUS = array(
'HOST'  => 'localhost',
'PORT'  => 143,
'ADMIN' => 'cyrus@"${MX_MAIL}".${main_domain_name}',
'PASS'  => '${conf_cyrus_pass}'
);
\$cyrus_used=1;
\$cyrus_default_quota=51200;
?>" > $cyrus_auth_php;
	else
		echo "<?php
\$cyrus_used=0;
?>" > $cyrus_auth_php;
	fi
}

modifyCyrusImapdConf () {

	if [ ""$conf_use_cyrus = "true" ] ; then
	    echoIfVerbose "===> Cyrus enabled"

		if [ "$UNIX_TYPE" = "freebsd" ] ; then
			cyrus_etc_path='/usr/local/etc'
		else
			cyrus_etc_path='/etc'
		fi # [ ""$UNIX_TYPE = "freebsd" ]
		# CL: OSX seems to use cyrusimap instead of cyrus
		if [ "$UNIX_TYPE" = "osx" ] ; then
			cyrus_admin='cyrusimap'
		else
			cyrus_admin='cyrus'
		fi # [ ""$UNIX_TYPE = "freebsd" ]

        # CL: Please, if you do changes here, think about the linx part also, thanks :)
		if [ "$UNIX_TYPE" = "freebsd" -o "$UNIX_TYPE" = "osx" ] ; then
			echo "configdirectory: /var/spool/imap
partition-default: /var/spool/mail
admins: ${cyrus_admin}
defaultdomain: "${MX_MAIL}".${main_domain_name}
duplicatesuppression: 1
sievedir: /var/spool/sieve
sendmail: /usr/sbin/sendmail
hashimapspool: yes
quotawarn: 90
virtdomains: userid
unixhierarchysep: yes

sasl_pwcheck_method: auxprop
auxprop_plugin: sql
sasl_mech_list: plain login digest-md5 cram-md5

sasl_sql_engine: mysql
sasl_sql_hostnames: ${conf_mysql_host}
sasl_sql_database: ${conf_mysql_db}
sasl_sql_user: dtcdaemons
sasl_sql_select: SELECT passwd FROM pop_access WHERE fullemail = '%u@%r'
" > $cyrus_etc_path/imapd.conf

			# CL: ok this looks like bsd only, so I will not touch this.
			# except for the mkimap, I will use that one for mac also in the else part.
			if [ "$UNIX_TYPE" = "freebsd" -o "$UNIX_TYPE" = "osx" ] ; then
				if [ ! -z ${MYSQL_DTCDAEMONS_PASS} ] ; then
					echo "sasl_sql_passwd: ${MYSQL_DTCDAEMONS_PASS}" >> $cyrus_etc_path/imapd.conf
				fi #MYSQL_DTCDAEMONS_PASS

				if [ "$UNIX_TYPE" = "freebsd" ] ; then
					/usr/local/cyrus/bin/mkimap
				else
					su cyrusimap /usr/bin/cyrus/tools/mkimap
					# restart cyrus
					launchctl stop edu.cmu.andrew.cyrus.master
				fi
			fi
			if [ "$UNIX_TYPE" = "freebsd" ] ; then
			        named=`grep  cyrus_imapd_enable /etc/rc.conf`
				if [ "$named" = "" ] || [ "$nonamed" != "" ] ; then
					echo "===> FreeBSD: Backing up /etc/rc.conf and inserting cyrus_imapd_enable=YES"
					cp /etc/rc.conf /etc/rc.conf.old
					echo "/etc/rc.conf /etc/rc.conf.old saved"
					cat /etc/rc.conf | grep -v "cyrus_imapd_enable" >> /etc/rc.tmp
					echo 'cyrus_imapd_enable="YES"' >> /etc/rc.tmp
					mv /etc/rc.tmp /etc/rc.conf
					echo "cyrus imapd /etc/rc.conf injected"
				else
			                echo "===> /etc/rc.conf is already configured: leaving..."
				fi #[ "$named" = "" ] || [ "$nonamed" != "" ]

				if [ ! -d /var/imap/socket ] ; then
					mkdir -p /var/imap/socket
				fi #[ ! -d /var/imap/socket ]

				/usr/local/etc/rc.d/imapd restart

			fi #if [ ""$UNIX_TYPE = "freebsd" ]
			
		    if [ -z ""$conf_cyrus_pass ] ; then
				conf_cyrus_pass=${MYSQL_DTCDAEMONS_PASS};
			fi			
			$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="INSERT IGNORE INTO pop_access (id,mbox_host,fullemail,passwd,crypt) VALUES('root','"${main_domain_name}"','root@"${main_domain_name}"','"${conf_cyrus_pass}"',ENCRYPT('"${conf_cyrus_pass}"'))"

             sleep 10 
			 echo "===> calling $PATH_DTC_ADMIN/install/mk_root_mailbox.php ${main_domain_name}"
			 php -f $PATH_DTC_ADMIN/install/mk_root_mailbox.php ${main_domain_name}
		fi # [ ""$UNIX_TYPE = "freebsd" -o $UNIX_TYPE"" = "osx" ]
	fi # [ ""$conf_use_cyrus = "true" ]
}

modifyNamedConf () {
	# Change the rights of the zones folder, in case it was wrong like before
	mkdir -p $PATH_DTC_ETC/zones
	mkdir -p $PATH_DTC_ETC/slave_zones
	mkdir -p $PATH_DTC_ETC/reverse_zones
	mkdir -p $PATH_DTC_ETC/slave_reverse_zones
	chmod 777 $PATH_DTC_ETC/zones $PATH_DTC_ETC/slave_zones $PATH_DTC_ETC/reverse_zones $PATH_DTC_ETC/slave_reverse_zones

	#
	# include $PATH_DTC_ETC/named.zones in $PATH_NAMED_CONF
	#
	echoIfVerbose "===> Configuring named.conf"
	if [ "$UNIX_TYPE" = "redhat" ] ; then
		for i in conf root.hints rfc1912.zones ; do
			if [ ! -e /etc/named.${i} ] ; then
				cp /usr/share/doc/bind-9.*/sample/etc/named.${i} /etc
			fi
		done
		VAR_NAMED_FOLDER=/usr/share/doc/bind-9.*/sample/var/named
		if [ -e "${VAR_NAMED_FOLDER}" ] ; then
			OLD_CWD=`pwd`
			cd ${VAR_NAMED_FOLDER}
			for i in * ; do
				if [ ! -e /var/named/${i} ] ; then
					cp -rf ${i} /var/named
				fi
			done
			cd slaves
			for i in * ; do
				if [ ! -e /var/named/slaves/${i} ] ; then
					cp -rf ${i} /var/named/slaves
				fi
			done
			cd ${OLD_CWD}
		else
			echo "WARNING! Folder ${VAR_NAMED_FOLDER} does not exists in your system!!!"
		fi
		if grep "use /usr/sbin/dns-keygen to generate TSIG keys" $PATH_NAMED_CONF >/dev/null ; then
			NAMED_KEY=`/usr/sbin/dns-keygen`
			sed -i "s/use \/usr\/sbin\/dns-keygen to generate TSIG keys/${NAMED_KEY}/" $PATH_NAMED_CONF
		fi
	fi

	# need to detect named chroot for gentoo
	NAMED_CHROOT=
	if [ -e /etc/conf.d/named ] ; then
		NAMED_CHROOT=`. /etc/conf.d/named; echo -n $CHROOT`
		echoIfVerbose "named is configured for chroot at $NAMED_CHROOT"
	fi
	# check to see if NAMED_CHROOT is / 
	# if so, then we need not do all this hooha below
	if [ "${NAMED_CHROOT}" = "/" ] ; then
		NAMED_CHROOT=
	fi

	if [ -n ""$NAMED_CHROOT ] ; then
		if [ -e ""$NAMED_CHROOT ] ; then
			mkdir -p $NAMED_CHROOT/$PATH_DTC_ETC/zones
			mkdir -p $NAMED_CHROOT/$PATH_DTC_ETC/slave_zones
			touch $NAMED_CHROOT/$PATH_DTC_ETC/named.conf
			if [ -e $PATH_DTC_ETC/named.conf ] ; then
				if [ ! -L $PATH_DTC_ETC/named.conf -a ! -e $PATH_DTC_ETC/named.conf.moved ] ; then 
					mv $PATH_DTC_ETC/named.conf $PATH_DTC_ETC/named.conf.moved
				fi
			fi
			if [ -e $PATH_DTC_ETC/zones ] ; then 
				if [ ! -L $PATH_DTC_ETC/zones -a ! -e $PATH_DTC_ETC/zones.moved ] ; then
					mv $PATH_DTC_ETC/zones $PATH_DTC_ETC/zones.moved
				fi
			fi
			if [ -e $PATH_DTC_ETC/slave_zones ] ; then 
				if [ ! -L $PATH_DTC_ETC/slave_zones -a ! -e $PATH_DTC_ETC/slave_zones.moved ] ; then
					mv $PATH_DTC_ETC/slave_zones $PATH_DTC_ETC/slave_zones.moved
				fi
			fi
			if [ ! -L $PATH_DTC_ETC/named.conf ] ; then
				ln -s $NAMED_CHROOT/$PATH_DTC_ETC/named.conf $PATH_DTC_ETC/named.conf
			fi
			if [ ! -L $PATH_DTC_ETC/zones ] ; then
				ln -s $NAMED_CHROOT/$PATH_DTC_ETC/zones $PATH_DTC_ETC/zones
			fi
			if [ ! -L $PATH_DTC_ETC/slave_zones ] ; then
				ln -s $NAMED_CHROOT/$PATH_DTC_ETC/slave_zones $PATH_DTC_ETC/slave_zones
			fi
		fi
	fi

	if grep "Configured by DTC" $PATH_NAMED_CONF 2>&1 >/dev/null ; then
		echoIfVerbose "named.conf has been configured before : skipping include insertion !"
	else
		if ! [ -f $PATH_NAMED_CONF.DTC.backup ] ; then
			cp -f $PATH_NAMED_CONF $PATH_NAMED_CONF.DTC.backup
		fi
		line1="// Configured by DTC v0.10 : please don't touch this line !"
		line2="include \"$PATH_DTC_ETC/named.conf\";"
		if grep -q "view  .*\"external\".*" $PATH_NAMED_CONF ; then
			LINE_NUM=`grep -n "view  .*\"external\".*" $PATH_NAMED_CONF | tail -n 1 | cut -d":" -f1`
			LINE_NUM_TWO=$((${LINE_NUM} + 1 ))
			NEXT_LINE=`head -n ${LINE_NUM_TWO} $PATH_NAMED_CONF | tail -n 1`
			if [ "${NEXT_LINE}" = "{" ] ; then
				TMP_FILE=`${MKTEMP} DTC_install.named.conf.XXXXXX` || exit 1
				head -n ${LINE_NUM_TWO} $PATH_NAMED_CONF >${TMP_FILE}
				echo $line1 >>${TMP_FILE}
				echo $line2 >>${TMP_FILE}
				NUM_LINES=`cat ${PATH_NAMED_CONF} | wc -l`
				TAIL=$((${NUM_LINES} - ${LINE_NUM_TWO} ))
				tail -n ${TAIL} ${PATH_NAMED_CONF} >>${TMP_FILE}
				cat <${TMP_FILE} >$PATH_NAMED_CONF
				rm ${TMP_FILE}
			fi
			if grep -q "view \"localhost_resolver\"" $PATH_NAMED_CONF ; then
				LINE_NUM=`grep -n "view \"localhost_resolver\"" $PATH_NAMED_CONF | tail -n 1 | cut -d":" -f1`
				LINE_NUM_TWO=$((${LINE_NUM} + 1 ))
				NEXT_LINE=`head -n ${LINE_NUM_TWO} $PATH_NAMED_CONF | tail -n 1`
				if [ "${NEXT_LINE}" = "{" ] ; then
					TMP_FILE=`${MKTEMP} DTC_install.named.conf.XXXXXX` || exit 1
					head -n ${LINE_NUM_TWO} $PATH_NAMED_CONF >${TMP_FILE}
					echo $line1 >>${TMP_FILE}
					echo $line2 >>${TMP_FILE}
					NUM_LINES=`cat ${PATH_NAMED_CONF} | wc -l`
					TAIL=$((${NUM_LINES} - ${LINE_NUM_TWO} ))
					tail -n ${TAIL} ${PATH_NAMED_CONF} >>${TMP_FILE}
					cat <${TMP_FILE} >$PATH_NAMED_CONF
					rm ${TMP_FILE}
				fi
			fi
		else
			TMP_FILE=`${MKTEMP} DTC_install.named.conf.XXXXXX` || exit 1
			echo $line1 > $TMP_FILE
			echo $line2 >> $TMP_FILE
			touch $PATH_DTC_ETC/named.conf
			cat < $TMP_FILE >> $PATH_NAMED_CONF
			rm -f $TMP_FILE
		fi
		if [ "$UNIX_TYPE" = "redhat" ] ; then
			touch $PATH_DTC_ETC/named.conf
			chown named.named $PATH_DTC_ETC/named.conf
		fi
		if [ ${UNIX_TYPE} = freebsd ]
		then
			if ! [ -f /etc/namedb/rndc.key ]
			then
				echo "Creating rndc.key to control named"
				rndc-confgen -a
				chmod 644 /etc/namedb/rndc.key
			else
				echo "rndc.key already exists..."
			fi
			if grep -i listen-on /etc/namedb/named.conf|egrep -v "^//"
			then
				echo "Commenting Listen directives on named.conf"
				sed "s'listen-on'//listen-on'I" $PATH_NAMED_CONF >$TMP_FILE
				cat < $TMP_FILE > $PATH_NAMED_CONF
				rm -f $TMP_FILE
			fi
		fi
	fi
}

linkQmailFilesToGenerated () {
	# only try and do qmail stuff if we have qmail installed! (check the control directory)
	if [ -e "$PATH_QMAIL_CTRL" ] ; then
		#
		# Install the qmail links in the /etc/qmail
		#
		echoIfVerbose "===> Linking qmail control files to DTC generated files"
		if ! [ -e $PATH_QMAIL_CTRL/rcpthosts.DTC.backup ]
		then
			cp -f $PATH_QMAIL_CTRL/rcpthosts $PATH_QMAIL_CTRL/rcpthosts.DTC.backup
		fi
		rm -f $PATH_QMAIL_CTRL/rcpthosts
		touch $PATH_DTC_ETC/rcpthosts
		ln -s $PATH_DTC_ETC/rcpthosts $PATH_QMAIL_CTRL/rcpthosts

		touch $PATH_QMAIL_CTRL/virtualdomains
		if ! [ -e $PATH_QMAIL_CTRL/virtualdomains.DTC.backup ]
		then
			cp -f $PATH_QMAIL_CTRL/virtualdomains $PATH_QMAIL_CTRL/virtualdomains.DTC.backup
		fi
		rm -f $PATH_QMAIL_CTRL/virtualdomains
		touch $PATH_DTC_ETC/virtualdomains
		ln -s $PATH_DTC_ETC/virtualdomains $PATH_QMAIL_CTRL/virtualdomains

		if ! [ -e /var/qmail/users/assign.DTC.backup ]
		then
			if [ -e /var/qmail/users/assign ] ; then
				cp -f /var/qmail/users/assign /var/qmail/users/assign.DTC.backup
			fi
		fi
		rm -f /var/qmail/users/assign
		touch $PATH_DTC_ETC/assign
		if ! [ -e /var/qmail/users ] ; then
			mkdir -p /var/qmail/users
		fi
		ln -s $PATH_DTC_ETC/assign /var/qmail/users/assign

		touch /etc/poppasswd
		if ! [ -e /etc/poppasswd.DTC.backup ]
		then
			cp -f /etc/poppasswd /etc/poppasswd.DTC.backup
		fi
		rm -f /etc/poppasswd
		touch $PATH_DTC_ETC/poppasswd
		ln -s $PATH_DTC_ETC/poppasswd /etc/poppasswd
	else
		echoIfVerbose "Could not find qmail directory: skipping"
	fi
}

setupAmavisConf () {
	echoIfVerbose "===> Customizing amavis config"
	#
	# Make some changes to the amavisd-new configuration to allow clamav to work with it cleanly.
	#

	# make sure the amavisd configuration has '$AMAVISD_USER' user and group

	if [ $UNIX_TYPE = freebsd ] ; then
		if grep "Configured by DTC" /etc/rc.conf >/dev/null ; then
			# rc.conf already spammed
			echo -n ""
		else
			echo "### Configured by DTC 0.31 - please do not remove" >>/etc/rc.conf
		fi

		if grep amavisd_enable /etc/rc.conf >/dev/null ; then
			echo "Amavisd already activated in rc.conf"
		else
			echo "Activating amavisd on /etc/rc.conf"
			echo "amavisd_enable=\"YES\"" >>/etc/rc.conf
		fi
	fi

	if [ -n ""$PATH_AMAVISD_CONF ] ; then
		PATH_AMAVISD_ETC=`dirname $PATH_AMAVISD_CONF`
	fi
	AMAVISD_CONFD=0
	# CLAMD_CONF is the file we modify that has the clamd.ctl
	AMAVIS_CLAMD_CONF=$PATH_AMAVISD_CONF
	# if there is no amavisd conf, but there is a conf.d, create a 99-dtc file
	if [ ! -f "$PATH_AMAVISD_CONF" -a -e $PATH_AMAVISD_ETC/conf.d ] ; then
		touch $PATH_AMAVISD_ETC/conf.d/99-dtc
		PATH_AMAVISD_CONF=$PATH_AMAVISD_ETC/conf.d/99-dtc
		AMAVISD_CONFD=1
		AMAVIS_CLAMD_CONF=`grep -l clamd.ctl $PATH_AMAVISD_ETC/conf.d/*`	
	fi

	if [ -f "$PATH_AMAVISD_CONF" ] ; then
		echoIfVerbose "===> Checking user and group configuration for amavisd..."

	        # make sure our users exist for amavis
	        # turn back on error handling, these users probably exist already
	        if [ $UNIX_TYPE = freebsd ] ; then
			# On FreeBSD amavisd user and group are created with app install
			echo -n ""
		else
			$GROUP_ADD_CMD $AMAVISD_USER > /dev/null 2>&1 || true
	        	if [ $? -ne 0 ] ; then
				echoIfVerbose "-> Group amavis already exists..."
	        	fi
	        	$USER_ADD_CMD -g $AMAVISD_USER $AMAVISD_USER > /dev/null 2>&1 || true
	        	if [ $? -ne 0 ] ; then
				echoIfVerbose "-> User amavis already exists..."
	        	fi
	        	$PASSWD_CMD -l $AMAVISD_USER > /dev/null 2>&1 || true
	        	if [ $? -ne 0 ] ; then
				echoIfVerbose "Change password failed for amavis user"
	        	fi
		fi

	        if grep "Configured by DTC" "$PATH_AMAVISD_CONF" >/dev/null; then
			echoIfVerbose "$PATH_AMAVISD_CONF already configured..."
        	else
        		if ! [ -f ${PATH_AMVISD_CONF}.DTC.backup ] ; then
        			echoIfVerbose "===> Backuping "$PATH_AMAVISD_CONF
        			cp -f "$PATH_AMAVISD_CONF" "$PATH_AMAVISD_CONF.DTC.backup"
        		fi
			echoIfVerbose "Inserting configuration into $PATH_AMAVISD_CONF"

			# strip the 1; from the end of the config file
                	perl -i -p -e 's/^1;[^\n]*\n//' $PATH_AMAVISD_CONF

			# fix the clamd ctl file to point to /var/run/clamav/clamd.ctl
			perl -i -p -e 's/\"i\/.*?\/clamd.ctl\"/\"\/var\/run\/clamav\/clamd.ctl\"/' $AMAVIS_CLAMD_CONF

			mkdir -p /var/run/clamav/
			chown -R clamav:clamav /var/run/clamav

                	TMP_FILE=`${MKTEMP} dtc_install.amavisd.conf.XXXXXX` || exit 1
                	echo "# Configured by DTC $VERSION" >> $TMP_FILE
                	echo "\$daemon_user  = '$AMAVISD_USER';" >> $TMP_FILE
                	echo "\$daemon_group  = '$AMAVISD_USER';" >> $TMP_FILE
			echo "\$max_servers=5;" >> $TMP_FILE
                	echo "\$final_virus_destiny = D_DISCARD;" >> $TMP_FILE
                	echo "\$final_spam_destiny = D_PASS;" >> $TMP_FILE
                	echo "\$final_banned_destiny = D_PASS;" >> $TMP_FILE
                	echo "\$final_bad_header_destiny = D_PASS;" >> $TMP_FILE
                	echo "\$warnvirussender = 0;" >> $TMP_FILE
                	echo "\$warnspamsender = 0;" >> $TMP_FILE
			echo " # kill level defaults " >> $TMP_FILE

			echo "\$sa_tag_level_deflt  = -9999;" >> $TMP_FILE
			echo "\$sa_tag2_level_deflt = 4.3;" >> $TMP_FILE
			echo "\$sa_kill_level_deflt = 6.0;" >> $TMP_FILE
			echo "\$sa_dsn_cutoff_level = 11;" >> $TMP_FILE

			echo "\$sa_mail_body_size_limit = 150*1024;" >> $TMP_FILE
			echo "# The following line will read the local domains as generated by DTC, amavisd will need to be restarted for new domains..." >> $TMP_FILE
			echo "read_hash(\\%local_domains, '$PATH_DTC_ETC/local_domains');" >> $TMP_FILE

			# if we have a list of postfix relay domains, we may as well check them to virii etc...
			# If you enable this, it will tag ***SPAM*** twice... not very good looking :)
	 		# if [ -e "$PATH_DTC_ETC/postfix_relay_domains" ] ; then
	 		#	echo "my %tmp_relay_domains;" >> $TMP_FILE
			#	echo "read_hash(\\%tmp_relay_domains, '$PATH_DTC_ETC/postfix_relay_domains');" >> $TMP_FILE
			#	echo "# now merge the two hashes" >> $TMP_FILE
			#	echo "@local_domains{keys %tmp_relay_domains} = values %tmp_relay_domains;" >> $TMP_FILE
			# fi

			echo "# Make sure anti-virus and spam are enabled
@bypass_virus_checks_acl = [ 1 ];
@bypass_spam_checks_acl  = [ 1 ];

# need to check to see if the variables exist, and set them properly if they do
{
no strict 'refs';
my \$ref=\"bypass_virus_checks_maps\";
if (defined @\$ref)
{
@\$ref = (
   \\%bypass_virus_checks, \\@bypass_virus_checks_acl, \\\$bypass_virus_checks_re);
}
\$ref=\"bypass_spam_checks_maps\";
if (defined @\$ref)
{
@\$ref = (
   \\%bypass_spam_checks, \\@bypass_spam_checks_acl, \\\$bypass_spam_checks_re);
}
}

" >> $TMP_FILE

	                echo "# End of DTC configuration $VERSION" >> $TMP_FILE
	                echo "1;  # insure a defined return" >> $TMP_FILE

	                # now to insert it at the end of the actual amavisd.conf
	                cat < $TMP_FILE >>$PATH_AMAVISD_CONF
	                rm ${TMP_FILE}
	        fi
	fi
}

modifyClamavConf () {
	if [ -f "$PATH_CLAMAV_CONF" ] ; then
		if [ $UNIX_TYPE = freebsd ] ; then
			if grep "Configured by DTC" /etc/rc.conf >/dev/null ; then
				# rc.conf already spammed
				echo -n ""
			else
				echo "### Configured by DTC 0.31 - please do not remove" >>/etc/rc.conf
			fi
			if grep clamav_clamd /etc/rc.conf >/dev/null
			then
				echo "Clamav daemon already activated on rc.conf"
			else
				echo "Activating clamav daemon on rc.conf"
				echo "clamav_clamd_enable=\"YES\"" >>/etc/rc.conf
				echo "clamav_freshclam_enable=\"YES\"" >>/etc/rc.conf
			fi
		fi

                echoIfVerbose "===> Checking user and group configuration for clamav..."

	        # make sure our users exist for amavis
	        # turn back on error handling, these users probably exist already
	        if [ $UNIX_TYPE = freebsd ] ; then
			# On FreeBSD tha clamav user and group created on the app install.
			echo -n ""
		else
			$GROUP_ADD_CMD clamav > /dev/null 2>&1 || true
	        	if [ $? -ne 0 ] ; then
				echoIfVerbose "-> Group clamav already exists..."
	        	fi
	        	$USER_ADD_CMD -g clamav clamav > /dev/null 2>&1 || true
	        	if [ $? -ne 0 ] ; then
				echoIfVerbose "-> User clamav already exists..."
	        	fi
	        	$PASSWD_CMD -l clamav > /dev/null 2>&1 || true
	        	if [ $? -ne 0 ] ; then
				echoIfVerbose "-> Change password failed for clamav user"
	        	fi
			# now add amavisd to the clamav group and vice versa
			$USER_MOD_CMD -G clamav,$AMAVISD_USER clamav > /dev/null 2>&1 || true
	        	if [ $? -ne 0 ] ; then
				echoIfVerbose "-> Change group failed for clamav user"
			fi
			$USER_MOD_CMD -G $AMAVISD_USER,clamav $AMAVISD_USER > /dev/null 2>&1 || true
	        	if [ $? -ne 0 ] ; then
				echoIfVerbose "-> Change group failed for amavis user"
			fi
		fi

		# need to add the following to the config file:
		# AllowSupplementaryGroups
		# LocalSocket /var/run/clamav/clamd.ctl
	
		# need to fix a problem with a previous version

		if grep "^1;" "$PATH_CLAMAV_CONF" > /dev/null; then
			perl -i -p -e 's/^1;[^\n]*\n//' $PATH_CLAMAV_CONF
		fi

		# We don't need that code anymore, as clamav is now configured correctly by default
#		if grep "Configured by DTC" "$PATH_CLAMAV_CONF" >/dev/null; then
#			echoIfVerbose "$PATH_CLAMAV_CONF already configured..."
#	        else
#			echoIfVerbose "Inserting configuration into $PATH_CLAMAV_CONF"
#
#	                TMP_FILE=`${MKTEMP} dtc_install.clamav.conf.XXXXXX` || exit 1
#	                echo "# Configured by DTC $VERSION" >> $TMP_FILE
#			if [ "$UNIX_TYPE" = "debian" ] ; then
#				DEBIAN_VERSION=`lsb_release -c -s`
#				if [ "$DEBIAN_VERSION" = "sarge" ] ; then
#					echo "AllowSupplementaryGroups" >> $TMP_FILE
#				fi
#			fi
#			echo "LocalSocket /var/run/clamav/clamd.ctl" >> $TMP_FILE
#	                echo "# End of DTC configuration $VERSION" >> $TMP_FILE
#
#	                # now to insert it at the end of the actual clamav.conf
#	                cat < $TMP_FILE >>$PATH_CLAMAV_CONF
#	                rm -f $TMP_FILE
#	        fi
#	        # Finaly restart the daemon
		if [ ""$UNIX_TYPE = freebsd ] ; then
			restartDaemonMultiUnix clamav-clamd
			restartDaemonMultiUnix clamav-freshclam
		else
	        	restartDaemonMultiUnix clamav-daemon
		fi
	fi
}

modifyCyrusPath () {
	#
	# Modify the cyrus imapd.conf 
	#
	if [ -f "$PATH_CYRUS_CONF" -a  "$UNIX_TYPE" != "freebsd" -a "$UNIX_TYPE" != "osx" ] ; then
		echoIfVerbose "===> modifying cyrus config"
		if grep "Configured by DTC" "$PATH_CYRUS_CONF" >/dev/null
		then
			echoIfVerbose "Cyrus imapd.conf has been configured before"
		else
			searchAndReplace $PATH_CYRUS_CONF unixhierarchysep:\ no unixhierarchysep:\ yes

			# replace auxprop sith saslauthd only if we are using sasl instead of PAM
			if [ ! -f $PATH_SASLLIB/libsql.so ] ; then
				searchAndReplace $PATH_CYRUS_CONF sasl_pwcheck_method:\ auxprop sasl_pwcheck_method:\ saslauthd
				echoIfVerbose "configuring Cyrus for pam_mysql"
			else
				echoIfVerbose "configuring Cyrus for sasl_sql"
			fi
			echoIfVerbose "Inserting DTC configuration inside $PATH_CYRUS_CONF"

			TMP_FILE=`${MKTEMP} DTC_install.imapd.conf.XXXXXX` || exit 1
			echo "# Configured by DTC v0.20 : Please don't touch this line !" > $TMP_FILE
			echo "#virtdomains: yes
quotawarn: 90
admins: cyrus
# sasl_mech_list: PLAIN LOGIN

defaultdomain: "${MX_MAIL}".${main_domain_name}
duplicatesuppression: 1
virtdomains: userid

auxprop_plugin: sql

sasl_sql_engine: mysql
sasl_sql_hostnames: ${conf_mysql_host}
sasl_sql_database: ${conf_mysql_db}
sasl_sql_user: dtcdaemons
sasl_sql_select: SELECT passwd FROM pop_access WHERE fullemail = '%u@%r'
sasl_sql_passwd: ${MYSQL_DTCDAEMONS_PASS}
" >> $TMP_FILE
			echo "# End of DTC configuration v0.20 : Please don't touch this line !" >> $TMP_FILE
		# now to insert it at the end of the actual imapd.conf
		cat < $TMP_FILE >>$PATH_CYRUS_CONF
		rm $TMP_FILE
		fi
	else
		echoIfVerbose "$PATH_CYRUS_CONF NOT FOUND, maybe not using Cyrus this time."
	fi
}

modifySaslStartAndSaslStartup () {
	if [ -f "$PATH_SASL_START_CONF" ] ; then
		echoIfVerbose "===> modifying saslauthd startup parameters"
		if grep "Configured by DTC" $PATH_SASL_START_CONF >/dev/null ; then
			echoIfVerbose "Already configured: skipping"
		else
			TMP_FILE=`${MKTEMP} DTC_install.saslauthd.XXXXXX` || exit 1
			echo "# Configured by DTC v0.20 : Please don't touch this line !" > $TMP_FILE
			echo "START=yes
OPTIONS=\"-r -c -m /var/spool/postfix/var/run/saslauthd\"" >> $TMP_FILE
			echo "# End of DTC configuration v0.20 : Please don't touch this line !" >> $TMP_FILE
			# now to insert it at the end of the actual saslauthd startup file
			cat < $TMP_FILE >>$PATH_SASL_START_CONF
			rm $TMP_FILE
		fi
		if [ -f $PATH_SASL_STARTUP ] ; then
			echoIfVerbose "modifying saslauthd startup file"
			if grep "Configured by DTC" $PATH_SASL_STARTUP >/dev/null ; then
				echoIfVerbose "Already configured: skipping"
			else
				# create the directory for postfix to access SASL socket
				if [ "$UNIX_TYPE" = "debian" ] ; then
					dpkg-statoverride --force --add root sasl 710 /var/spool/postfix/var/run/saslauthd
				else
					chgrp sasl /var/spool/postfix/var/run/saslauthd || true
					chmod 710 /var/spool/postfix/var/run/saslauthd || true
				fi
				echoIfVerbose "Starting SASLauthd"
				/etc/init.d/saslauthd start
			fi
		fi
	else
		if [ ""$conf_use_cyrus = "true" ] ; then
			echo "Cyrus install selected but no saslauthd startup file";
			echo "If you plan to use pam_mysql then do this workaround: make saslauth start with -r -c -a pam";
			echo "And add /var/run/saslauthd /var/spool/postfix/var/run/saslauthd/        none    bind to yout /etc/fstab"
			echo "if you plan to use sasl_mysql just ignore this";
		fi
	fi
	# Fixes broken link of the sasldb2
  # if ! [ -f /etc/sasldb2 ] ; then
  #   if [ -h /etc/sasldb2 ] ; then
  #     rm /etc/sasldb2
  #   fi
  #   ln -s ${PATH_DTC_ETC}/sasldb2 /etc/sasldb2
  # fi
}

modifyPostfixConfig () {
	# 
	# Modify the postfix main.cf to include virtual delivery options
	#

	# Declare this makes the test when appenning the configuration for SASL
	# works if you don't have SASL

	SASLTMP_FILE="/thisfiledoesnotexists"
	if [ -f "$PATH_POSTFIX_CONF" ] ; then
		echoIfVerbose "===> Linking postfix control files to DTC generated files"
		#These files are created by the first cron.php run so (at least for FreeBSD) do not create them
		if [ $UNIX_TYPE != freebsd ]
		then
			touch $PATH_DTC_ETC/postfix_virtual.db
			touch $PATH_DTC_ETC/postfix_aliases.db
			# fix default /etc/aliases
			touch /etc/aliases
			newaliases
			touch $PATH_DTC_ETC/postfix_relay_recipients.db
			touch $PATH_DTC_ETC/postfix_vmailbox.db
			touch $PATH_DTC_ETC/postfix_virtual_uid_mapping.db
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} $PATH_DTC_ETC/postfix_*.db
		fi
		if grep "Configured by DTC" "$PATH_POSTFIX_CONF" >/dev/null
		then
			echoIfVerbose "Postfix main.cf has been configured before, not adding virtual mailbox options"
		else
			if ! [ -f $PATH_POSTFIX_CONF.DTC.backup ] ; then
				echoIfVerbose "===> Backuping "$PATH_POSTFIX_CONF
				cp -f "$PATH_POSTFIX_CONF" "$PATH_POSTFIX_CONF.DTC.backup"
			fi
			if [ ! -d ${PATH_POSTFIX_ETC}/maps ] ; then
				mkdir -p ${PATH_POSTFIX_ETC}/maps
			fi
if grep "recipient_delimiter = +" "$PATH_POSTFIX_ETC/main.cf" >/dev/null; then
				if [ "$conf_recipient_delim" = "-" ] ; then
					echoIfVerbose "Changing recipient delimiter from + to -"
					TMP_FILE=`${MKTEMP} DTC_install.main.cf.XXXXXX` || exit 1
					sed "s/recipient_delimiter = +/recipient_delimiter = -/" "$PATH_POSTFIX_ETC/main.cf" >$TMP_FILE
					cat <$TMP_FILE >"$PATH_POSTFIX_ETC/main.cf"
					rm $TMP_FILE
				fi
			fi

			if grep "recipient_delimiter = -" "$PATH_POSTFIX_ETC/main.cf" >/dev/null; then
				if [ "$conf_recipient_delim" = "+" ] ; then
					echoIfVerbose "Changing recipient delimiter from - to +"
					TMP_FILE=`${MKTEMP} DTC_install.main.cf.XXXXXX` || exit 1
					sed "s/recipient_delimiter = -/recipient_delimiter = +/" "$PATH_POSTFIX_ETC/main.cf" >$TMP_FILE
					cat <$TMP_FILE >"$PATH_POSTFIX_ETC/main.cf"
					rm $TMP_FILE
				fi
			fi

			echoIfVerbose "Inserting DTC configuration inside $PATH_POSTFIX_CONF"

			TMP_FILE=`${MKTEMP} DTC_install.postfix_main.cf.XXXXXX` || exit 1
			echo "# Configured by DTC v0.12 : Please don't touch this line !" > $TMP_FILE
			# CL: this is general config, for courier and cyrus
			# for mailname to be mx.$main_domain_name
			echo ""${MX_MAIL}".$main_domain_name" > /etc/mailname
			echo "# DTC virtual configuration" >> $TMP_FILE
			if [ ""$conf_use_cyrus != "true" ] ; then
				echo "myhostname = "${MX_MAIL}".$main_domain_name" >> $TMP_FILE
			fi
			echo "# disable the following functionality by default (otherwise can't match subdomains correctly)
parent_domain_matches_subdomains=

# Bind on all interfaces by default (needed on CentOS)
inet_interfaces = all

# Sets the sasldb2 path
#smtpd_sasl_path=$PATH_DTC_ETC/sasldb2

# disable mailbox size limit by default (user can add to postfix_config_snippets)
mailbox_size_limit = 0
" >> $TMP_FILE
			if [ ! -e ${PATH_POSTFIX_ETC}/maps/relaying_stoplist ] ; then
				cp -f ${PATH_DTC_ADMIN}/postfix_checks/relaying_stoplist ${PATH_POSTFIX_ETC}/maps
			fi

			FOUND_DKIMPROXY=0;
			if [ -x /usr/sbin/amavisd-new -o -x /usr/local/sbin/amavisd-new -o -x /usr/local/bin/amavisd-new -o -x /usr/sbin/amavisd ] ; then
				if [ -x /usr/sbin/dkimproxy.in -o -x /usr/bin/dkimproxy.in -o -x /usr/local/sbin/dkimproxy.in -o -x /usr/local/bin/dkimproxy.in ] ; then
					FOUND_DKIMPROXY=1;
					echo "# use check_access directive to filter all incoming mail
/^/  FILTER dkimsign:[127.0.0.1]:10026" > $PATH_POSTFIX_ETC/filter_10026_catchall
					echo "# Amavis AND dkimproxy.in have been detected as installed, so this has been activated by default
# if this is not what you want, comment it and restart postfix
# This is the default action, AKA signing
# we trigger the other action (scanning via a check_access directive)
content_filter=dkimsign:[127.0.0.1]:10028
" >> $TMP_FILE
				else
					echo "# Amavis has been detected as installed, so this has been activated by default
# if this is not what you want, comment it and restart postfix
content_filter=smtp-amavis:[127.0.0.1]:10024
" >> $TMP_FILE
				fi
			else
				echo "# uncomment to enable amavis
#   - if you do uncomment this, make sure that you
#     also edit the master.cf file to make sure that
#     the return channel is set correctly
#content_filter=smtp-amavis:[127.0.0.1]:10024
" >> $TMP_FILE
			fi					

echo "virtual_mailbox_domains = hash:$PATH_DTC_ETC/postfix_virtual_mailbox_domains
" >> $TMP_FILE

			if [ ""$conf_use_cyrus = "true" ] ; then
				if [ "$UNIX_TYPE" = "debian" ] ; then
					echo "virtual_transport = lmtp:unix:/var/run/cyrus/socket/lmtp
mailbox_transport = lmtp:unix:/var/run/cyrus/socket/lmtp
# local_recipient_maps = $alias_maps, ... ### CL ToDo! " >> $TMP_FILE
				else
					echo "virtual_transport = cyrus
mailbox_transport = lmtp:unix:/var/run/socket/lmtp
# local_recipient_maps = $alias_maps, ... ### CL ToDo! " >> $TMP_FILE
				fi
			else
				# courier/postfix only!
				echo "virtual_mailbox_base = /
virtual_mailbox_maps = hash:$PATH_DTC_ETC/postfix_vmailbox
virtual_minimum_uid = 98
virtual_uid_maps = static:${CONF_DTC_SYSTEM_UID}
virtual_gid_maps = static:${CONF_DTC_SYSTEM_GID}
virtual_uid_maps = hash:$PATH_DTC_ETC/postfix_virtual_uid_mapping" >> $TMP_FILE
			fi
			# CL continue with global part
			echo "virtual_alias_maps = hash:$PATH_DTC_ETC/postfix_virtual
alias_maps = hash:/etc/aliases, hash:$PATH_DTC_ETC/postfix_aliases
relay_domains = $PATH_DTC_ETC/postfix_relay_domains
relay_recipient_maps = hash:$PATH_DTC_ETC/postfix_relay_recipients " >> $TMP_FILE
			if [ -n $conf_dnsbl_list ] ; then
				IFS=, 
				for i in $conf_dnsbl_list; do 
					dnsbl_list="$dnsbl_list reject_rbl_client $i,"
				done
				unset IFS
			fi
		
			if [ "$PATH_SASL_PASSWD2" = "" ] ; then
				echo -n ""
			elif [ -f $PATH_SASL_PASSWD2 ] ; then
				echoIfVerbose "Found sasl2passwd at $PATH_SASL_PASSWD2"

				mkdir -p $PATH_POSTFIX_ETC/sasl
			
				if [ -e $PATH_POSTFIX_ETC/sasl/smtpd.conf ] ; then
					if ! [ -e $PATH_POSTFIX_ETC/sasl/smtpd.conf.dtcbackup ] ; then 
						cp $PATH_POSTFIX_ETC/sasl/smtpd.conf $PATH_POSTFIX_ETC/sasl/smtpd.conf.dtcbackup
					fi
				fi

#				# prepare some sasldb2 files, so that our script latter can fix them
#
#				if [ -e /var/spool/postfix/etc ] ; then
#					touch /var/spool/postfix/etc/sasldb2
#					if [ ! -e $PATH_DTC_ETC/sasldb2 ] ; then
#						cp /var/spool/postfix/etc/sasldb2 $PATH_DTC_ETC/sasldb2
#					fi
#					chown postfix:${CONF_DTC_SYSTEM_GROUPNAME} /var/spool/postfix/etc/sasldb2
#					chmod 664 /var/spool/postfix/etc/sasldb2
#				else
#					if [ -d /etc/sasl2 ] ; then
#						touch /etc/sasl2/sasldb2
#						chown postfix:${CONF_DTC_SYSTEM_GROUPNAME} /etc/sasl2/sasldb2
#						chmod 664 /etc/sasl2/sasldb2
#					else
#						touch /etc/sasldb2
#						chown postfix:${CONF_DTC_SYSTEM_GROUPNAME} /etc/sasldb2
#						chmod 664 /etc/sasldb2
#					fi
#					if [ ! -e $PATH_DTC_ETC/sasldb2 ] ; then
#						if [ -d /etc/sasl2 ] ; then
#							cp /etc/sasl2/sasldb2 $PATH_DTC_ETC/sasldb2
#						else
#							cp /etc/sasldb2 $PATH_DTC_ETC/sasldb2
#						fi
#					fi
#				fi
        # add postfix to the sasl and mail group, not sure if we still need sasl, but mail is neede for LMTP
        if [ ""$conf_use_cyrus = "true" ] ; then
          if [ "$UNIX_TYPE" = "debian" ] ; then
            echoIfVerbose "Adding postfix to the sasl group"
            adduser postfix sasl
            echoIfVerbose "Adding postfix to the mail group"
            adduser postfix mail
          else
            echoIfVerbose "**** For lmtp delivery to work, postfix needs access to /var/run/cyrus/socket/, please add postfix to mail group !"
          fi
        fi
#         SASLTMP_FILE=`${MKTEMP} DTC_install.postfix_sasl.XXXXXX` || exit 1
#         echo "# Configured by DTC v0.15 : Please don't touch this line !" > ""$SASLTMP_FILE
#         # CL: for cyrus use saslauthd instead of auxprop!
#         # and add postfix to the sasl group
#         if [ ""$conf_use_cyrus = "true" ] ; then
#           echo "pwcheck_method: saslauthd
# mech_list: login plain" >> $SASLTMP_FILE
#           if [ "$UNIX_TYPE" = "debian" ] ; then
#             echoIfVerbose "Adding postfix to the sasl group"
#             adduser postfix sasl
#             echoIfVerbose "Adding postfix to the mail group"
#             adduser postfix mail
#           else
#             echo "*** Please add Postfix to the sasl group so it has access to the saslauthd socket"
#           fi
#         else
#           echo "pwcheck_method: auxprop
# mech_list: plain login digest-md5 cram-md5" >> $SASLTMP_FILE
#         fi
#         echo "# End of DTC configuration v0.15 : please don't touch this line !" >> $SASLTMP_FILE
				permit_sasl_authenticated="
				permit_sasl_authenticated,"
				sasl_main_dot_cf_rules="
smtp_sasl_auth_enable = no
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = /etc/mailname
smtpd_sasl_auth_enable = yes
smtpd_tls_auth_only = no"
#				echo "smtp_sasl_auth_enable = no
#smtpd_sasl_security_options = noanonymous
#smtpd_sasl_local_domain = /etc/mailname
#smtpd_sasl_auth_enable = yes
#smtpd_tls_auth_only = no
#"
			else
				echoIfVerbose "No saslpasswd2 found"
				echo "smtpd_recipient_restrictions = permit_mynetworks," >> $TMP_FILE
				echo "		check_client_access regexp:${PATH_POSTFIX_ETC}/maps/relaying_stoplist," >> $TMP_FILE
echo "                               $dnsbl_list
                               reject_unauth_destination" >> $TMP_FILE
				if [ "$FOUND_DKIMPROXY" -eq 1 ] ; then
#				if [ "$FOUND_DKFILTER" -eq 1 ] ; then
					echo "			check_sender_access regexp:$PATH_POSTFIX_ETC/filter_10026_catchall" >> $TMP_FILE
				fi
                               permit_sasl_authenticated=""
                               sasl_main_dot_cf_rules=""
			fi
			echo "smtpd_delay_reject = yes
smtpd_helo_required = yes
disable_vrfy_command = yes

smtp_tls_security_level = may

smtpd_client_connection_rate_limit=20
smtpd_client_message_rate_limit=20
smtpd_client_recipient_rate_limit=20
anvil_rate_time_unit = 60s

smtpd_recipient_restrictions = permit_mynetworks,${permit_sasl_authenticated}
			check_client_access regexp:${PATH_POSTFIX_ETC}/maps/relaying_stoplist,
			reject_invalid_hostname,
			reject_non_fqdn_sender,
			reject_non_fqdn_recipient,
			reject_unknown_sender_domain,
			reject_unknown_recipient_domain,
			$dnsbl_list
			reject_unauth_destination," >> $TMP_FILE
			if [ "$FOUND_DKIMPROXY" -eq 1 ] ; then
#			if [ "$FOUND_DKFILTER" -eq 1 ] ; then
				echo "			check_sender_access regexp:$PATH_POSTFIX_ETC/filter_10026_catchall" >> $TMP_FILE
			fi
			echo "			permit${sasl_main_dot_cf_rules}" >> $TMP_FILE

			if [ -x /usr/bin/tumgreyspf -o -x ${LOCALBASE}/bin/tumgreyspf ] ; then
				echo "smtpd_sender_restrictions = permit_mynetworks,
				permit_sasl_authenticated,
				reject_unauth_destination,
				check_policy_service unix:private/tumgreyspf,
				permit
" >> $TMP_FILE
			fi
			if [ -x /usr/sbin/spamd -o -x /usr/local/bin/spamd ] ; then
				echo "spam.spam       sa-spam:
ham.ham         sa-ham:
" >$PATH_POSTFIX_ETC/transport
				postmap $PATH_POSTFIX_ETC/transport
				echo "# spam learning transport maps
transport_maps = hash:$PATH_POSTFIX_ETC/transport
" >> $TMP_FILE
			fi

			# this adds supports for "config" snippets to append to main.cf
			if [ -f $PATH_DTC_ETC/postfix_config_snippets ] ; then
				cat $PATH_DTC_ETC/postfix_config_snippets >> $TMP_FILE
			else
				echo "# /var/lib/dtc/etc/postfix_config_snippets
# this file is appended to the postfix configure, in case you need to override some configure parameters in the postfix main.cf" > $PATH_DTC_ETC/postfix_config_snippets
			fi

			if grep "Configured by DTC" /etc/aliases >/dev/null; then
				echoIfVerbose "/etc/aliases configured before, not adding ham/spam aliases"
			else
				if ! [ -f /etc/aliases.DTC.backup ] ; then
					echoIfVerbose "===> Backuping /etc/aliases"
					cp -f /etc/aliases /etc/aliases.DTC.backup
				fi
				echo "# Configured by DTC v0.26 : Please don't touch this line !" >>/etc/aliases
				echo "# auto-spam-learning" >>/etc/aliases
				echo "spam:	spam@spam.spam" >>/etc/aliases
				echo "ham:	ham@ham.ham" >>/etc/aliases
				echo "notspam:	ham@ham.ham" >>/etc/aliases
				echo "# End of DTC configuration v0.26 : please don't touch this line !" >>/etc/aliases
				if [ -f /usr/local/sbin/postalias ] ; then
					/usr/local/sbin/postalias -r /etc/aliases
				else
					/usr/sbin/postalias -r /etc/aliases
				fi
			fi

			if grep "Configured by DTC 0.21" "$PATH_POSTFIX_ETC/master.cf" >/dev/null; then
				echoIfVerbose "Postfix master.cf has been configured before, not adding maildrop options"
			else
				if ! [ -f $PATH_POSTFIX_ETC/master.cf.DTC.backup ] ; then
					echoIfVerbose "===> Backuping $PATH_POSTFIX_ETC/master.cf"
					cp -f "$PATH_POSTFIX_ETC/master.cf" "$PATH_POSTFIX_ETC/master.cf.DTC.backup"
				fi
				echoIfVerbose "Inserting DTC configuration inside $PATH_POSTFIX_ETC/master.cf"

				TMP_FILE2=`${MKTEMP} DTC_install.postfix_master.cf.XXXXXX` || exit 1
				echo "# Configured by DTC v0.17 : Please don't touch this line !" > $TMP_FILE2

				# Insert the sa-learn stuff if spamd is found
				if [ -x /usr/sbin/spamd -o -x /usr/local/bin/spamd ] ; then
					echo "# Adds support for the sa-learn script
sa-spam unix    -       n       n       -       -       pipe
    -o smtpd_client_restrictions=permit_sasl_authenticated,permit_mynetworks,reject
    user=$AMAVISD_USER:$AMAVISD_USER argv=$PATH_DTC_ADMIN/sa-wrapper spam \${sender}

sa-ham  unix    -       n       n       -       -       pipe
    -o smtpd_client_restrictions=permit_sasl_authenticated,permit_mynetworks,reject
    user=$AMAVISD_USER:$AMAVISD_USER argv=$PATH_DTC_ADMIN/sa-wrapper ham  \${sender}

" >> $TMP_FILE2
				fi
				
				# CL: change lmtp from chroot to non chroot, else lmtp delivery won't work
				if [ ""$conf_use_cyrus = "true" ] ; then
  				if [ "$UNIX_TYPE" = "debian" ] ; then  			
    				# Fix the master.cf lmtp stuff
    				sed -i "s/lmtp      unix  -       -       -       -       -       lmtp/lmtp      unix  -       -       n       -       -       lmtp/" $TMP_FILE2
				  fi
			  fi
				
				if [ -x /usr/bin/tumgreyspf -o -x ${LOCALBASE}/bin/tumgreyspf ] ; then
					if [ -x /usr/bin/tumgreyspf ] ; then
						TMP_TUMGREYPATH=/usr/bin/tumgreyspf
					else
						TMP_TUMGREYPATH=${LOCALBASE}/bin/tumgreyspf
					fi
					echo "# Adds support for tumgreyspf
tumgreyspf unix  -      n       n       -       -       spawn
    user=tumgreyspf argv=${TMP_TUMGREYPATH}

" >> $TMP_FILE2
				fi
				# if we have maildrop, we should use it!
				if [ -n ""$PATH_MAILDROP_BIN -a -f "$PATH_MAILDROP_BIN" ] ; then
					if [ $UNIX_TYPE = freebsd ] ; then
						## On FreeBSD: maildrop needs to be setuid root to work the way dtc wants.
						chmod 4755 $PATH_MAILDROP_BIN
					fi
					echo "maildrop  unix  -       n       n       -       -       pipe
    flags=DRhu user=${CONF_DTC_SYSTEM_USERNAME} argv=$PATH_MAILDROP_BIN -a -w 90 -d \${user}@\${nexthop} \${extension} \${recipient} \${user} \${nexthop}

" >> $TMP_FILE2
				fi
				# CL do we use cyrus? 
				if [ "${conf_use_cyrus}" = "true" ] ; then
					if [ -x /usr/sbin/cyrdeliver ] ; then
						TMP_CYRDELIVERPATH=/usr/sbin/cyrdeliver
					else
						if [ -x "${LOCALBASE}/sbin/cyrdeliver" ] ; then
							TMP_CYRDELIVERPATH=${LOCALBASE}/sbin/cyrdeliver
						fi
					fi
					echo "cyrus     unix  -       n       n       -       -       pipe
  flags=R user=cyrus argv=${TMP_CYRDELIVERPATH} -e -m \${extension} \${recipient}
">> $TMP_FILE2
				fi

				# Insert our amavis stuff inside the master.cf
				echo "# amavisd-new
smtp-amavis unix -      -       -       -       2  smtp
    -o smtp_data_done_timeout=1200
    -o smtp_send_xforward_command=yes
    -o disable_dns_lookups=yes
    -o max_use=20

127.0.0.1:10025 inet n  -       -       -       -  smtpd
    -o content_filter=
    -o local_recipient_maps=
    -o relay_recipient_maps=
    -o smtpd_restriction_classes=
    -o smtpd_client_restrictions=
    -o smtpd_helo_restrictions=
    -o smtpd_sender_restrictions=
    -o smtpd_recipient_restrictions=permit_mynetworks,reject
    -o strict_rfc821_envelopes=yes
    -o smtpd_error_sleep_time=0
    -o smtpd_soft_error_limit=1001
    -o smtpd_hard_error_limit=1000
    -o smtpd_client_connection_count_limit=0
    -o smtpd_client_connection_rate_limit=0
    -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_address_mappings

" >> $TMP_FILE2

				if [ "$FOUND_DKIMPROXY" -eq 1 ] ; then
					echo "# DKIM filter configuration
#
# modify the default submission service to specify a content filter
# and restrict it to local clients and SASL authenticated clients only
#
submission  inet  n     -       n       -       -       smtpd
    -o smtpd_etrn_restrictions=reject
    -o smtpd_sasl_auth_enable=yes
    -o content_filter=dkimsign:[127.0.0.1]:10028
    -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject

#
# specify the location of the DomainKeys signing filter
#
dkimsign    unix  -       -       n       -       4      smtp
    -o smtp_send_xforward_command=yes
    -o smtp_discard_ehlo_keywords=8bitmime

#
# service for accepting messages FROM the DomainKeys signing filter
#
127.0.0.1:10029 inet  n  -      n       -       5      smtpd
    -o smtpd_use_tls=no
    -o content_filter=
    -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks,no_address_mappings
    -o smtpd_helo_restrictions=
    -o smtpd_client_restrictions=
    -o smtpd_sender_restrictions=
    -o smtpd_recipient_restrictions=permit_mynetworks,reject
    -o mynetworks=127.0.0.0/8
    -o smtpd_authorized_xforward_hosts=127.0.0.0/8

# For Postfix to sign mails sent out using Webmail or other locally delivered mail
pickup fifo n - n 60 1 pickup
        -o content_filter=dkimsign:127.0.0.1:10028

" >> $TMP_FILE2
				fi

				echo "# End of DTC configuration v0.17 : please don't touch this line !" >> $TMP_FILE2
				cat < $TMP_FILE2 >>"$PATH_POSTFIX_ETC/master.cf"
				rm $TMP_FILE2
			fi

			# Keep bounce and queue small, we don't want the default 5 days ...
			echo "bounce_queue_lifetime = 3d
maximal_queue_lifetime = 3d" >> $TMP_FILE
			# Now we add the header, mime and body checks
			if [ ! -e ${PATH_POSTFIX_ETC}/maps/header_checks ] ; then
				cp -f ${PATH_DTC_ADMIN}/postfix_checks/header_checks ${PATH_POSTFIX_ETC}/maps
			fi
			if [ ! -e ${PATH_POSTFIX_ETC}/maps/body_checks ] ; then
				cp -f ${PATH_DTC_ADMIN}/postfix_checks/body_checks ${PATH_POSTFIX_ETC}/maps
			fi
			if [ ! -e ${PATH_POSTFIX_ETC}/maps/mime_header_checks ] ; then
				cp -f ${PATH_DTC_ADMIN}/postfix_checks/mime_header_checks ${PATH_POSTFIX_ETC}/maps
			fi
			if [ ! -e ${PATH_POSTFIX_ETC}/maps/header_checks ] ; then
				cp -f ${PATH_DTC_ADMIN}/postfix_checks/header_checks ${PATH_POSTFIX_ETC}/maps
			fi
			
			
#			postmap ${PATH_POSTFIX_ETC}'/maps/header_checks'
#			postmap ${PATH_POSTFIX_ETC}'/maps/body_checks'
#			postmap ${PATH_POSTFIX_ETC}'/maps/mime_header_checks'

			echo "header_checks = regexp:${PATH_POSTFIX_ETC}/maps/header_checks
body_checks = regexp:${PATH_POSTFIX_ETC}/maps/body_checks
mime_header_checks = regexp:${PATH_POSTFIX_ETC}/maps/mime_header_checks
smtpd_client_restrictions = permit_mynetworks,
	permit_sasl_authenticated,
	check_client_access regexp:${PATH_POSTFIX_ETC}/maps/relaying_stoplist,
	permit
" >> $TMP_FILE
			
			# if we have maildrop, we should use it!
			if [ -n ""$PATH_MAILDROP_BIN -a -f "$PATH_MAILDROP_BIN" ] ; then
				echo "virtual_transport = maildrop" >> $TMP_FILE
				echo "## Set to 1 because Maildrop only delivers one message at a time.
maildrop_destination_recipient_limit = 1" >> $TMP_FILE
			fi

			echo "# End of DTC configuration v0.12 : please don't touch this line !" >> $TMP_FILE

			# now to insert it at the end of the actual main.cf
			cat < $TMP_FILE >>$PATH_POSTFIX_CONF
			rm $TMP_FILE
		fi
		newaliases
	fi
  		# CL: For mac os and debian (probably also other linux) the conf for smtp must go in /usr/lib/sasl2/...
  		# deffined in $PATH_SASLLIB

  		# check if libsql is installed for sasl, else use PAM 
  		# CL: PAM will be removed and replaced by sasl!
  		if [ -f $PATH_SASLLIB/libsql.so ] ; then
  			echoIfVerbose "===> found $PATH_SASLLIB/libsql.so using sasl with sql"
  			PATH_AUTH_SMTP=$PATH_SASLLIB/smtpd.conf
  			PATH_AUTH_SASLPASSWD=$PATH_SASLLIB/saslpasswd.conf
  			echoIfVerbose "===> Adding configuration inside $PATH_SASLLIB"
  			if [ -f $PATH_AUTH_SMTP ] ; then
  				if ! [ -f $PATH_AUTH_SMTP.DTC.backup ] ; then
  					cp -f $PATH_AUTH_SMTP $PATH_AUTH_SMTP.DTC.backup
  				fi #[ -f $PATH_AUTH_SMTP.DTC.backup ] ;
  			fi #[ -f $PATH_AUTH_SMTP ] ;
			if [ "${conf_mysql_host}" = "localhost" ] ; then
				my_smtp_mysql_host="127.0.0.1"
			else
				my_smtp_mysql_host=${conf_mysql_host}
			fi
  			echo "# Configured by DTC v0.25 : Please don't touch this line !
  pwcheck_method: auxprop
  mech_list: plain login digest-md5 cram-md5
  auxprop_plugin: sql
  sql_engine: mysql
  sql_hostnames: ${my_smtp_mysql_host}
  sql_user: dtcdaemons
  sql_passwd: ${MYSQL_DTCDAEMONS_PASS}
  sql_database: ${conf_mysql_db}
  #password_format: crypt
  #sql_select: SELECT crypt FROM pop_access WHERE fullemail = '%u@%r'
  #sql_update: UPDATE pop_access SET crypt = '%v' WHERE fullemail = '%u@%r'
  sql_select: SELECT passwd FROM pop_access WHERE fullemail = '%u@%r'
  sql_update: UPDATE pop_access SET passwd = '%v' WHERE fullemail = '%u@%r'
  sql_verbose: yes
  # End of DTC configuration v0.25 : please don't touch this line !" >${PATH_AUTH_SMTP}

  			if [ -f $PATH_AUTH_SASLPASSWD ] ; then
  				if ! [ -f $PATH_AUTH_SASLPASSWD.DTC.backup ] ; then
  					cp -f $PATH_AUTH_SASLPASSWD $PATH_AUTH_SASLPASSWD.DTC.backup
  				fi #[ -f $PATH_AUTH_SASLPASSWD.DTC.backup ]
  			fi #[ -f $PATH_AUTH_SASLPASSWD ] ;

  			cp -f $PATH_AUTH_SMTP $PATH_AUTH_SASLPASSWD
  			if [ "$UNIX_TYPE" = "debian" ] ; then
  				if [ -e $PATH_POSTFIX_ETC/sasl/smtpd.conf ] ; then
  					mv $PATH_POSTFIX_ETC/sasl/smtpd.conf $PATH_POSTFIX_ETC/sasl/smtpd.conf-remove_by_DTC
  				fi
  				ln -s $PATH_SASLLIB/smtpd.conf $PATH_POSTFIX_ETC/sasl/smtpd.conf 
# 				if [ ! -e /var/spool/postfix/etc/sasldb2 ] ; then
#  					ln -s /etc/sasldb2 /var/spool/postfix/etc/sasldb2
#  				fi
  			fi
  		else
  		  echoIfVerbose "===> ********************************************************** "
  			echoIfVerbose "===> ****** $PATH_SASLLIB/libsql.so NOT found and PAM was removed from the installation, leaving Postfix SASL unconfigured! Please fix me!"
  		  echoIfVerbose "===> ********************************************************** "
  		fi # [ -f $PATH_SASLLIB/libsql.so ]
	# By default, CentOS setup is wrong with maildrop not being SUID
	if [ "$UNIX_TYPE" = "redhat" -a /usr/bin/maildrop ] ; then
		chmod +s /usr/bin/maildrop
	fi
	# Configure dkimproxy_out in CentOS
	if [ "$UNIX_TYPE" = "redhat" -a -f /etc/sysconfig/dkimproxy_out ] ; then
		echo "# options to dkimproxy_out
OPTIONS=\"--domain=\`cat /var/lib/dtc/etc/local_domains | tr \\\\\\r\\\\\\n ,,\`\"
" >/etc/sysconfig/dkimproxy_out
	fi
}

prepareMlmmjSpool () {
	#
	# prepare mlmmj environment to work with dtc
	#
	MLMMJ_TYPE="with.sh"
	if [ -x /usr/bin/mlmmj-make-ml ] ; then
		TMP_MLMMJ_PATH=/usr/bin/mlmmj-make-ml
		MLMMJ_TYPE="no.sh"
	else
		if [ -x "/usr/bin/mlmmj-make-ml.sh" ] ; then
			TMP_MLMMJ_PATH=/usr/bin/mlmmj-make-ml.sh
		else
			if [ -x "${LOCALBASE}/bin/mlmmj-make-ml" ] ; then
				TMP_MLMMJ_PATH=${LOCALBASE}/bin/mlmmj-make-ml
				MLMMJ_TYPE="no.sh"
			else
				if [ -x "${LOCALBASE}/bin/mlmmj-make-ml.sh" ] ; then
					TMP_MLMMJ_PATH=${LOCALBASE}/bin/mlmmj-make-ml.sh
				else
					TMP_MLMMJ_PATH=`which mlmmj-make-ml.sh`
					if [ -z "${TMP_MLMMJ_PATH}" ] ; then
						TMP_MLMMJ_PATH=`which mlmmj-make-ml`
						if ! [ -z "${TMP_MLMMJ_PATH}" ] ; then
							MLMMJ_TYPE="no.sh"
						fi
					fi
				fi
			fi
		fi
	fi

	if ! [ -z "${TMP_MLMMJ_PATH}" ]
	then

		echoIfVerbose "===> Detected presence of mlmmj... prepping environment..."
		# Debian like case
		if [ ${MLMMJ_TYPE} -o "no.sh" ] ; then
			# symlink the .sh to the non .sh, for the genfiles 
			TMP_MLMMJ_PATH_NOSH=`dirname $TMP_MLMMJ_PATH`/`basename $TMP_MLMMJ_PATH .sh`
			if [ ! -e $TMP_MLMMJ_PATH_NOSH ] ; then
				echo "Symlinking mlmmj-make-ml.sh to mlmmj-make-ml"
				ln -s $TMP_MLMMJ_PATH $TMP_MLMMJ_PATH_NOSH
			fi
		fi
		MLMMJ_LIST_PATH=/etc/mlmmj/lists
		mkdir -p $MLMMJ_LIST_PATH
		chown -R root:${CONF_DTC_SYSTEM_GROUPNAME} $MLMMJ_LIST_PATH
		chmod -R g+w $MLMMJ_LIST_PATH
	
		# create mlmmj spool directory if it doesn't exist yet
		if [ ! -e /var/spool/mlmmj/ ] ; then
			mkdir -p /var/spool/mlmmj
		fi
		if [ -e /var/spool/mlmmj/ ] ; then
			chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} /var/spool/mlmmj/
		fi
	fi
}

modifyCourierConfig () {
	# Activate courier in rc.conf on FreeBSD
	if [ $UNIX_TYPE = freebsd ] ; then
		echo "Checking activation of Courier Daemons"
		if grep "Configured by DTC" /etc/rc.conf >/dev/null ; then
			# Configured already echoed
			echo -n ""
		else
			echo "### Configured by DTC 0.31 - please do not remove" >>/etc/rc.conf
		fi
		if grep courier_authdaemond /etc/rc.conf >/dev/null ; then
			# Authdaemon already activated
			echo -n ""
		else
			echo "courier_authdaemond_enable=\"YES\"" >>/etc/rc.conf
		fi
		if grep courier_imap_pop3d_enable /etc/rc.conf >/dev/null ; then
			# pop3d already activated
			echo -n ""
		else
			echo "courier_imap_pop3d_enable=\"YES\"" >>/etc/rc.conf
		fi
		if grep courier_imap_imapd_enable /etc/rc.conf >/dev/null ; then
			# imapd already activated
			echo -n ""
		else
			echo "courier_imap_imapd_enable=\"YES\"" >>/etc/rc.conf
		fi

		if grep courier_imap_pop3d_ssl /etc/rc.conf >/dev/null ; then
			# pop3d_ssl already activated
			echo -n ""
		else
			echo "courier_imap_pop3d_ssl_enable=\"YES\"" >>/etc/rc.conf
		fi

		if grep courier_imap_imapd_ssl /etc/rc.conf >/dev/null ; then
			# imapd_ssl already activated
			echo -n ""
		else
			echo "courier_imap_imapd_ssl_enable=\"YES\"" >>/etc/rc.conf
		fi
	fi
	# check to see if we have a userdb FILE, rather than a FOLDER, rm -r if any folder...
	if [ -d "/etc/authlib" ] ; then
		COURIER_FOLDER="/etc/authlib"
	elif [ -d "/usr/local/etc/courier" ] ; then
		COURIER_FOLDER="/usr/local/etc/courier"
	elif [ -d "/usr/local/etc/authlib" ] ; then
		COURIER_FOLDER="/usr/local/etc/authlib"
	else
		COURIER_FOLDER="/etc/courier"
	fi

	if [ -d "$COURIER_FOLDER" ] ; then
		if [ ! -f /etc/courier/userdb ] ; then
			# rm the userdb because it could be a folder in previous installs...
			rm -rf $COURIER_FOLDER/userdb
			touch $COURIER_FOLDER/userdb
		fi
		chown ${CONF_DTC_SYSTEM_USERNAME} $COURIER_FOLDER/userdb
		chmod 600 $COURIER_FOLDER/userdb
	fi

	if [ ! -e ${COURIER_FOLDER}/quotawarnmsg ] ; then
		# if we don't have $PATH_DTC_ETC yet, create it
                if [ ! -e $PATH_DTC_ETC ]; then
                        mkdir -p $PATH_DTC_ETC
                fi
		# if we don't have a COURIER folder yet, create it
                if [ ! -e ${COURIER_FOLDER} ]; then
                        mkdir -p ${COURIER_FOLDER}
                fi
		# don't relink this if it exists already
		if [ ! -h $PATH_DTC_ETC/quotawarnmsg ]; then
                        ln -s ${COURIER_FOLDER}/quotawarnmsg $PATH_DTC_ETC/quotawarnmsg
                fi
		# finally add the quota warning message
		if [ ! -e $PATH_DTC_ETC/quotawarnmsg ] ; then
			echo "From: Mail Delivery System <postmaster@${main_domain_name}>
Reply-To: postmaster@${main_domain_name}
To: Valued Customer:;
Subject: Mail quota warning
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 7bit

Your mailbox on the server is now more than 90% full. So that you can
continue to receive mail you need to remove some messages from your
mailbox. Note that the reason for being over quota could be that you
are reaching the maximum number of messages (max file limitation) or
that your overall mailbox size is reached. If you are unsure, ask your
mail server administrator about it.

" >$PATH_DTC_ETC/quotawarnmsg
		fi
	fi

	#
	# Install courier mysql authenticaion
	#
	if [ -f "$PATH_COURIER_AUTHD_CONF_PATH/authdaemonrc" ] ; then
		echoIfVerbose "===> Adding directives to Courier authdaemonrc"
		if grep "Configured by DTC" $PATH_COURIER_AUTHD_CONF_PATH/authdaemonrc >/dev/null
		then
			echoIfVerbose "authdaemonrc has been configure before: skipping include insertion !"
		else
			echoIfVerbose "Inserting DTC configuration inside "$PATH_COURIER_AUTHD_CONF_PATH/authdaemonrc
			if ! [ -f $PATH_COURIER_AUTHD_CONF_PATH.DTC.backup ]
			then
				cp -f $PATH_COURIER_AUTHD_CONF_PATH/authdaemonrc $PATH_COURIER_AUTHD_CONF_PATH/authdaemonrc.DTC.backup
				cp -f $PATH_COURIER_AUTHD_CONF_PATH/authmysqlrc $PATH_COURIER_AUTHD_CONF_PATH/authmysqlrc.DTC.backup
			fi
			TMP_FILE=`${MKTEMP} DTC_install.courier.conf.XXXXXX` || exit 1
			echo "# Configured by DTC v0.12 : Please don't touch this line !" > $TMP_FILE
			echo "authmodulelist=\"authmysql authpam\"" >> $TMP_FILE
			echo "# End of DTC configuration v0.12 : please don't touch this line !" >> $TMP_FILE
			# now append this to the existing configuration file
			cat < $TMP_FILE >> $PATH_COURIER_AUTHD_CONF_PATH/authdaemonrc
			rm $TMP_FILE
			echo "
# DB details for dtc mysql DB
MYSQL_SERVER		$conf_mysql_host
MYSQL_PORT		3306
MYSQL_DATABASE		$conf_mysql_db
MYSQL_USERNAME		dtcdaemons
MYSQL_PASSWORD		${MYSQL_DTCDAEMONS_PASS}
MYSQL_USER_TABLE        pop_access
MYSQL_LOGIN_FIELD       id
MYSQL_CRYPT_PWFIELD     crypt
MYSQL_HOME_FIELD        home
MYSQL_UID_FIELD         uid
MYSQL_GID_FIELD         gid
MYSQL_QUOTA_FIELD       quota_couriermaildrop
MYSQL_DEFAULT_DOMAIN    $main_domain_name

# use the experimental query
MYSQL_SELECT_CLAUSE     SELECT concat(id, '@', mbox_host), crypt, passwd, uid, gid, home, '', quota_couriermaildrop, ''  FROM pop_access  WHERE ( (id = '\$(local_part)' AND mbox_host = '\$(domain)') OR (id = SUBSTRING_INDEX('\$(local_part)', '%', 1) AND mbox_host = SUBSTRING_INDEX('\$(local_part)', '%', -1)) ) AND active = '1'
# We now use a query that checks if the account is expired, so this way, pop and imap access
# are disabled for expired accounts! :)
#MYSQL_SELECT_CLAUSE     SELECT concat(pop_access.id, '@', mbox_host), crypt, passwd, uid, gid, home, '', quota_couriermaildrop, ''  FROM pop_access,domain,admin  WHERE ( (pop_access.id = '\$(local_part)' AND mbox_host = '\$(domain)') OR (pop_access.id = SUBSTRING_INDEX('\$(local_part)', '%', 1) AND mbox_host = SUBSTRING_INDEX('\$(local_part)', '%', -1)) ) AND active = '1' AND domain.name=pop_access.mbox_host AND domain.owner=admin.adm_login AND admin.expire > now()

MYSQL_CHPASS_CLAUSE     UPDATE pop_access SET passwd='\$(newpass)', crypt='\$(newpass_crypt)' WHERE (id = '\$(local_part)' AND mbox_host = '\$(domain)') OR (id = SUBSTRING_INDEX('\$(local_part)', '%', 1)  AND mbox_host = SUBSTRING_INDEX('\$(local_part)', '%', -1))
" > $PATH_COURIER_AUTHD_CONF_PATH/authmysqlrc
			if [ ""$UNIX_TYPE = freebsd ] ; then
				restartDaemonMultiUnix courier-authdaemond
				restartDaemonMultiUnix courier-imap-imapd
				restartDaemonMultiUnix courier-imap-imapd-ssl
				restartDaemonMultiUnix courier-imap-pop3d
				restartDaemonMultiUnix courier-imap-pop3d-ssl
			else
				restartDaemonMultiUnix courier-authdaemon
				restartDaemonMultiUnix courier-authlib
				restartDaemonMultiUnix courier-imap
				restartDaemonMultiUnix courier-imap-ssl
				restartDaemonMultiUnix courier-pop
				restartDaemonMultiUnix courier-pop-ssl
			fi
		fi	
	fi

	# need to remove the paths for courier in /etc/profile.d/
	# since the MTA really breaks postfix paths and handling
	if [ -e /etc/profile.d/courier.sh ] ; then
		mv /etc/profile.d/courier.sh /etc/profile.d/courier.sh.DTC.disabled
	fi

	if [ -e /etc/profile.d/courier.csh ] ; then
		mv /etc/profile.d/courier.csh /etc/profile.d/courier.csh.DTC.disabled
	fi
}

modifyDovecotConfig () {
	#
	# Install dovecot mysql authenticaion
	#
	if [ -f $PATH_DOVECOT_CONF ]
	then
		echoIfVerbose "Detecting dovecot version..."
		DOVECOT_VERSION=`dovecot --version`
		DOVECOT_POSTONE=false
		case $DOVECOT_VERSION in
			1.*)
				echoIfVerbose "Found version 1.0 or greater"
				DOVECOT_POSTONE=true
				;;
			0.*)
				echoIfVerbose "Found pre 1.0 version"
				;;

		esac
		DOVECOT_MAJOR=`echo $DOVECOT_VERSION | cut -f1 -d"."`
		DOVECOT_MINOR=`echo $DOVECOT_VERSION | cut -f2 -d"."`
		DOVECOT_RELEASE=`echo $DOVECOT_VERSION | cut -f3 -d"."`
		echoIfVerbose "===> Adding directives to dovecot.conf"
		DOVECOT_CONF_OK="no"
		if [ -f "${PATH_DOVECOT_CONF}" ] ; then
			if grep -q "Configured by DTC" $PATH_DOVECOT_CONF >/dev/null; then
				DOVECOT_CONF_OK="yes"
			fi
		fi
		if [ ${DOVECOT_CONF_OK} = "yes" ] ; then
			echoIfVerbose "dovecot.conf has been configure before: skipping include insertion !"
		else
			if [ ""$DOVECOT_POSTONE ] ; then
				echoIfVerbose "Version 1.x needs a new config file... replacing existing"
				if ! [ -f $PATH_DOVECOT_CONF.DTC.backup ] ; then
					cp -f $PATH_DOVECOT_CONF $PATH_DOVECOT_CONF.DTC.backup
				fi
				if [ "${DOVECOT_MAJOR}" -ge 1 -a "${DOVECOT_MINOR}" -ge 1 ] ; then
					dovecot_env_directive="mail_location"
				else
					dovecot_env_directive="default_mail_env"
				fi
				if [ ""$conf_gen_ssl_cert = "true" ] ; then
					DOVECOT_SSL_CERT_CONF="## SSL settings
ssl_cert_file = $PATH_DTC_ETC/ssl/dovecot/new.cert.cert
ssl_key_file = $PATH_DTC_ETC/ssl/dovecot/new.cert.key
#ssl_ca_file = 
#ssl_verify_client_cert = no
#ssl_parameters_regenerate = 168
#ssl_cipher_list = ALL:!LOW:!SSLv2
#verbose_ssl = no"
				else
					DOVECOT_SSL_CERT_CONF=""
				fi
				echo "
# Configured by DTC v0.x : Please don't touch this line !
protocols = imap imaps pop3 pop3s
${dovecot_env_directive} = maildir:%h/Maildir
pop3_uidl_format = %08Xu%08Xv
maildir_copy_with_hardlinks = yes
disable_plaintext_auth= no
protocol imap {
    mail_plugins = quota imap_quota
}
protocol pop3 {
    mail_plugins = quota
}
auth default {
  mechanisms = plain
#  passdb pam {
#    args = \"*\"
#  }
#  userdb passwd {
#  }
  user = root
  # use prefetch for pass+user homedir in 1 query, faster. see dovecot-mysql.conf
  userdb prefetch {
  }
  # order of ops important. passdb before userdb. this userdb here only for delivery.
  userdb sql {
    args = $PATH_DTC_ETC/dovecot-mysql.conf
  }
  passdb sql {
    args = $PATH_DTC_ETC/dovecot-mysql.conf
  }
  socket listen {
    master {
      path = /var/run/dovecot-auth-master
      # WARNING: Giving untrusted users access to master socket may be a
      # security risk, don't give too wide permissions to it!
      mode = 0600
      # Default user/group is the one who started dovecot-auth (root)
      #user =
      #group =
    }
    client {
      path = /var/run/dovecot/dovecot-auth-client
      mode = 0666
    }
  }
}
plugin {
}
${DOVECOT_SSL_CERT_CONF}
# End of DTC configuration v0.x : please don't touch this line !
" > $PATH_DOVECOT_CONF
			else
				echoIfVerbose "Inserting DTC configuration inside "$PATH_DOVECOT_CONF
				if ! [ -f $PATH_DOVECOT_CONF.DTC.backup ]
				then
					cp -f $PATH_DOVECOT_CONF $PATH_DOVECOT_CONF.DTC.backup
				fi
				TMP_FILE=`${MKTEMP} DTC_install.dovecot.conf.XXXXXX` || exit 1
				echo "# Configured by DTC v0.12 : Please don't touch this line !" > $TMP_FILE
				echo "auth_userdb = mysql $PATH_DTC_ETC/dovecot-mysql.conf" >> $TMP_FILE
				echo "auth_passdb = mysql $PATH_DTC_ETC/dovecot-mysql.conf" >> $TMP_FILE
				echo "# End of DTC configuration v0.12 : please don't touch this line !" >> $TMP_FILE 
				# now append this to the existing configuration file
				cat < $TMP_FILE >> $PATH_DOVECOT_CONF
				rm  $TMP_FILE
			fi
			if [ ""$DOVECOT_POSTONE ] ; then
				if [ "${conf_mysql_host}" = "localhost" ] ; then
					DOVECOT_MYSQL="${MYSQL_DB_SOCKET_PATH}"
				else
					DOVECOT_MYSQL="${conf_mysql_host} port=3306"
				fi
				# there is a new configuration for 1.0.x
				echo "
connect = host=$DOVECOT_MYSQL dbname=$conf_mysql_db user=dtcdaemons password=${MYSQL_DTCDAEMONS_PASS} client_flags=0
driver = mysql
default_pass_scheme = PLAIN
password_query = SELECT passwd AS password FROM pop_access WHERE id = '%n' AND mbox_host = '%d'
user_query = SELECT home, uid, gid FROM pop_access WHERE id = '%n' AND mbox_host = '%d'
" > $PATH_DTC_ETC/dovecot-mysql.conf
			else
				echo "
# DB details for dtc mysql DB
connect = host=${MYSQL_DB_SOCKET_PATH} port=3306 dbname=$conf_mysql_db user=dtcdaemons password=${MYSQL_DTCDAEMONS_PASS}
driver = mysql
default_pass_scheme = PLAIN
password_query = SELECT passwd AS password, home as userdb_home, uid as userdb_uid, gid as userdb_gid FROM pop_access WHERE id = '%n' AND mbox_host = '%d'
user_query = SELECT home, uid, gid FROM pop_access WHERE id = '%n' AND mbox_host = '%d'
db_client_flags = 0
" > $PATH_DTC_ETC/dovecot-mysql.conf
			fi
			# keys may need to be regenerated even if we have fixed the dovecot config
			# Generate the OpenSSL test certificate if it does not exists - for dovecot this time: KC
			if [ ""$conf_gen_ssl_cert = "true" ] ; then
				echoIfVerbose "generating dovecot ssl keys... please wait..."
				if [ ! -e $PATH_DTC_ETC"/ssl/dovecot" ] ; then
					mkdir -p $PATH_DTC_ETC"/ssl/dovecot"
				fi
				DOVCERT_CWD=`pwd`
				cd $PATH_DTC_ETC"/ssl/dovecot"
				export RANDFILE=`${MKTEMP} ssl_randfile.XXXXXX` || exit 2	# openSSL requires a writeable $RANDFILE or $HOME/.rnd, this ensures: KC
				if ! [ -e "./"new.cert.csr -o -e "./"new.cert.cert -o -e "./"new.cert.key ] ; then
					CERTPASS_TMP_FILE=`${MKTEMP} certfilepass.XXXXXX` || exit 2
					echo $conf_gen_ssl_cert"" >$CERTPASS_TMP_FILE
					echoIfVerbose " - generating cert signing request.."
					( ( echo $conf_cert_countrycode;
						echo $conf_cert_statecode;
						echo $conf_cert_locality;
						echo $conf_cert_organization;
						echo $conf_cert_unit;
						echo $dtc_admin_subdomain"."$main_domain_name;
						echo $conf_cert_email;
						echo $conf_cert_challenge_pass;
						echo $conf_cert_organization; ) | openssl req -passout file:$CERTPASS_TMP_FILE -new > new.cert.csr ) || 
							(echo " * Problem generating certificate signing request. If you continue your connections may be insecure." 1>&2 &&
							 exit 2)
						echo
					echoIfVerbose " - generating certificate key.."
					openssl rsa -passin file:$CERTPASS_TMP_FILE -in privkey.pem -out new.cert.key  ||
						(echo " * Problem generating certificate key. If you continue your connections may be insecure." 1>&2 &&
						 exit 2)
					echo
					echoIfVerbose " - signing cert with key.. "
					openssl x509 -in new.cert.csr -out new.cert.cert -req -signkey new.cert.key -days 3650 ||
						(echo " * Problem signing certificate key. If you continue your connections may be insecure." 1>&2 &&
						 exit 2)
					echo
					rm $CERTPASS_TMP_FILE $RANDFILE
				fi
				cd ${DOVCERT_CWD}
			fi
			restartDaemonMultiUnix dovecot
		fi	
	fi
}

modifyPureFtpdMySQLConfig () {
	#
	# Install pure-ftpd-mysql
	#
	echoIfVerbose "===> Adding directives to pure-ftpd-mysql"
	# FreeBSD has a file pure-ftpd.conf to configure pure-ftpd
	# It has to be tested like that because Debian don't have $conf_ftp_type and it
	# will never have: it just tests for the directory existance...
	if [ "$UNIX_TYPE" = "freebsd" -a ""$conf_ftp_type = "pureftpd" ] ; then
		if [ ! -f "/usr/local/etc/pure-ftpd.conf" ] ; then
			sed -e "/^# MySQLConfigFile/d" /usr/local/etc/pure-ftpd.conf.sample > /usr/local/etc/pure-ftpd.conf
			echo "MySQLConfigFile		/usr/local/etc/pureftpd-mysql.conf" >> /usr/local/etc/pure-ftpd.conf
		fi
		if [ ! -f "/usr/local/etc/pureftpd-mysql.conf" ] ; then
			echo "# Configured by DTC v0.10 : Please don't touch this line !

MYSQLSocket /tmp/mysql.sock
MYSQLUser dtcdaemons
MYSQLPassword ${MYSQL_DTCDAEMONS_PASS}
MYSQLDatabase $conf_mysql_db
MYSQLCrypt cleartext
MYSQLGetPW      SELECT password FROM ftp_access WHERE login=\"\L\"
MYSQLGetUID     SELECT uid FROM ftp_access WHERE login=\"\L\"
MYSQLGetGID     SELECT gid FROM ftp_access WHERE login=\"\L\"
MYSQLGetDir     SELECT homedir FROM ftp_access WHERE login=\"\L\"

" >/usr/local/etc/pureftpd-mysql.conf;
		fi

		if grep 'pureftpd_enable="YES"' /etc/rc.conf >/dev/null ; then
			echoIfVerbose "rc.conf already has pureftpd_enable=yes"
		else
			echoIfVerbose "Adding pureftpd_enable=yes in rc.conf"
			echo 'pureftpd_enable="YES"' >> /etc/rc.conf
		fi

		/usr/local/etc/rc.d/pure-ftpd start
	else	
		PURE_FTPD_ETC="/etc/pure-ftpd"
		if [ -e $PURE_FTPD_ETC ] ; then
			if [ "$UNIX_TYPE" = "redhat" -a ""$conf_ftp_type = "pureftpd" ] ; then
				# This will activate the MySQL config in CentOS.
				# FIXME: This also removes some useful comments, so it's not optimum
				TMP_FILE=`${MKTEMP} DTC_pure-ftpd.conf.XXXXXX` || exit 1
				grep -v MySQLConfigFile ${PATH_PUREFTPD_CONF} | grep -v MinUID >${TMP_FILE}
				echo "MinUID 100" >>${TMP_FILE}
				echo "MySQLConfigFile /etc/pure-ftpd/pureftpd-mysql-dtc.conf" >>${TMP_FILE}
				cat <${TMP_FILE} >${PATH_PUREFTPD_CONF}
				rm -f ${TMP_FILE}
			fi
			if [ -e /etc/pure-ftpd/conf/ ] ; then
				echo "yes" >/etc/pure-ftpd/conf/ChrootEveryone
			fi

			# Debian uses a directory structure with many files (and maybe other distro)
			PURE_DBCONFIG_FILE=""
			if [ -e $PURE_FTPD_ETC/db/ ] ; then
				PURE_DBCONFIG_FILE=$PURE_FTPD_ETC/db/mysql.conf
			else
				PURE_DBCONFIG_FILE=$PURE_FTPD_ETC/pureftpd-mysql-dtc.conf
			fi
			echo "# Configured by DTC v0.10 : Please don't touch this line !

MYSQLServer $conf_mysql_host
MYSQLUser dtcdaemons
MYSQLPassword ${MYSQL_DTCDAEMONS_PASS}
MYSQLDatabase $conf_mysql_db
MYSQLCrypt cleartext
MYSQLGetPW      SELECT password FROM ftp_access WHERE login=\"\L\"
MYSQLGetUID     SELECT uid FROM ftp_access WHERE login=\"\L\"
MYSQLGetGID     SELECT gid FROM ftp_access WHERE login=\"\L\"
MYSQLGetDir     SELECT homedir FROM ftp_access WHERE login=\"\L\"

" >${PURE_DBCONFIG_FILE}
			# If running in Debian, try to determine if using standalone or daemon
			if [ "$UNIX_TYPE" = "debian" -o -f /etc/default/pure-ftpd-common ] ; then
				PURE_DEFAULT_FILE=`cat /etc/default/pure-ftpd-common | grep STANDALONE_OR_INETD= | cut -d= -f2`
				if [ ${PURE_DEFAULT_FILE} = "standalone" ] ; then
					restartDaemonMultiUnix pure-ftpd-mysql
				fi
			else
				restartDaemonMultiUnix pure-ftpd-mysql
				restartDaemonMultiUnix pure-ftpd
			fi
		fi
	fi
}

configProftpd () {
	echoIfVerbose "===> Customizing proftpd.conf"
	#
	# Install proftpd.conf to access to the database
	#
	if [ -f $PATH_PROFTPD_CONF ] ; then
		if [ $UNIX_TYPE = freebsd ] ; then
			if grep proftpd_enable /etc/rc.conf >/dev/null
			then
				echoIfVerbose "===> proftpd already activated"
			else
				echoIfVerbose "===> Activating proftpd in /etc/rc.conf"
				echo "proftpd_enable=\"YES\"" >>/etc/rc.conf
			fi
		fi
		echoIfVerbose "===> Adding directives to proftpd.conf"
		PATH_PROFTPD_DIR=`dirname $PATH_PROFTPD_CONF`
		if ! [ `basename $PATH_PROFTPD_DIR` = proftpd ] ; then
			PATH_PROFTPD_DIR=$PATH_PROFTPD_DIR/proftpd
		fi
		mkdir -p $PATH_PROFTPD_DIR
		if grep "Configured by DTC" $PATH_PROFTPD_CONF >/dev/null ; then
			echoIfVerbose "proftpd.conf has been configured before : skipping include inssertion !"
		else
			echoIfVerbose "Inserting DTC configuration inside "$PATH_PROFTPD_CONF
			if ! [ -f $PATH_PROFTPD_CONF.DTC.backup ] ; then
				cp -f $PATH_PROFTPD_CONF $PATH_PROFTPD_CONF.DTC.backup
			fi

			# Generate the OpenSSL test certificate if it does not exists
			if [ ""$conf_gen_ssl_cert = "true" ] ; then
				if [ ! -e $PATH_DTC_ETC"/ssl" ] ; then
					mkdir -p $PATH_DTC_ETC"/ssl"
				fi
				if [ ! -e $PATH_DTC_ETC"/ssl/proftpd" ] ; then
					 mkdir -p $PATH_DTC_ETC"/ssl/proftpd"
				fi
				cwd=`pwd`
				cd $PATH_DTC_ETC"/ssl/proftpd"
				if [ ! -e "./"new.cert.csr ] ; then
					if [ ! -e "./"new.cert.cert ] ; then
						if [ ! -e "./"new.cert.key ] ; then
							CERTPASS_TMP_FILE=`${MKTEMP} certfilepass.XXXXXX` || exit 1
							echo $conf_gen_ssl_cert"" >$CERTPASS_TMP_FILE
							( echo $conf_cert_countrycode;
								echo $conf_cert_statecode;
								echo $conf_cert_locality;
								echo $conf_cert_organization;
								echo $conf_cert_unit;
								echo $dtc_admin_subdomain"."$main_domain_name;
								echo $conf_cert_email;
								echo $conf_cert_challenge_pass;
								echo $conf_cert_organization; ) | openssl req -passout file:$CERTPASS_TMP_FILE -new > new.cert.csr
							openssl rsa -passin file:$CERTPASS_TMP_FILE -in privkey.pem -out new.cert.key
							openssl x509 -in new.cert.csr -out new.cert.cert -req -signkey new.cert.key -days 3650
							rm $CERTPASS_TMP_FILE
						fi
					fi
				fi
				cd $cwd
			fi

			# need to comment out any existing AuthOrder, since we are changing it
			perl -i -p -e 's/AuthOrder/#AuthOrder/' $PATH_PROFTPD_CONF

			TMP_FILE=`${MKTEMP} DTC_install.proftp.conf.XXXXXX` || exit 1
			echo "# Configured by DTC v0.30 : Please don't touch this line !" > $TMP_FILE
			echo "AuthOrder		mod_sql.c mod_auth_pam.c mod_auth_unix.c" >> $TMP_FILE
			echo "IdentLookups	off" >> $TMP_FILE
			echo "DefaultRoot	~" >> $TMP_FILE
			echo "Include $PATH_PROFTPD_DIR/sql-dtc.conf" >> $TMP_FILE
			echo "Include $PATH_PROFTPD_DIR/tls-dtc.conf" >> $TMP_FILE
			echo "# End of DTC configuration v0.30 : please don't touch this line !" >> $TMP_FILE
			TMP_FILE_TLS=`${MKTEMP} DTC_install.proftp.conf.tls.XXXXXX` || exit 1
			if [ -e $PATH_DTC_ETC"/ssl/proftpd/new.cert.cert" ] ; then
				if [ -e $PATH_DTC_ETC"/ssl/proftpd/new.cert.key" ] ; then
					if [ ""$conf_gen_ssl_cert = "true" ] ; then
						echo "# This is the TLS auth support. Thanks to Erwan Gurcuff (gort) for the tip!
<IfModule mod_tls.c>
	TLSEngine on
	TLSLog /var/log/proftpd-tls.log
	TLSProtocol TLSv1
	TLSRequired off
	TLSRSACertificateFile "$PATH_DTC_ETC"/ssl/proftpd/new.cert.cert
	TLSRSACertificateKeyFile "$PATH_DTC_ETC"/ssl/proftpd/new.cert.key
	TLSVerifyClient on
</IfModule>" >> $TMP_FILE_TLS
					fi
				fi
			fi
			TMP_FILE_SQL=`${MKTEMP} DTC_install.proftp.conf.sql.XXXXXX` || exit 1
			echo "<IfModule mod_sql.c>" > $TMP_FILE_SQL
			echo "SQLAuthenticate	on" >> $TMP_FILE_SQL
			echo "SQLConnectInfo	"$conf_mysql_db"@"$conf_mysql_host" dtcdaemons "${MYSQL_DTCDAEMONS_PASS} >> $TMP_FILE_SQL
			echo "SQLAuthTypes	Plaintext Crypt" >> $TMP_FILE_SQL
			echo "SQLUserInfo	ftp_access login password uid gid homedir shell" >> $TMP_FILE_SQL
			echo "# // Transfer Log to Proftpd
SQLLog RETR,STOR transfer1
SQLNamedQuery transfer1 INSERT \"'%u', '%f', '%b', '%h', '%a', '%m', '%T',now(), 'c', NULL\" ftp_logs

# // Count Logins per User
SQLLog                PASS logincount
SQLNamedQuery         logincount UPDATE \"count=count+1 WHERE login='%u'\" ftp_access

# // Remember the last login time
SQLLog                PASS lastlogin
SQLNamedQuery         lastlogin UPDATE \"last_login=now() WHERE login='%u'\" ftp_access

# // Count the downloaded bytes
SQLLog RETR           dlbytescount
SQLNamedQuery         dlbytescount UPDATE \"dl_bytes=dl_bytes+%b WHERE login='%u'\" ftp_access

# // Count the downloaded files
SQLLog RETR           dlcount
SQLNamedQuery         dlcount UPDATE \"dl_count=dl_count+1 WHERE login='%u'\" ftp_access

# // Count the uploaded bytes
SQLLog STOR           ulbytescount
SQLNamedQuery         ulbytescount UPDATE \"ul_bytes=ul_bytes+%b WHERE login='%u'\" ftp_access

# // Count the uploaded files
SQLLog STOR           ulcount
SQLNamedQuery         ulcount UPDATE \"ul_count=ul_count+1 WHERE login='%u'\" ftp_access
" >> $TMP_FILE_SQL
			if [ ${CONF_DTC_SYSTEM_GID} -lt 1000 ] ; then
				echo "SQLMinUserGID 50" >>$TMP_FILE_SQL
			fi
			if [ ${CONF_DTC_SYSTEM_UID} -lt 1000 ] ; then
				echo "SQLMinUserUID 50" >>$TMP_FILE_SQL
			fi
			echo "</IfModule>" >>$TMP_FILE_SQL

			cat < $TMP_FILE >>$PATH_PROFTPD_CONF
			mv $TMP_FILE_TLS $PATH_PROFTPD_DIR/tls-dtc.conf
			mv $TMP_FILE_SQL $PATH_PROFTPD_DIR/sql-dtc.conf
			rm $TMP_FILE
			# This restarts proftpd if under debian like system
			# work has to be done under other OS to restart the ftp daemon
			restartDaemonMultiUnix proftpd
		fi
	fi
}

configFreeRadius () {
	#
	# Install and configuration of FreeRadius 1.0
	#
	if [ -e ""$FREERADIUS_ETC ] ; then 
		echoIfVerbose "DTC has found you are using Freeradius and it's now configuring it" 

		FREERADIUS_CONF=$FREERADIUS_ETC/radiusd.conf  
		FREERADIUS_SQL_DOT_CONF=$FREERADIUS_ETC/sql.conf 
		FREERADIUS_SITE_ENABLED_CONF=$FREERADIUS_ETC/sites-enabled/default

		if [ $UNIX_TYPE = freebsd ] ; then
			if grep "Configured by DTC" /etc/rc.conf >/dev/null ; then
				# rc.conf already spammed
				echo -n ""
			else
				echo "### Configured by DTC 0.31 - please do not remove" >>/etc/rc.conf
			fi

			if grep radiusd_enable /etc/rc.conf >/dev/null ; then
				echo "Freeradius already activated in rc.conf"
			else
				echo "Activating freeradius on /etc/rc.conf"
				echo "radiusd_enable=\"YES\"" >>/etc/rc.conf
			fi
		fi


		# Backup of freeradius config files
		if [ -e $FREERADIUS_CONF ] ; then
			if ! [ -e $FREERADIUS_CONF".DTCbackup" ] ; then
				cp $FREERADIUS_CONF $FREERADIUS_CONF".DTCbackup"
			fi
		fi

		if [ -e $FREERADIUS_SQL_DOT_CONF ] ; then
			if ! [ -e $FREERADIUS_SQL_DOT_CONF".DTCbackup" ] ; then
				cp $FREERADIUS_SQL_DOT_CONF $FREERADIUS_SQL_DOT_CONF".DTCbackup"
			fi
		fi

		if [ -e $FREERADIUS_SITE_ENABLED_CONF ] ; then
			if ! [ -e $FREERADIUS_SITE_ENABLED_CONF".DTCbackup" ] ; then
				cp $FREERADIUS_SITE_ENABLED_CONF $FREERADIUS_SITE_ENABLED_CONF".DTCbackup"
			fi
		fi

		TMP_FILE=`${MKTEMP} DTC_install.radius.conf.XXXXXX` || exit 1
		TMP_FILE2=`${MKTEMP} DTC_install.radius.conf.XXXXXX` || exit 1

		if [ -e /var/log/radacct ] ; then
			chown -R ${CONF_DTC_SYSTEM_USERNAME} /var/log/radacct
			chmod -R 770 /var/log/radacct
		fi

		sed "s/#user = nobody/user = nobody/" $FREERADIUS_CONF >$TMP_FILE
		if grep "group = nobody" $TMP_FILE >/dev/null ; then
			sed "s/#group = nobody/group = nobody/" $TMP_FILE >$TMP_FILE2
		else
			sed "s/#group = nogroup/group = nogroup/" $TMP_FILE >$TMP_FILE2
		fi
		sed "s/auth = no/auth = yes/" $TMP_FILE2 >$TMP_FILE
		sed "s/auth_badpass = no/auth_badpass = yes/" $TMP_FILE >$TMP_FILE2
		sed "s/auth_goodpass = no/auth_goodpass = yes/" $TMP_FILE2 >$TMP_FILE
		sed "s/#	sql$/       sql/" $TMP_FILE >$TMP_FILE2 
		sed "s/#	\$INCLUDE sql/	\$INCLUDE sql/" $TMP_FILE2 >$TMP_FILE 

		cat <$TMP_FILE >$FREERADIUS_CONF

		rm $TMP_FILE $TMP_FILE2

		echoIfVerbose "===> Adding directives to sql.conf"

		if grep "Configured by DTC" $FREERADIUS_SQL_DOT_CONF >/dev/null
		then
	                echoIfVerbose "sql.conf has been configured before : skipping include inssertion !"
		else
	                echoIfVerbose "Inserting DTC configuration inside "$FREERADIUS_SQL_DOT_CONF

		        TMP_FILE1=`${MKTEMP} DTC_install.sql.conf.XXXXXX` || exit 1
		        TMP_FILE2=`${MKTEMP} DTC_install.sql.conf.XXXXXX` || exit 1

			# Remove the default config
			grep -v "server =" $FREERADIUS_SQL_DOT_CONF >$TMP_FILE1
			grep -v "login =" $TMP_FILE1 >$TMP_FILE2
			grep -v "password =" $TMP_FILE2 >$TMP_FILE1
			grep -v "radius_db = " $TMP_FILE1 >$TMP_FILE2
			grep -v "readclients *=" $TMP_FILE2 >$TMP_FILE1
			grep -v "read_groups *=" $TMP_FILE1 >$TMP_FILE2
			grep -v "authcheck_table *=" $TMP_FILE2 >$TMP_FILE1
			grep -v "INCLUDE sql" $TMP_FILE1 >$TMP_FILE2
			grep -v "}$" $TMP_FILE2 >$TMP_FILE1

			# Install the DTC db config
		        echo "# Configured by DTC v0.10 : Please don't touch this line !
        # Connect info
	driver = rlm_sql_mysql
        server = "$conf_mysql_host"
        login = "$conf_mysql_login"
        password = "$conf_mysql_pass"" >> $TMP_FILE1
		        echo "        # Database table configuration
        radius_db = "$conf_mysql_db"
	readclients=yes
	read_groups=yes
	authcheck_table="radcheckview"
        \$INCLUDE sql/\${database}/dialup.conf
# End of DTC configuration v0.10 : please don't touch this line !
}
" >> $TMP_FILE1

			cat <$TMP_FILE1 >$FREERADIUS_SQL_DOT_CONF
			rm $TMP_FILE1 $TMP_FILE2
		fi

		echoIfVerbose "===> Activating sql directives in sites-enabled/default"

		TMP_FILE=`${MKTEMP} DTC_install.sites-enabled.XXXXXX` || exit 1
		TMP_FILE1=`${MKTEMP} DTC_install.sites-enabled.XXXXXX` || exit 1

		sed "s/#	sql$/       sql/" $FREERADIUS_SITE_ENABLED_CONF >$TMP_FILE
		sed "s/	unix$/#       unix/" $TMP_FILE >$TMP_FILE1 
		sed "s/	radutmp$/#       radutmp/" $TMP_FILE1 >$TMP_FILE 

		cat <$TMP_FILE >$FREERADIUS_SITE_ENABLED_CONF
		rm $TMP_FILE $TMP_FILE1

		#Finally start the daemon
	        restartDaemonMultiUnix radiusd
	fi
}

modifyAWStatsConfig () {
	echoIfVerbose "===> Configuring awstats.conf"
	#
	# Generate default config file for awstats (if we have it installed)
	#
	if [ -f $PATH_AWSTATS_ETC/awstats.conf ] ; then
		# now if we don't already have a dtc awstats config, create one based on the installed package config
		if ! [ -f $PATH_AWSTATS_ETC/awstats.dtc.conf ] ; then
			# we will use the environment variables while calling awstats...
			# Parameter="__ENVNAME__"
			cp $PATH_AWSTATS_ETC/awstats.conf $PATH_AWSTATS_ETC/awstats.dtc.conf
			perl -i -p -e 's/^LogFile=\"[^\"]*\"/LogFile=\"__AWSTATS_LOG_FILE__\"/'  $PATH_AWSTATS_ETC/awstats.dtc.conf
			perl -i -p -e 's/^SiteDomain=\"[^\"]*\"/SiteDomain=\"__AWSTATS_FULL_DOMAIN__\"/' $PATH_AWSTATS_ETC/awstats.dtc.conf
			perl -i -p -e 's/^DirData=\"[^\"]*\"/DirData=\"__AWSTATS_DIR_DATA__\"/' $PATH_AWSTATS_ETC/awstats.dtc.conf
			perl -i -p -e 's/^CreateDirDataIfNotExists=0/CreateDirDataIfNotExists=1/' $PATH_AWSTATS_ETC/awstats.dtc.conf
		fi
	fi
}

createRRDFiles () {
	#
	# create the rrd file for queuegraph.cgi
	#
	echoIfVerbose "===> Setting up rrdtools and graphs in \"$PATH_CGIBIN\""
	if [ ! "$UNIX_TYPE" = "osx" ] ; then
		echoIfVerbose "-> Creating mail queue rrd: $PATH_DTC_ADMIN/queuegraph/createrrd.sh $PATH_DTC_ETC"
		if [ ! -e $PATH_DTC_ETC/mailqueues.rrd ] ; then
			$PATH_DTC_ADMIN/queuegraph/createrrd.sh $PATH_DTC_ETC
		fi
		if [ -e $PATH_DTC_ETC/mailqueues.rrd ] ; then
			chmod 770 $PATH_DTC_ETC/mailqueues.rrd
		fi
		# fix path for mailqueues.rrd
	
		if [ -z "$conf_eth2monitor" ] ; then
			echoIfVerbose "No interface selected: skipping the netusage.rrd setup!!!"
		else
			#
			# create the rrd file for netusegraph.cgi
			#
			if [ ! -e $PATH_DTC_ETC/netusage.rrd ] ; then
				echoIfVerbose "-> Creating network statistics rrd file"
				$PATH_DTC_ADMIN/netusegraph/createrrd.sh $PATH_DTC_ETC
			fi

			if [ -e $PATH_DTC_ETC/netusage.rrd ] ; then
				chmod 775 $PATH_DTC_ETC/netusage.rrd
			fi
		fi
		#
		# create the rrd file for cpugraph.cgi
		#
		echoIfVerbose "-> Creating cpu load statistics rrd"
		if [ ! -e $PATH_DTC_ETC/cpu.rrd ] ; then
			$PATH_DTC_ADMIN/cpugraph/createrrd.sh $PATH_DTC_ETC
		fi
		if [ -e $PATH_DTC_ETC/cpu.rrd ] ; then
			chmod 775 $PATH_DTC_ETC/cpu.rrd
		fi

		#
		# Create the rrd file for memgraph.cgi
		#
		echoIfVerbose "-> Creating memory statistics rrd"
		if [ ! -e $PATH_DTC_ETC/memusage.rrd ] ; then
			$PATH_DTC_ADMIN/memgraph/createrrd.sh $PATH_DTC_ETC
		fi
		if [ -e $PATH_DTC_ETC/memusage.rrd ] ; then
			chmod 775 $PATH_DTC_ETC/memusage.rrd
		fi
		#
		# Create the sales stats rrd
		#
		echoIfVerbose "-> Creating sales stats rrd"
		if [ ! -e $PATH_DTC_ETC/stat_total_active_prods.rrd ] ; then
			$PATH_DTC_ADMIN/create_stat_total_active_prods_rrd.sh $PATH_DTC_ETC
		fi
		if [ -e $PATH_DTC_ETC/stat_total_active_prods.rrd ] ; then
			chmod 775 $PATH_DTC_ETC/stat_total_active_prods.rrd
		fi
	fi
	if [ -d /tmp/queuegraph ] ; then
		rm -rf /tmp/queuegraph
	fi
	if [ -d /tmp/netusegraph ] ; then
		rm -rf /tmp/netusegraph
	fi
	if [ -d /tmp/memusage ] ; then
		rm -rf /tmp/memusage
	fi
	if [ -d /tmp/cpugraph ] ; then
		rm -rf /tmp/cpugraph
	fi
	echoIfVerbose "===> Creating dtc.log with 666 permissions."
	touch /var/log/dtc.log
	chmod 640 /var/log/dtc.log
	chown root:adm /var/log/dtc.log
}

modifySSHDConfig () {
	#
	# Modify the SSH default option to make sure the UsePAM and turn on Password auth
	# 
	echoIfVerbose "===> Modifying your ssh.conf"
	# default to /etc/ssh/sshd_config if it's not set by the installer
	if [ -z ""$PATH_SSH_CONF ] ; then
		PATH_SSH_CONF=/etc/ssh/sshd_config
	fi

	echoIfVerbose "===> Modifying SSH config to allow chroot logins... "$PATH_SSH_CONF
	# first we want to comment out any previously set variables
	# PasswordAuthentication 
	# UsePAM
	TMP_FILE=`${MKTEMP} DTC_install.sshd_conf.XXXXXX` || exit 1

	if grep "^PasswordAuthentication" $PATH_SSH_CONF >/dev/null 2>&1
	then
		sed -e "s/^PasswordAuthentication/#PasswordAuthentication/" $PATH_SSH_CONF > $TMP_FILE
		cat <$TMP_FILE >$PATH_SSH_CONF
	fi

	if grep "^UsePAM" $PATH_SSH_CONF >/dev/null 2>&1
	then
		sed -e "s/^UsePAM/#UsePAM/" $PATH_SSH_CONF > $TMP_FILE
		cat <$TMP_FILE >$PATH_SSH_CONF
	fi

	# now that we have removed the conflicting entries, add it back with the DTC required switches

	if grep "Configured by DTC" $PATH_SSH_CONF >/dev/null
	then
		echoIfVerbose "$PATH_SSH_CONF has been configured before..."
	else
		if ! [ -f $PATH_SSH_CONF.DTC.backup ]
		then
			echoIfVerbose "===> Backuping "$PATH_SSH_CONF
			cp -f "$PATH_SSH_CONF" "$PATH_SSH_CONF.DTC.backup"
		fi
		echo "# Configured by DTC 0.21 : please do not touch this line !" > $TMP_FILE
		echo "UsePAM yes" >> $TMP_FILE
		echo "PasswordAuthentication yes" >> $TMP_FILE
		echo "# End of DTC configuration : please don't touch this line !" >> $TMP_FILE
		cat <$TMP_FILE >>$PATH_SSH_CONF
	fi

	rm $TMP_FILE
}

modifyNSSConfig () {
	#
	# Modify /etc/nsswitch.conf
	#
	TMP_FILE=`${MKTEMP} DTC_install.nsswitch.conf.XXXXXX` || exit 1

	if [ -z "$PATH_NSSWITCH_CONF" ] ; then
		PATH_NSSWITCH_CONF=/etc/nsswitch.conf
	fi

	if [ -f $PATH_NSSWITCH_CONF ] ; then
		if grep "Configured by DTC" $PATH_NSSWITCH_CONF >/dev/null
		then
			echoIfVerbose "$PATH_NSSWITCH_CONF has been configured before..."
		else
			if ! [ -f $PATH_NSSWITCH_CONF.DTC.backup ]
			then
				echoIfVerbose "===> Backuping "$PATH_NSSWITCH_CONF
				cp -f "$PATH_NSSWITCH_CONF" "$PATH_NSSWITCH_CONF.DTC.backup"
			fi
			echo "# Configured by DTC 0.21 : please do not touch this line !" > $TMP_FILE
			if [ "$UNIX_TYPE" = "freebsd" ] ; then
				echo "
passwd:		files mysql
group:		files mysql
shadow:		files mysql
" >> $TMP_FILE
			else
				echo "
passwd:         compat mysql
group:          compat mysql
shadow:         compat mysql
" >> $TMP_FILE
			fi
			echo "# End of DTC configuration : please don't touch this line !" >> $TMP_FILE
			cat <$TMP_FILE >>$PATH_NSSWITCH_CONF
		fi

		rm $TMP_FILE

		#
		# Modify /etc/nss-mysql.conf and /etc/nss-mysql-root.conf
		# 
		TMP_FILE=`${MKTEMP} DTC_install.nss-mysql.conf.XXXXXX` || exit 1

		if [ -z "$PATH_NSS_CONF" ] ; then
			if [ "$UNIX_TYPE" = "freebsd" ] ; then
				PATH_NSS_CONF="${LOCALBASE}/etc/libnss-mysql.cfg"
				NSSMYSQL_VERSION=libnss-mysql
				if [ -f $PATH_NSS_CONF ] ; then
					if ! grep "Configured by DTC" $PATH_NSS_CONF >/dev/null
					then
						mv ${PATH_NSS_CONF} ${PATH_NSS_CONF}.before.dtc
						touch ${PATH_NSS_CONF}
			        fi
				else
					touch ${PATH_NSS_CONF}
				fi
		        elif [ -e /etc/libnss-mysql.cfg ] ; then
				PATH_NSS_CONF=/etc/libnss-mysql.cfg	
				NSSMYSQL_VERSION=libnss-mysql
				# mv the existing config out of the way
				mv $PATH_NSS_CONF $PATH_NSS_CONF.before.dtc
				touch ${PATH_NSS_CONF}
			else
				PATH_NSS_CONF=/etc/nss-mysql.conf
				NSSMYSQL_VERSION=nss-mysql
			fi
		fi

		if [ -z "$PATH_NSS_ROOT_CONF" ] ; then
			if [ "$UNIX_TYPE" = "freebsd" ] ; then
				PATH_NSS_ROOT_CONF="${LOCALBASE}/etc/libnss-mysql-root.cfg"
				NSSMYSQL_VERSION=libnss-mysql
				if [ -f $PATH_NSS_ROOT_CONF ] ; then
					if ! grep "Configured by DTC" $PATH_NSS_ROOT_CONF >/dev/null
					then
						mv ${PATH_NSS_ROOT_CONF} ${PATH_NSS_ROOT_CONF}.before.dtc
						touch ${PATH_NSS_ROOT_CONF}
					fi
				else
					touch ${PATH_NSS_ROOT_CONF}
		                fi
		        elif [ -e /etc/libnss-mysql-root.cfg ] ; then
				PATH_NSS_ROOT_CONF=/etc/libnss-mysql-root.cfg	
				NSSMYSQL_VERSION=libnss-mysql
				mv $PATH_NSS_ROOT_CONF $PATH_NSS_ROOT_CONF.before.dtc
				touch ${PATH_NSS_ROOT_CONF}
			else
				PATH_NSS_ROOT_CONF=/etc/nss-mysql-root.conf
				NSSMYSQL_VERSION=nss-mysql
			fi
		fi

		if grep "Configured by DTC" $PATH_NSS_CONF >/dev/null
		then
			echoIfVerbose "$PATH_NSS_CONF has been configured before..."
		else
			if ! [ -f $PATH_NSS_CONF.DTC.backup ]
			then
				echoIfVerbose "===> Backuping "$PATH_NSS_CONF
				cp -f "$PATH_NSS_CONF" "$PATH_NSS_CONF.DTC.backup"
			fi

			echo "# Configured by DTC 0.21 : please do not touch this line !" > $TMP_FILE
			if [ ""$NSSMYSQL_VERSION = "nss-mysql" ] ; then
				echo "
users.host = inet:${conf_mysql_host}:3306;
users.database = ${conf_mysql_db};
users.db_user = dtcdaemons;
users.db_password = ${MYSQL_DTCDAEMONS_PASS};
users.backup_host =;
users.backup_database =;
users.table = ssh_access;
users.where_clause =;
users.user_column = ssh_access.login;
users.password_column = ssh_access.crypt;
users.userid_column = ssh_access.uid;
users.uid_column = ssh_access.uid;
users.gid_column = ssh_access.gid;
users.realname_column = \"DTC User\";
users.homedir_column = ssh_access.homedir;
users.shell_column = ssh_access.shell;
groups.group_info_table = ssh_groups;
groups.where_clause =;
groups.group_name_column = ssh_groups.group_name;
groups.groupid_column = ssh_groups.group_id;
groups.gid_column = ssh_groups.gid;
groups.password_column = ssh_groups.group_password;
groups.members_table = ssh_user_group;
groups.member_userid_column = ssh_user_group.user_id;
groups.member_groupid_column = ssh_user_group.group_id;
" >> $TMP_FILE
			else
				# this is the libnss version
				# for freebsd, needs all 10 GECOS fields for getpwent et al to return properly: KC
				if [ "$UNIX_TYPE" = "freebsd" ] ; then
					echo "
[queries]
getpwnam    SELECT login,crypt,uid,gid,'','default','DTC User',homedir,shell,2145916000 FROM ssh_access WHERE login='%1\$s' LIMIT 1
getpwuid    SELECT login,'*',uid,gid,'DTC User',homedir,shell FROM ssh_access WHERE uid='%1\$u' LIMIT 1
getpwent    SELECT login,'*',uid,gid,'DTC User',homedir,shell FROM ssh_access
getgrnam    SELECT group_name,group_password,group_id FROM ssh_groups WHERE group_name='%1\$s' LIMIT 1
getgrgid    SELECT group_name,group_password,group_id FROM ssh_groups WHERE group_id='%1\$u' LIMIT 1
getgrent    SELECT group_name,group_password,group_id FROM ssh_groups
memsbygid   SELECT login FROM ssh_access WHERE gid='%1\$u'
gidsbymem   SELECT gid  FROM ssh_access WHERE login='%1\$s'
getspnam    SELECT login,crypt,UNIX_TIMESTAMP() - 10,1,2,7,-1,-1,0 FROM ssh_access WHERE ssh_access.login='%1\$s' LIMIT 1
getspent    SELECT login,crypt,UNIX_TIMESTAMP() - 10,1,2,7,-1,-1,0 FROM ssh_access

[server]
host ${conf_mysql_host}
port 3306
database ${conf_mysql_db}
username dtcdaemons
password ${MYSQL_DTCDAEMONS_PASS}
" >> $TMP_FILE
				else
					echo "
[queries]
getpwnam    SELECT login,crypt,uid,gid,'DTC User',homedir,shell FROM ssh_access WHERE login='%1\$s' LIMIT 1 
getpwuid    SELECT login,'*',uid,gid,'DTC User',homedir,shell FROM ssh_access WHERE uid='%1\$u' LIMIT 1
getpwent    SELECT login,'*',uid,gid,'DTC User',homedir,shell FROM ssh_access
getgrnam    SELECT group_name,group_password,group_id FROM ssh_groups WHERE group_name='%1\$s' LIMIT 1
getgrgid    SELECT group_name,group_password,group_id FROM ssh_groups WHERE group_id='%1\$u' LIMIT 1
getgrent    SELECT group_name,group_password,group_id FROM ssh_groups
memsbygid   SELECT login FROM ssh_access WHERE gid='%1\$u'
gidsbymem   SELECT gid  FROM ssh_access WHERE login='%1\$s'
getspnam    SELECT login,crypt,UNIX_TIMESTAMP() - 10,1,2,7,-1,-1,0 FROM ssh_access WHERE ssh_access.login='%1\$s' LIMIT 1
getspent    SELECT login,crypt,UNIX_TIMESTAMP() - 10,1,2,7,-1,-1,0 FROM ssh_access

[server]
host ${conf_mysql_host}
port 3306
database ${conf_mysql_db}
username dtcdaemons
password ${MYSQL_DTCDAEMONS_PASS}
" >> $TMP_FILE
				fi

			fi
			echo "# End of DTC configuration : please don't touch this line !" >> $TMP_FILE
			cat <$TMP_FILE >>$PATH_NSS_CONF
		fi

		# fix perm for the nss root configuration
		chmod 400 $PATH_NSS_CONF

		if grep "Configured by DTC" $PATH_NSS_ROOT_CONF >/dev/null
		then
			echoIfVerbose "$PATH_NSS_ROOT_CONF has been configured before..."
		else
			if ! [ -f $PATH_NSS_ROOT_CONF.DTC.backup ]
			then
				echoIfVerbose "===> Backuping "$PATH_NSS_ROOT_CONF
				cp -f "$PATH_NSS_ROOT_CONF" "$PATH_NSS_ROOT_CONF.DTC.backup"
			fi
			echo "# Configured by DTC 0.21 : please do not touch this line !" > $TMP_FILE
			if [ ""$NSSMYSQL_VERSION = "nss-mysql" ] ; then
			echo "
shadow.host = inet:${conf_mysql_host}:3306;
shadow.database = ${conf_mysql_db};
shadow.db_user = dtcdaemons;
shadow.db_password = ${MYSQL_DTCDAEMONS_PASS};
shadow.backup_host =; 
shadow.backup_database =; 
shadow.table = ssh_access;
shadow.where_clause =;
shadow.userid_column = ssh_access.uid;
shadow.user_column = ssh_access.login;
shadow.password_column = ssh_access.crypt;
shadow.lastchange_column = UNIX_TIMESTAMP()-10;
shadow.min_column = 1;
shadow.max_column = 2;
shadow.warn_column = 7;
shadow.inact_column = -1; 
shadow.expire_column = -1; 
" >> $TMP_FILE
			else
				# libnss version
				echo "[server]
host ${conf_mysql_host}
port 3306
database ${conf_mysql_db}
username dtcdaemons
password ${MYSQL_DTCDAEMONS_PASS}
" >> $TMP_FILE
			fi
			echo "# End of DTC configuration : please don't touch this line !" >> $TMP_FILE
			cat <$TMP_FILE >>$PATH_NSS_ROOT_CONF
		fi
		# fix perm for the nss root configuration
		chmod 400 $PATH_NSS_ROOT_CONF

		rm $TMP_FILE
	else
		echo "-> Didn't find libnss nsswitch.conf: configuration of libnssmysql aborded"
	fi

	# Fixup the Lenny /etc/pam.d/common-auth to use libpam-unix2 so we can use LibNSSMySQL for ssh logins from vhosts
	if [ -e /etc/pam.d/common-auth ] ; then
		# We do this in Lenny only
		DEB_CODENAME=`lsb_release -c | awk '{print $2}'`
		if [ "${DEB_CODENAME}" = "lenny" -a -e /lib/security/pam_unix2.so ] ; then
			if grep "pam_unix.so" /etc/pam.d/common-auth >/dev/null ; then
				sed -i "s/pam_unix.so/pam_unix2.so/" /etc/pam.d/common-auth
			fi
			if grep "nullok_secure" /etc/pam.d/common-auth >/dev/null ; then
				sed -i "s/nullok_secure/nullok/" /etc/pam.d/common-auth
			fi
		# And in SID, we fix back as it breaks ssh logins :/
		else
			if grep "pam_unix2.so" /etc/pam.d/common-auth >/dev/null ; then
				sed -i "s/pam_unix2.so/pam_unix.so/" /etc/pam.d/common-auth
			fi
			COMMON_AUTH_NULL_SELECTION=`cat /etc/pam.d/common-auth | grep 'pam_unix' | awk '{print $4}'`
			if [ "${COMMON_AUTH_NULL_SELECTION}" = "nullok" ] ; then
				sed -i "s/nullok/nullok_secure/" /etc/pam.d/common-auth
			fi
		fi
	fi
}
#
# Install mysqmailconfig in the $PATH_MYSQMAIL_CONF
#

if [ -z ""$PATH_MYSQMAIL_CONF ] ; then
	PATH_MYSQMAIL_CONF=/etc/mysqmail.conf
fi
if [ -z ""$SYSLOG_CONF ] ; then
	SYSLOG_CONF=/etc/syslog.conf
fi 

modifyMysqmail () {
	#
	# Generate default config file for mysqmail (if we have it installed)
	#
	if [ -f $PATH_MYSQMAIL_CONF ] ; then
		echoIfVerbose "===> Configuring mysqmail.conf"
		if grep "Configured by DTC 0.22" $PATH_MYSQMAIL_CONF >/dev/null
		then
			echoIfVerbose "$PATH_MYSQMAIL_CONF has been configured before..."
		else
			if ! [ -f $PATH_MYSQMAIL_CONF.DTC.backup ] ; then
				echoIfVerbose "===> Moving $PATH_MYSQMAIL_CONF to $PATH_MYSQMAIL_CONF.DTC.backup"
				mv -f "$PATH_MYSQMAIL_CONF" "$PATH_MYSQMAIL_CONF.DTC.backup"
			fi
			TMP_FILE=/tmp/mysqmail.tmp
			echo "# Configured by DTC 0.22 : please do not touch this line !" > $TMP_FILE
			echo "mysql_hostname ${conf_mysql_host}" >> $TMP_FILE
			echo "mysql_user dtcdaemons" >> $TMP_FILE
			echo "mysql_pass ${MYSQL_DTCDAEMONS_PASS}" >> $TMP_FILE
			echo "mysql_db ${conf_mysql_db}" >> $TMP_FILE
			echo "mysql_table_smtp_logs smtp_logs" >> $TMP_FILE
			echo "mysql_table_pop_access pop_access" >> $TMP_FILE
			echo "mysql_table_scoreboard email_accounting" >> $TMP_FILE
			echo "mysql_table_domain domain" >> $TMP_FILE
			if [ $UNIX_TYPE = freebsd ] ; then
				echo "syslog_file /var/log/maillog" >>$TMP_FILE
			else
				echo "syslog_file /var/log/syslog" >>$TMP_FILE
			fi
			echo "# End of DTC Configuration : please do not touch this line !" >> $TMP_FILE
			echo "" >> $TMP_FILE
			cat < $TMP_FILE >>$PATH_MYSQMAIL_CONF
			rm $TMP_FILE	
			# Activate courier in rc.conf on FreeBSD
			if [ $UNIX_TYPE = freebsd ] ; then
				echo "Checking activation of mysqmail Daemons"
				if grep "Configured by DTC" /etc/rc.conf >/dev/null ; then
					# Configured already echoed
					echo -n ""
				else
					echo "### Configured by DTC 0.31 - please do not remove" >>/etc/rc.conf
				fi
				if grep mysqmail_postfix_logger /etc/rc.conf >/dev/null ; then
					# Postfix logger  already activated
					echo -n ""
				else
					echo "Activating Postfix Logger"
					echo "mysqmail_postfix_logger_enable=\"YES\"" >>/etc/rc.conf
				fi
				if [ ""$conf_use_cyrus = "false" ] ; then
					if grep mysqmail_courier_logger /etc/rc.conf >/dev/null ; then
						# Courier logger  already activated
						echo -n ""
					else
						echo "Activating Courier Logger"
						echo "mysqmail_courier_logger_enable=\"YES\"" >>/etc/rc.conf
					fi
				fi
				if [ -f $PATH_DOVECOT_CONF ] ; then
					if grep mysqmail_dovecot_logger /etc/rc.conf >/dev/null ; then
						# Dovecot logger  already activated
						echo -n ""
					else
						echo "Activating Dovecot Logger"
						echo "mysqmail_dovecot_logger_enable=\"YES\"" >>/etc/rc.conf
					fi
				fi
				if [ ""$conf_ftp_type = "pureftpd" ] ; then
					if grep mysqmail_pure_ftp_logger /etc/rc.conf >/dev/null ; then
						# Pure-ftp logger  already activated
						echo -n ""
					else
						echo "Activating Pure-Ftp Logger"
						echo "mysqmail_pure_ftp_logger_enable=\"YES\"" >>/etc/rc.conf
					fi
				fi
			fi
			restartDaemonMultiUnix mysqmail-postfix-logger
			if [ ""$conf_use_cyrus = "false" ] ; then
				restartDaemonMultiUnix mysqmail-courier-logger
			fi
			if [ -f $PATH_DOVECOT_CONF ] ; then
				restartDaemonMultiUnix mysqmail-dovecot-logger
			fi
			if [ ""$conf_ftp_type = "pureftpd" ] ; then
				restartDaemonMultiUnix mysqmail-pure-ftp-logger
			fi
		fi
#		if [ -f $SYSLOG_CONF ] ; then
#			if grep "Configured by DTC 0.22" $SYSLOG_CONF >/dev/null
#			then
#				echoIfVerbose "$SYSLOG_CONF has been configured before..."
#			else
#				if ! [ -f $SYSLOG_CONF.DTC.backup ]
#				then
#					echoIfVerbose "===> Backuping "$SYSLOG_CONF
#					cp -f "$SYSLOG_CONF" "$SYSLOG_CONF.DTC.backup"
#				fi
#				TMP_FILE=/tmp/mysqmail.tmp
#				echo "# Configured by DTC 0.22 : please do not touch this line !" > $TMP_FILE
#				echo "mail.*					|/var/log/mail.fifo" >> $TMP_FILE
#				echo "mail.*					|/var/log/courier.fifo" >> $TMP_FILE
#		#	echo "ftp.*						|/var/log/pure-ftpd.fifo" >> $TMP_FILE
#				cat < $TMP_FILE >> $SYSLOG_CONF;
#				rm $TMP_FILE
#				if ! [ -e /var/log/mail.fifo ] ; then
#					mkfifo /var/log/mail.fifo
#				fi
#				if ! [ -e /var/log/courier.fifo ] ; then
#					mkfifo /var/log/courier.fifo
#				fi
#				if ! [ -e /var/log/pure-ftpd.fifo ] ; then
#					mkfifo /var/log/pure-ftpd.fifo
#				fi
#				echoIfVerbose "Do not forget restart syslog daemon and mysqmail-loggers"
#			fi
#		fi
	fi
}

#
# Install the cron php4 scripts in the $PATH_CRONTAB_CONF
#

# just in case we haven't specified PATH_CRONTAB_CONF, default to /etc/crontab
if [ -z ""$PATH_CRONTAB_CONF ] ; then
	PATH_CRONTAB_CONF=/etc/crontab
fi

modifyCrontab () {
	echoIfVerbose "===> Installing cron script"
	if [ "$UNIX_TYPE" = "freebsd" ] && crontab -l | grep -q 'Configured by DTC'; then
		echoIfVerbose "root crontab has been configured before : skipping include insertion"
	elif grep -q "Configured by DTC " $PATH_CRONTAB_CONF >/dev/null ; then
		echoIfVerbose "/etc/crontab has been configured before : skinping include insertion"
	else
		echoIfVerbose "Inserting DTC cronjob in "$PATH_CRONTAB_CONF
		if ! [ -f $PATH_CRONTAB_CONF.DTC.backup ] ; then
			cp -f $PATH_CRONTAB_CONF $PATH_CRONTAB_CONF.DTC.backup
		fi

		# If not using Debian, install this directly
		if [ ! "$UNIX_TYPE" = "debian" ] ; then
			if [ ! "$UNIX_TYPE" = "redhat" ] ; then
				TMP_FILE=`${MKTEMP} DTC_install.crontab.XXXXXX` || exit 1
				echo "# Configured by DTC v0.10 : Please don't touch this line !" > $TMP_FILE
				echo -n `grep "^PATH=" ${PATH_CRONTAB_CONF}` >> $TMP_FILE
				echo ":/usr/local/bin:/usr/local/sbin" >> $TMP_FILE
				sed -e "s/\* dtc /\* ${CONF_DTC_SYSTEM_USERNAME} /" $PATH_DTC_CRON_FILE  | sed -e "s! /usr/share/dtc/admin! ${PATH_DTC_ADMIN}!g" | sed -e "s!/usr/bin/php!${PATH_PHP_CGI}!g" | sed -e "s!/var/lib/dtc/etc!${PATH_DTC_ETC}!g" >> $TMP_FILE
				cat < $TMP_FILE >>$PATH_CRONTAB_CONF
				rm $TMP_FILE
			fi
		fi

	fi

	# Now using a single rrdtool.sh script instead of multiple to help reduce the load
	# and also to make it dynamic (if using postfix or qmail)
	echo "#!/bin/sh

nice -n+20 cpugraph/get_cpu_load.sh     $PATH_DTC_ETC 2>&1 >>/var/log/dtc.log
nice -n+20 netusegraph/get_net_usage.sh $PATH_DTC_ETC \"${conf_eth2monitor}\" 2>&1 >>/var/log/dtc.log
nice -n+20 memgraph/get_meminfo.sh      $PATH_DTC_ETC 2>&1 >>/var/log/dtc.log
" >$PATH_DTC_ADMIN/rrdtool.sh
	if [ ""$conf_mta_type = "postfix" -o ""$conf_mta_type = "p" ] ; then
		echo "nice -n+20 queuegraph/count_postfix.sh $PATH_DTC_ETC 2>&1 >>/var/log/dtc.log" >>$PATH_DTC_ADMIN/rrdtool.sh
	fi
	if [ ""$conf_mta_type = "qmail" -o ""$conf_mta_type = "q" ] ; then
		echo "nice -n+20 queuegraph/count_qmail.sh $PATH_DTC_ETC 2>&1 >>/var/log/dtc.log" >>$PATH_DTC_ADMIN/rrdtool.sh
	fi
	chmod 700 $PATH_DTC_ADMIN/rrdtool.sh

}

reportingInstall () {
	if [ -e /usr/bin/wget ] ; then
		WGET="/usr/bin/wget"
	else
		WGET=`which wget`
	fi
	
	if [ ""$conf_report_setup = "true" -a -x "$WGET" ] ; then
		echoIfVerbose "===> Reporting install using $WGET -b -q --output-document=/dev/null http://www.gplhost.com/dtc-install-stats.php?ostype=${UNIX_TYPE}"
		$WGET -b -q --output-document=/dev/null "http://www.gplhost.com/dtc-install-stats.php?ostype=${UNIX_TYPE}" -o /dev/null >/dev/null
	else
		echoIfVerbose "===> Not reporting install this time..."
	fi
}

startPhpCronScript () {
	# Set the flags on the SQL table to make the cron job execute correctly
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE cron_job SET qmail_newu='yes',restart_qmail='yes',gen_qmail='yes',reload_named='yes',restart_apache='yes',gen_vhosts='yes',gen_named='yes' WHERE 1"
	# Only start fetchmail cronjob if we have fetchmail installed *steveetm*
	if [ `which fetchmail` ] ; then
	    $MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE cron_job SET gen_fetchmail='yes' WHERE 1"
	fi
	$MYSQL -u$conf_mysql_login -h$conf_mysql_host -D$conf_mysql_db --execute="UPDATE domain SET generate_flag='yes' WHERE 1"
	if [ ""$VERBOSE_INSTALL = "yes" ] ; then
		echo "***********************************************************"
		echo "*** Please wait while DTC configures all the daemons... ***"
		echo "***********************************************************"

		curdir=`pwd`
		cd $PATH_DTC_ADMIN; $PATH_PHP_CGI $PATH_DTC_ADMIN/cron.php
		cd $curdir
		echo "--- --- --- INSTALLATION FINISHED --- --- ---"
	else
		curdir=`pwd`
		cd $PATH_DTC_ADMIN; $PATH_PHP_CGI $PATH_DTC_ADMIN/cron.php 2>&1 >/var/log/dtc.log
		echo "done!"
		cd $curdir
	fi
}

echoEndMessage () {
	echo ""
	echo "Browse to: \"http://"$dtc_admin_subdomain"."$main_domain_name"/dtcadmin/\""
	echo "    or to: \"https://"$dtc_admin_subdomain"."$main_domain_name"/dtcadmin/\""
	echo "with login: ${conf_adm_login}"
	echo "Passwords can be administered using"
	echo "$PATH_DTC_ADMIN/dtcpassadm"
	echo "or by going in General config -> support and auth."
	echo "Remember to relaunch this installer if you install some other mail servers,"
	echo "whatever it is (qmail, postfix, courier, amavis, cyrus, etc...), as this"
	echo "script tries to guess what's installed in your system. Please check sshd_config"
	echo "and then restart ssh. Visit DTC web site:"
	echo "  Homepage: <http://www.gplhost.com/software-dtc.html>"
}

createChrootTemplate () {
	checkBsdKernel
	if [ -z $conf_chroot_path"" ] ; then
		CHROOT_DIR=/var/www/chroot
	fi

	echoIfVerbose "===> Creating chroot tree in "$conf_chroot_path" for unix type: "$UNIX_TYPE
	# set our umask so things are created with the correct group perms
	oldumask=`umask`
	umask 022

	# now onto the creation
	mkdir -p $conf_chroot_path
	cd $conf_chroot_path

	# create directory structure
	mkdir -p etc dev bin lib tmp var/tmp var/run sbin libexec
	mkdir -p usr/bin usr/lib usr/libexec usr/share usr/lib/zoneinfo

	# make devices - adjust MAJOR/MINOR as appropriate ( see ls -l /dev/* )
	if ! [ ""$conf_omit_dev_mknod = "true" ] ; then
		echoIfVerbose "-> Making devices"
		if ! [ -e dev/null ] ; then
			if [ "$UNIX_TYPE" = "freebsd" -o "$UNIX_TYPE" = "osx" ] ; then
				mknod dev/null    c  2 2   # FreeBSD?
			else
				mknod dev/null    c  1 3   # Linux
			fi
		fi

		if [ "$UNIX_TYPE" = "freebsd"  -o "$UNIX_TYPE" = "osx" ] ; then
			if [ $kernel"" = "OpenBSD" ] ; then
				if ! [ -e dev/urandom ] ; then
					mknod dev/urandom c 45 2   # OpenBSD ?
				fi
			else
				if ! [ -e dev/random ] ; then
					mknod dev/random  c  2 3   # FreeBSD
				fi
				if ! [ -e dev/urandom ] ; then
					mknod dev/urandom  c  2 3
				fi
			fi
		else
			if ! [ -e dev/random ] ; then
				mknod dev/random  c  1 8   # Linux
			fi
			if ! [ -e dev/urandom ] ; then
				mknod dev/urandom c  1 9   # Linux
			fi
		fi

		# some external programs may need these:
		if [ "$UNIX_TYPE" = "freebsd"  -o "$UNIX_TYPE" = "osx" ] ; then
			if ! [ -e dev/stdin ] ; then
				mknod dev/stdin   c 22 0   # FreeBSD, OpenBSD
			fi
			if ! [ -e dev/stdout ] ; then
				mknod dev/stdout  c 22 1   # FreeBSD, OpenBSD
			fi
			if ! [ -e dev/stderr ] ; then
				mknod dev/stderr  c 22 2   # FreeBSD, OpenBSD
			fi
		fi
	fi

	# copy required binaries to $conf_chroot_path/usr/bin and $conf_chroot_path/bin
	echoIfVerbose "-> Copying utilities"
	if [ -e /bin/bzip2 ] ; then
		cp -pf /bin/bzip2 usr/bin/
	fi
	if [ -e /usr/bin/bzip2 ] ; then
		cp -pf /usr/bin/bzip2 usr/bin/
	fi
	if [ -e /usr/bin/file ] ; then
		cp -pf /usr/bin/file usr/bin/
	fi
	if [ -e /usr/bin/groups ] ; then
		cp -pf /usr/bin/groups usr/bin
	fi
	if [ -e /usr/bin/id ] ; then
		cp -pf /usr/bin/id usr/bin
	fi
	if [ -e /bin/mkdir ] ; then
		cp -pf /bin/mkdir bin
	fi

	# copy zip and unzip if they are present
	if [ -e /usr/bin/zip ] ; then
		cp -pf /usr/bin/zip bin/
	fi
	if [ -e /usr/bin/unzip ] ; then
		cp -pf /usr/bin/unzip bin/
	fi

	if [ -e ${PATH_BASH} ] ; then
		cp -pf ${PATH_BASH} bin
	fi
	if [ -e /usr/bin/tar ] ; then
		cp -pf /usr/bin/tar bin
	fi
	if [ -e /bin/tar ] ; then
		cp -pf /bin/tar bin
	fi
	if [ -e /usr/bin/false ] ; then
		cp -pf /usr/bin/false bin
	fi
	if [ -e /bin/false ] ; then
		cp -pf /bin/false bin
	fi

	if [ -e /usr/bin/sftp ] ; then
		cp -pf /usr/bin/sftp bin/
	fi

	# the sftp-server binary can be in /usr/lib or /lib, so check both places
	if [ -e /usr/lib/sftp-server ] ; then
		cp -pf /usr/lib/sftp-server usr/lib/
	fi

	if [ -e /usr/libexec/sftp-server ] ; then
		cp -pf /usr/libexec/sftp-server usr/libexec/
	fi

	mkdir -p usr/lib/openssh
	if [ -e /usr/lib/openssh/sftp ] ; then
		cp -pf /usr/lib/openssh/sftp usr/lib/openssh
	fi

	if [ -e /lib/sftp-server ] ; then
		cp -pf /lib/sftp-server lib/
	fi

	# Debian location for the sftp-server
	if [ -e /usr/lib/openssh/sftp-server ] ; then
		mkdir -p usr/lib/openssh
		cp -pf /usr/lib/openssh/sftp-server usr/lib/openssh
	fi

	# CentOS location
	if [ -e /usr/libexec/openssh/sftp-server ] ; then
		mkdir -p usr/libexec/openssh
		cp -pf /usr/libexec/openssh/sftp-server usr/libexec/openssh
	fi

	if [ -e /usr/bin/scp ] ; then
		cp -pf /usr/bin/scp bin/
	fi

	# copy more required binaries to $conf_chroot_path/bin
	cp -pf /bin/sh /bin/echo /bin/ls /bin/pwd /bin/cat bin/

	if [ "$UNIX_TYPE" = "freebsd" ] ; then
		cp -pf /usr/bin/cpio usr/bin
	        cp -f /libexec/ld-elf.so.1 libexec
		cp -pf /bin/rm /bin/mv /usr/bin/gunzip /usr/bin/tar /usr/bin/false bin/
	elif [ "$UNIX_TYPE" = "osx" ] ; then
		cp -pf /usr/bin/cpio usr/bin
		cp -pf /usr/bin/rm /usr/bin/mv /usr/bin/gunzip /usr/bin/tar /usr/bin/false bin/
	else
		cp -pf /bin/rm /bin/mv /bin/gunzip bin/
		cp -pf /bin/cpio usr/bin
	fi

	# copy ldconfig from sbin to $conf_chroot_path/sbin
	if ! [ "$UNIX_TYPE" = "osx" ] ; then
		cp -pf /sbin/ldconfig* sbin/
	fi

	echoIfVerbose "-> Creating /etc template"
	# copy needed /etc files to $conf_chroot_path/etc
	cp -pf /etc/protocols /etc/services /etc/hosts /etc/resolv.conf etc/

	# generate /etc/passwd and /etc/group
	# ignore errors
	grep daemon /etc/passwd > etc/passwd || true
	grep bin /etc/passwd >> etc/passwd || true
	grep sys /etc/passwd >> etc/passwd || true
	grep man /etc/passwd >> etc/passwd || true
	grep lp /etc/passwd >> etc/passwd || true
	grep mail /etc/passwd >> etc/passwd || true
	grep news /etc/passwd >> etc/passwd || true
	grep uucp /etc/passwd >> etc/passwd || true
	grep www-data /etc/passwd >> etc/passwd || true
	# generate this one manually: grep nobody /etc/passwd >> etc/passwd
	grep daemon /etc/group > etc/group || true
	grep bin /etc/group >> etc/group || true
	grep sys /etc/group >> etc/group || true
	grep man /etc/group >> etc/group || true
	grep lp /etc/group >> etc/group || true
	grep mail /etc/group >> etc/group || true
	grep news /etc/group >> etc/group || true
	grep uucp /etc/group >> etc/group || true
	grep www-data /etc/group >> etc/group || true
	grep ${CONF_DTC_SYSTEM_GROUPNAME} /etc/group >> etc/group || true
	grep ${CONF_DTC_SYSTEM_USERNAME} /etc/group >> etc/group || true

	# fix entry for the dtc system user in /etc/passwd
	echo "${CONF_DTC_SYSTEM_USERNAME}:x:${CONF_DTC_SYSTEM_UID}:${CONF_DTC_SYSTEM_GID}:${CONF_DTC_SYSTEM_USERNAME}:/html:${PATH_BASH}" >> etc/passwd

	# create shadow account line for nobody
	echo "${CONF_DTC_SYSTEM_USERNAME}::12719:0:99999:7:::" > etc/shadow
	chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} etc/shadow

	if [ -e /etc/host.conf ] ; then
		cp -pf /etc/host.conf etc/
	fi

	if [ -e /etc/ld.conf ] ; then
		cp -pf /etc/ld.conf etc/
	fi

	if [ -e /etc/nsswitch.conf ] ; then
		cp -pf /etc/nsswitch.conf etc/
	fi

	if [ -e /etc/localtime ] ; then
		cp -pf /etc/localtime etc/
	fi

	# copy shared libraries to $conf_chroot_path/lib
	#   (check:  ldd /usr/bin/perl (or other binary) to see which ones are needed)
	#
	#FreeBSD: 
	#for j in \
	echoIfVerbose "-> Copying essential libraries"
	if [ "$UNIX_TYPE" = "freebsd"  ] ; then
		cp -f /lib/libc.so* /lib/libm.so* lib/
		for i in /usr/local/lib/libintl.so.* /usr/local/lib/libiconv.so.* \
			/usr/lib/libarchive.so.* /usr/lib/libasn1.so.* /usr/lib/libbsm.so.* \
			/usr/lib/libbz2.so.* /usr/lib/libcom_err.so.* /usr/lib/libgssapi.so.* /usr/lib/libkrb5.so.* /usr/lib/libmagic.so.* \
			/usr/lib/libroken.so.* /usr/lib/libssh.so.* ; do
			cp -f ${i} usr/lib
		done
		LIBPERL=/usr/local/lib/perl5/` ldd /usr/local/bin/perl | grep libperl | cut -d/ -f 6`/mach/CORE/libperl.so
		if [ ! -f $LIBPERL ]
		then
			echo "No PERL Library Found. $LIBPERL"
			exit 1
		else
			cp -f $LIBPERL usr/lib
		fi
		cp -f /lib/libc.so* /lib/libm.so* /lib/libedit.so* /lib/libncurses.so* /lib/libcrypt.so.* /lib/libmd.so.* /lib/libutil.so.* \
			/lib/libz.so.* lib/
		cp -f /usr/lib/libc.so* usr/lib/
		cp -pf /usr/lib/libm.so* usr/lib/
		cp -pf /usr/lib/libstdc\+\+.so* usr/lib/
		if [ -e /usr/compat/linux/usr/lib/libz.so.1 ] ; then
			cp /usr/compat/linux/usr/lib/libz.so.1 usr/lib
		fi
	else
		if [ "$UNIX_TYPE" = "osx"  ] ; then
			mkdir -p usr/lib
			echo "-> usr/lib"
			cp -pf /usr/lib/dyld /usr/lib/libSystem.B.dylib \
			  /usr/lib/libc.dylib /usr/lib/libdl.dylib \
			  /usr/lib/libncurses.5.dylib /usr/lib/libpam.dylib \
			  /usr/lib/libpthread.dylib usr/lib/
			cp -pf /usr/lib/dylib1.o /usr/lib/libSystem.dylib \
			  /usr/lib/libcrypto.dylib /usr/lib/libm.dylib \
			  /usr/lib/libncurses.dylib /usr/lib/libpam_misc.dylib \
			  /usr/lib/libz.dylib usr/lib
			echo "-> usr/lib/system"
			mkdir -p usr/lib/system
			cp -pf /usr/lib/system/libmathCommon.A.dylib usr/lib/system
		else
			FOUNDED_ARCH=`uname -m`
			if [ ""$FOUNDED_ARCH = "x86_64" ] ; then
				if [ ! -e lib64 ] ; then
					ln -s lib lib64
				fi
			fi
			# Some libs for CentOS
			if [ -e /lib/libdl.so.2 ] ; then
				cp -pf /lib/libdl.so.2 lib
			fi
			if [ -e /lib64/libdl.so.2 ] ; then
				cp -pf /lib64/libdl.so.2 lib
			fi
			if [ -e /lib/libc.so.6 ] ; then
				cp -pf /lib/libc.so.6 lib
			fi
			if [ -e /lib64/libc.so.6 ] ; then
				cp -pf /lib64/libc.so.6 lib
			fi
			if [ -e /lib/libtermcap.so.2 ] ; then
				cp -pf /lib/libtermcap.so.2 lib
			fi
			if [ -e /lib64/libtermcap.so.2 ] ; then
				cp -pf /lib64/libtermcap.so.2 lib
			fi

			if [ -e /lib/ld-linux.so.2 ] ; then
				cp -pf /lib/ld-linux.so.2 lib/
			fi
			if [ -e /lib/ld-linux-x86-64.so.2 ] ; then
				cp -pf /lib/ld-linux-x86-64.so.2 lib/
			fi
			if [ -e /lib/libdl.so.2 ] ; then
				cp -pf /lib/libdl.so.2 lib/
			fi
			if [ -e /lib/libm.so.6 ] ; then
				cp -pf /lib/libm.so.6 lib/
			fi
			if [ -e /lib/libpthread.so.0 ] ; then
				cp -pf /lib/libpthread.so.0 lib/
			fi
			if [ -e /lib/libc.so.6 ] ; then
				cp -pf /lib/libc.so.6 lib/
			fi
			if [ -e /lib/libcrypt.so.1 ] ; then
				cp -pf /lib/libcrypt.so.1 lib/
			fi
			if [ -e /lib/librt.so.1 ] ; then
				cp -pf /lib/librt.so.1 lib/
			fi

			CPY_LIBS="libnss_compat.so.2 libnsl.so.1 libnss_files.so.2 libpam.so.0 libpam_misc.so.0 libncurses.so.5 libacl.so.1 libattr.so.1 libcap.so.1 libbz2.so.1.0 libz.so.1"
			for i in ${CPY_LIBS} ; do
				if [ -f /lib/${i} ] ; then
					cp -pf  /lib/${i} lib/
				fi
				if [ -f /lib64/${i} ] ; then
					cp -pf  /lib64/${i} lib/
				fi
			done
	
			CPY_LIBS="libncurses.so.5 libbz2.so.1.0 libmagic.so.1 libz.so.1"
			for i in ${CPY_LIBS} ; do
				if [ -f /usr/lib/${i} ] ; then
					cp -pf  /usr/lib/${i} lib/
				fi
				if [ -f /usr/lib64/${i} ] ; then
					cp -pf  /usr/lib64/${i} lib/
				fi
			done

			# libs for sftp and scp
			if [ -e /lib/libresolv.so.2 ] ; then
				cp -pf /lib/libresolv.so.2 lib/
			fi

			if [ -e /usr/lib/libcrypto.so.0.9.7 ] ; then
				cp -pf /usr/lib/libcrypto.so.0.9.7 lib/
			fi

			if [ -e /usr/lib/libcrypto.so.0.9.8 ] ; then
				cp -pf /usr/lib/libcrypto.so.0.9.8 lib/
			fi

			if [ -e /lib/libutil.so.1 ] ; then
				cp -pf /lib/libutil.so.1 lib/
			fi
		fi
	fi

	# magic files needed by file(1). Different versions and installations
	# expect magic files in different locations. Check the documentation.
	# Some usual locations are:
	if [ -e /usr/share/misc/file ] ; then
		#cp -pf /usr/local/share/file/*  usr/local/share/file/
		mkdir -p usr/share/misc/file
		cp -pf /usr/share/misc/file/magic*   usr/share/misc/file
		#cp -pf /usr/share/magic         usr/share/
	fi

	# No need anymore - fix up pam.d into jail
	# if [ -e /etc/pam.d ] ; then
	# 	mkdir -p ./etc/pam.d/
	# 	cp /etc/pam.d/* ./etc/pam.d/
	# fi
	# No need anymore - copy PAM-Modules to jail
	#if [ -e /lib/security ] ; then
		#cp -r /lib/security ./lib/
	#fi
	#if [ -e /etc/security ] ; then 
	#	cp -r /etc/security ./etc/
	#fi
	if [ -e /etc/login.defs ] ; then
		cp /etc/login.defs ./etc/
	fi

	# now we have come this far, make sure our chroot includes enough libs for this environment
	echoIfVerbose "-> Some ldd things"
	LDD=`which ldd`
	if [ -n "$LDD" -a ! "$UNIX_TYPE" = "freebsd" ] ; then

		for i in bin/* ; do
		        for j in `$LDD $i | cut -f 1 -d' '`;
		        do
				if [ -e $j ] ; then
					cp -pf $j lib/
				fi
		                if [ -e /lib/$j ] ; then
		                        cp -pf /lib/$j lib/
		                fi
		                if [ -e /usr/lib/$j ] ; then
		                        cp -pf /usr/lib/$j lib/
		                fi
		                if [ -e /usr/local/lib/$j ] ; then
		                        cp -pf /usr/local/lib/$j lib/
		                fi
		        done
		done
	fi

	# if we have a sudo binary around, then use it to create our chroot shell
	SUDO=`which sudo`
	SHELL=${LOCALBASE}/bin/dtc-chroot-shell
	#chmod 755 $SHELL

	# set protections
	echoIfVerbose "-> Fixup rights"
	chmod 1770 tmp
	chmod 1770 var/tmp
	if ! [ ""$conf_omit_dev_mknod = "true" ] ; then
		chmod 666 dev/null
		chmod 644 dev/*random
	fi

	#now need to copy over the perl binary and some modules
	cp -pf /usr/bin/perl usr/bin/

	echoIfVerbose "-> Managing ldconfig"
	if [ "$UNIX_TYPE" = "freebsd" ] ; then
	        # now create our ld.so cache
	        cp /libexec/ld-elf.so.1 $conf_chroot_path/libexec
		if [ -e /var/run/ld-elf.so.hints ] ; then
			cp /var/run/ld-elf.so.hints var/run			# need this for fbsd jails: KC
		fi
	        chroot $conf_chroot_path ./sbin/ldconfig
	        # just in case we have wiped our /etc/ld.so.cache (run locally)
	        /sbin/ldconfig
	else
		if ! [ "$UNIX_TYPE" = "osx" -o "$UNIX_TYPE" = 'freebsd' ] ; then
			# now create our ld.so cache
			mkdir -p $conf_chroot_path/etc
			touch $conf_chroot_path/etc/ld.so.cache
			touch $conf_chroot_path/etc/ld.so.conf
			chroot $conf_chroot_path ./sbin/ldconfig 
			# just in case we have wiped our /etc/ld.so.cache (run locally)
			/sbin/ldconfig
		fi
	fi

	# Adds the possibility to customize the chroot and helps upgrading between versions
	if [ -d $conf_chroot_path.custom ] ; then
		cp -fpR $conf_chroot_path.custom/* $conf_chroot_path/ 2>/dev/null || true # Make it possible to fail if the directory is empty
	else
		# Create the directory to show to the user he can use it
		if ! [ -e $conf_chroot_path.custom ] ; then
			mkdir -p $conf_chroot_path.custom
		fi
	fi

	chown ${CONF_DTC_SYSTEM_USERNAME}:${CONF_DTC_SYSTEM_GROUPNAME} etc dev bin lib tmp var sbin libexec usr
	umask $oldumask
	echoIfVerbose "-> Done chroot template!"
}

fixesExtplorer () {
	if [ -d "/etc/extplorer" -a -f "/usr/share/doc/dtc/contrib/extplorer.htusers.php" ] ; then
		if ! [ -f "/etc/extplorer/.htusers.php" ] ; then
			cp /usr/share/doc/dtc/contrib/extplorer.htusers.php /etc/extplorer/.htusers.php
		else
			if [ `cat /etc/extplorer/.htusers.php | wc -l` = 0 ] ; then
				cp /usr/share/doc/dtc/contrib/extplorer.htusers.php /etc/extplorer/.htusers.php
			fi
		fi
	fi
}

checkBsdKernel () {
	echoIfVerbose "===> Checking BSD type"
	kernel=`uname -a | awk '{print $1}'`;
	echoIfVerbose "Kernel: $kernel"
}

enableBsdBind () {
	checkBsdKernel
	if [ $kernel = "FreeBSD" ] || [ $kernel = "NetBSD" ] ; then
		named=` grep named_enable /etc/rc.conf | grep -v "^#" | cut -d= -f2|cut -d" " -f1`
		nonamed=`echo $named | grep -i no|cat`
		if [ "$named" = "" ] || [ "$nonamed" != "" ] ; then
			echo "===> FreeBSD or NetBSD: Backing up /etc/rc.conf and inserting named_enable=YES"
			if [ -f /etc/rc.conf.DTC.Backup ]
			then
				cp /etc/rc.conf /etc/rc.conf.DTC.Backup
				echo "/etc/rc.conf /etc/rc.conf.DTC.Backup saved"
			else
				echo "/etc/rc.conf.DTC.Backup already exists"
			fi
			cat /etc/rc.conf | grep -v "named" > /etc/rc.tmp
			echo 'named_enable="YES"              # Run named, the DNS server (or NO).' >> /etc/rc.tmp
			echo 'named_program="/usr/sbin/named" # path to named, if you want a different one.' >> /etc/rc.tmp
			echo '#named_flags="-u bind -g bind"  # Flags for named' >> /etc/rc.tmp
			echo 'named_chrootdir=""              # Do not chroot for named' >> /etc/rc.tmp
			mv /etc/rc.tmp /etc/rc.conf
			echo "named /etc/rc.conf injected"
		else
			echo "===> /etc/rc.conf is already configured: leaving..."
		fi
	fi

	if [ $kernel = "OpenBSD" ] ; then
		flag=`grep named_flags=\"-c /etc/rc.conf`	
		echo "conf $flag"
		if [ "$flag" = "" ] ; then
			echo "===> OpenBSD: Backing up /etc/rc.conf and inserting named_flags=\"-c /etc/named.conf\""
			echo "/etc/rc.conf no named"
			cp /etc/rc.conf /etc/rc.conf.old
			echo "/etc/rc.conf /etc/rc.conf.old saved"
			cat /etc/rc.conf | grep -v "named_flags=NO" >> /etc/rc.tmp
			echo 'named_flags="-c /etc/named.conf"' >> /etc/rc.tmp
			mv /etc/rc.tmp /etc/rc.conf
			echo "named /etc/rc.conf injected"
			if [ ! -f /etc/named.conf ] ; then
				echo "no /etc/named.conf"
				if ! [ ! -f /var/named/etc/named.conf ] ; then
					cp /var/named/etc/named.conf /etc/named.conf 
					echo "/var/named/etc/named.conf /etc/named.conf copied" 
				else
					mv	/etc/rc.conf.old /etc/rc.conf
					echo 	"/etc/rc.conf.old /etc/rc.conf replaced"
					echo	"set named at your own configuration in /etc/rc.conf and in your named.conf"
				fi
				echo "conf named.conf done"
			fi
			echo "conf /etc/rc.conf done"
		fi
		echo "conf done"
	fi
}

copyBsdPhpIni () {
	# Copy dist file if no php.ini is there yet...
	if [ -e /usr/local/etc/php.ini-dist ] ; then
		if ! [ -e /usr/local/etc/php.ini ] ; then
			cp /usr/local/etc/php.ini-dist /usr/local/etc/php.ini
		fi
	fi
}

########################## HERE STARTS THE UNINSTALLER ###################
deleteGeneratedFiles () {
	rm -f ${PATH_DTC_ADMIN}/.htaccess
	rm -f ${PATH_DTC_SHARED}/shared/cyrus.php
	rm -f ${PATH_DTC_SHARED}/shared/mysql_config.php
	if [ ! "$UNIX_TYPE" = "debian" ] ; then
		if [ -e /bin/dtc-chroot-shell ] ; then
			rm /bin/dtc-chroot-shell
		fi
	fi
	rm -f ${PATH_DTC_SHARED}/etc/apache.pid
}

uninstallCrontab () {
	if grep "Configured by DTC" $PATH_CRONTAB_CONF >/dev/null
	then
		echoIfVerbose "===> Uninstalling inclusion from crontab"
		TMP_FILE=`${MKTEMP} DTC_uninstall.crontab.XXXXXX` || exit 1
		TMP_FILE2=`${MKTEMP} DTC_uninstall.crontab.XXXXXX` || exit 1
		grep -v "Configured by DTC" $PATH_CRONTAB_CONF > $TMP_FILE
		grep -v "cd /usr/share/dtc/admin; " $TMP_FILE > $TMP_FILE2
		# don't rm the original file, just empty it so we keep permissions
		echo -n > $PATH_CRONTAB_CONF
		cat < $TMP_FILE2 >> $PATH_CRONTAB_CONF
		rm -f $TMP_FILE $TMP_FILE2
	fi
	# Those are for debian, removing the old version that was wrong
	# and conflicting (many messages sent to root).
	if [ -f "/etc/cron.d/dtc-mail-queue-graph" ] ; then
		rm -f /etc/cron.d/dtc-mail-queue-graph
	fi
	if [ -f "/etc/cron.d/dtc-postfix-courier" ] ; then
		rm -f /etc/cron.d/dtc-postfix-courier
	fi
}

uninstallNamed () {
	if grep "Configured by DTC" $PATH_NAMED_CONF >/dev/null
	then
		echoIfVerbose "===> Uninstalling inclusion from named.conf"
		TMP_FILE=`${MKTEMP} DTC_uninstall.named.conf.XXXXXX` || exit 1
		TMP_FILE2=`${MKTEMP} DTC_uninstall.named.conf.XXXXXX` || exit 1
		grep -v "Configured by DTC" $PATH_NAMED_CONF > $TMP_FILE
		grep -v "include \"$PATH_DTC_ETC/named.conf\"" $TMP_FILE > $TMP_FILE2
		cp -f $PATH_NAMED_CONF $PATH_NAMED_CONF.DTC.removed
		# don't rm the original file, just empty it
		echo -n > $PATH_NAMED_CONF
		cat < $TMP_FILE2 >> $PATH_NAMED_CONF
		rm -f $TMP_FILE $TMP_FILE2
	fi
}

uninstallHttpdConfig () {
	#
	# uninstall httpd.conf
	#
	if grep "Configured by DTC" $PATH_HTTPD_CONF >/dev/null 2>&1
	then
		echoIfVerbose "===> Uninstalling inclusion from httpd.conf"
		TMP_FILE=`$MKTEMP DTC_uninstall.httpd.conf.XXXXXX` || exit 1
		start_line=`grep -n "Configured by DTC" $PATH_HTTPD_CONF | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" $PATH_HTTPD_CONF| cut -d":" -f1`
		nbr_line=`cat $PATH_HTTPD_CONF | wc -l`
		cat $PATH_HTTPD_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
		cat $PATH_HTTPD_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		cat < $TMP_FILE >$PATH_HTTPD_CONF
		rm $TMP_FILE
	fi

	if [ -e /etc/apache2/ports.conf ] ; then
		echoIfVerbose "===> Uninstalling ports.conf"
		if [ -e /etc/apache2/ports.conf.DTC_backup ] ; then
			cat </etc/apache2/ports.conf.DTC_backup /etc/apache2/ports.conf
		fi
	fi
}

uninstallCourierConfig () {
	#
	# uninstall courier config details
	#
	echoIfVerbose "===> Uninstalling inclusion from courier authdaemonrc"
	if grep "Configured by DTC" $PATH_COURIER_CONF_PATH/authdaemonrc >/dev/null 2>&1
	then
		start_line=`grep -n "Configured by DTC" $PATH_COURIER_CONF_PATH/authdaemonrc | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" $PATH_COURIER_CONF_PATH/authdaemonrc| cut -d":" -f1`
		nbr_line=`cat $PATH_COURIER_CONF_PATH/authdaemonrc | wc -l`
		TMP_FILE=`${MKTEMP} DTC_uninstall.courier.conf.XXXXXX` || exit 1
		cat $PATH_COURIER_CONF_PATH/authdaemonrc | head -n $(($start_line - 1 )) > $TMP_FILE
		cat $PATH_COURIER_CONF_PATH/authdaemonrc | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		cp -f $PATH_COURIER_CONF_PATH/authdaemonrc $PATH_COURIER_CONF_PATH/authdaemonrc.DTC.removed
		echo -n > $PATH_COURIER_CONF_PATH/authdaemonrc
		cat < $TMP_FILE >> $PATH_COURIER_CONF_PATH/authdaemonrc
		rm $TMP_FILE
	fi
}

uninstallDevecotConfig () {
	#
	# uninstall dovecot.conf
	#
	echoIfVerbose "===> Uninstalling inclusion from dovecot.conf"
	if grep "Configured by DTC" $PATH_DOVECOT_CONF >/dev/null 2>&1
	then
		start_line=`grep -n "Configured by DTC" $PATH_DOVECOT_CONF | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" $PATH_DOVECOT_CONF| cut -d":" -f1`
		nbr_line=`cat $PATH_DOVECOT_CONF | wc -l`
		TMP_FILE=`${MKTEMP} DTC_uninstall.dovecot.conf.XXXXXX` || exit 1
		cat $PATH_DOVECOT_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
		cat $PATH_DOVECOT_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		cp -f $PATH_DOVECOT_CONF $PATH_DOVECOT_CONF.DTC.removed
		echo -n > $PATH_DOVECOT_CONF
		cat < $TMP_FILE >> $PATH_DOVECOT_CONF
	        rm $TMP_FILE
	fi
}

uninstallProftpdConfig () {
	#
	# uninstall proftpd.conf
	#
	echoIfVerbose "===> Uninstalling inclusion from proftpd.conf"
	if grep "Configured by DTC" $PATH_PROFTPD_CONF >/dev/null 2>&1
	then
		start_line=`grep -n "Configured by DTC" $PATH_PROFTPD_CONF | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" $PATH_PROFTPD_CONF| cut -d":" -f1`
		nbr_line=`cat $PATH_PROFTPD_CONF | wc -l`
		TMP_FILE=`${MKTEMP} DTC_uninstall.proftpd.conf.XXXXXX` || exit 1
		cat $PATH_PROFTPD_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
		cat $PATH_PROFTPD_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		cp -f $PATH_PROFTPD_CONF $PATH_PROFTPD_CONF.DTC.removed
		echo -n > $PATH_PROFTPD_CONF
		cat < $TMP_FILE >> $PATH_PROFTPD_CONF
	        rm $TMP_FILE
	fi
}

uninstallPostfix () {
	#
	# uninstall postfix/main.cf
	#
	echoIfVerbose "===> Uninstalling inclusion from postfix/main.cf"
	if grep "Configured by DTC" $PATH_POSTFIX_CONF >/dev/null 2>&1
	then
		start_line=`grep -n "Configured by DTC" $PATH_POSTFIX_CONF | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" $PATH_POSTFIX_CONF| cut -d":" -f1`
		nbr_line=`cat $PATH_POSTFIX_CONF | wc -l`
		TMP_FILE=`${MKTEMP} DTC_uninstall.postfix.conf.XXXXXX` || exit 1
		cat $PATH_POSTFIX_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
		cat $PATH_POSTFIX_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		cp -f $PATH_POSTFIX_CONF $PATH_POSTFIX_CONF.DTC.removed
		echo -n > $PATH_POSTFIX_CONF
		cat < $TMP_FILE >> $PATH_POSTFIX_CONF
	        rm $TMP_FILE
	fi

	#
	# uninstall postfix/master.cf
	#
	echoIfVerbose "===> Uninstalling inclusion from postfix/master.cf"
	if grep "Configured by DTC" ${PATH_POSTFIX_ETC}/master.cf >/dev/null 2>&1
	then
		start_line=`grep -n "Configured by DTC" ${PATH_POSTFIX_ETC}/master.cf | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" ${PATH_POSTFIX_ETC}/master.cf | cut -d":" -f1`
		nbr_line=`cat ${PATH_POSTFIX_ETC}/master.cf | wc -l`
		TMP_FILE=`${MKTEMP} DTC_uninstall.postfix.conf.XXXXXX` || exit 1
		cat ${PATH_POSTFIX_ETC}/master.cf | head -n $(($start_line - 1 )) > $TMP_FILE
		cat ${PATH_POSTFIX_ETC}/master.cf | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		cp -f ${PATH_POSTFIX_ETC}/master.cf ${PATH_POSTFIX_ETC}/master.cf.DTC.removed
		echo -n > ${PATH_POSTFIX_ETC}/master.cf
		cat < $TMP_FILE >> ${PATH_POSTFIX_ETC}/master.cf
		rm $TMP_FILE
	fi

	#
	# uninstall /etc/aliases
	#
	echoIfVerbose "===> Uninstalling aliases from /etc/aliases"
	if grep "Configured by DTC" /etc/aliases >/dev/null 2>&1
	then
		start_line=`grep -n "Configured by DTC" /etc/aliases | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" /etc/aliases | cut -d":" -f1`
		nbr_line=`cat /etc/aliases | wc -l`
		TMP_FILE=`${MKTEMP} DTC_uninstall.aliases.XXXXXX` || exit 1
		cat /etc/aliases | head -n $(($start_line - 1 )) > $TMP_FILE
		cat /etc/aliases | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		echo -n > /etc/aliases
		cat < $TMP_FILE >>/etc/aliases
		rm $TMP_FILE
	fi

	#
	# uninstall postfix/sasl/smtpd.conf
	#
	echoIfVerbose "===> Uninstalling inclusion from postfix/sasl/smtpd.conf"
	if grep "Configured by DTC" $PATH_POSTFIX_ETC/sasl/smtpd.conf >/dev/null 2>&1
	then
		start_line=`grep -n "Configured by DTC" $PATH_POSTFIX_ETC/sasl/smtpd.conf | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" $PATH_POSTFIX_ETC/sasl/smtpd.conf | cut -d":" -f1`
		nbr_line=`cat $PATH_POSTFIX_ETC/sasl/smtpd.conf | wc -l`
		TMP_FILE=`${MKTEMP} DTC_uninstall.postfix.sasl.XXXXXX` || exit 1
		cat $PATH_POSTFIX_ETC/sasl/smtpd.conf | head -n $(($start_line - 1 )) > $TMP_FILE
		cat $PATH_POSTFIX_ETC/sasl/smtpd.conf | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		cp -f $PATH_POSTFIX_ETC/sasl/smtpd.conf $PATH_POSTFIX_CONF.DTC.removed
		echo -n > $PATH_POSTFIX_ETC/sasl/smtpd.conf
		cat < $TMP_FILE >> $PATH_POSTFIX_ETC/sasl/smtpd.conf
	        rm $TMP_FILE
	fi
	
	#
	# uninstall /etc/init.d/dkfilter modifications
	#
	if [ -e /etc/init.d/dkfilter ] ; then
		echoIfVerbose "===> Uninstalling inclusion from /etc/init.d/dkfilter"
		if grep "Configured by DTC" /etc/init.d/dkfilter >/dev/null 2>&1
		then
			start_line=`grep -n "Configured by DTC" /etc/init.d/dkfilter | cut -d":" -f1`
			end_line=`grep -n "End of DTC configuration" /etc/init.d/dkfilter | cut -d":" -f1`
			nbr_line=`cat /etc/init.d/dkfilter | wc -l`
			TMP_FILE=`${MKTEMP} DTC_uninstall.dkfilter.init.XXXXXX` || exit 1
			cat /etc/init.d/dkfilter | head -n $(($start_line - 1 )) > $TMP_FILE
			cat /etc/init.d/dkfilter | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
			cp -f /etc/init.d/dkfilter /etc/init.d/dkfilter.DTC.removed
			echo -n > /etc/init.d/dkfilter
			cat < $TMP_FILE >> /etc/init.d/dkfilter
				rm $TMP_FILE
		fi
	fi
}

uninstallAmavisConf () {
	#
	# uninstall amavis/amavisd.conf
	#

	PATH_AMAVISD_ETC=`dirname $PATH_AMAVISD_CONF`
	# if there is no amavisd conf, but there is a conf.d, delete a 99-dtc file
	if [ ! -f "$PATH_AMAVISD_CONF" -a -e $PATH_AMAVISD_ETC/conf.d/99-dtc ] ; then
	        rm $PATH_AMAVISD_ETC/conf.d/99-dtc
	fi

	echoIfVerbose "===> Uninstalling inclusion from amavis/amavisd.conf"
	if grep "Configured by DTC" $PATH_AMAVISD_CONF >/dev/null 2>&1
	then
		start_line=`grep -n "Configured by DTC" $PATH_AMAVISD_CONF | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" $PATH_AMAVISD_CONF| cut -d":" -f1`
		nbr_line=`cat $PATH_AMAVISD_CONF | wc -l`
		TMP_FILE=`${MKTEMP} DTC_uninstall.amavisd.conf.XXXXXX` || exit 1
		cat $PATH_AMAVISD_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
		cat $PATH_AMAVISD_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		cp -f $PATH_AMAVISD_CONF $PATH_AMAVISD_CONF.DTC.removed
		echo -n > $PATH_AMAVISD_CONF
		cat < $TMP_FILE >> $PATH_AMAVISD_CONF
	        rm $TMP_FILE
	fi
}

uninstallQmail () {
	#
	# Uninstall qmail
	#
	echoIfVerbose "===> Uninstalling from qmail"
	if [ -e /var/qmail ]
	then
		if [ -e /var/qmail/control/rcpthosts.DTC.backup ] ; then
			cp -f /var/qmail/control/rcpthosts.DTC.backup /var/qmail/control/rcpthosts
		fi

		if [ -e /var/qmail/control/virtualdomains.DTC.backup ] ; then
			cp -f /var/qmail/control/virtualdomains.DTC.backup /var/qmail/control/virtualdomains
		fi

		if [ -e /var/qmail/control/users/assign.DTC.backup ] ; then
			cp -f /var/qmail/control/users/assign.DTC.backup /var/qmail/control/users/assign
		fi

		if [ -e /etc/poppasswd.DTC.backup ] ; then
			cp -f /etc/poppasswd.DTC.backup /etc/poppasswd
		fi
	fi
}

uninstallSshVhostsConfig () {
	# Uninstall sudoers and shell
	# check for some path defaults...
	if [ -z "$PATH_SUDO" ] ; then
	        PATH_SUDO=`which sudo`
	fi
	if [ -z "$PATH_CHROOT" ] ; then
	        PATH_CHROOT=`which chroot`
	fi
	if [ -z "$PATH_SHELLS_CONF" ] ; then
	        PATH_SHELLS_CONF=/etc/shells
	fi
	if [ -z "$PATH_SUDOERS_CONF" ] ; then
	        PATH_SUDOERS_CONF=/etc/sudoers
	fi
	echoIfVerbose "===> Uninstalling inclusion from $PATH_SUDOERS_CONF"
	if grep "Configured by DTC" $PATH_SUDOERS_CONF >/dev/null 2>&1
	then
	        start_line=`grep -n "Configured by DTC" $PATH_SUDOERS_CONF | cut -d":" -f1`
	        end_line=`grep -n "End of DTC configuration" $PATH_SUDOERS_CONF | cut -d":" -f1`
	        nbr_line=`cat $PATH_SUDOERS_CONF | wc -l`
	        TMP_FILE=`${MKTEMP} DTC_uninstall.sudoers.XXXXXX` || exit 1
	        cat $PATH_SUDOERS_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
	        cat $PATH_SUDOERS_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
	        cp -f $PATH_SUDOERS_CONF $PATH_SUDOERS_CONF.DTC.removed
	        echo -n > $PATH_SUDOERS_CONF
	        cat < $TMP_FILE >> $PATH_SUDOERS_CONF
	        rm $TMP_FILE
	fi

	echoIfVerbose "===> Uninstalling inclusion from $PATH_SHELLS_CONF"
	if grep "Configured by DTC" $PATH_SHELLS_CONF >/dev/null 2>&1
	then
	        start_line=`grep -n "Configured by DTC" $PATH_SHELLS_CONF | cut -d":" -f1`
	        end_line=`grep -n "End of DTC configuration" $PATH_SHELLS_CONF | cut -d":" -f1`
	        nbr_line=`cat $PATH_SHELLS_CONF | wc -l`
	        TMP_FILE=`${MKTEMP} DTC_uninstall.shells.XXXXXX` || exit 1
	        cat $PATH_SHELLS_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
	        cat $PATH_SHELLS_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
	        cp -f $PATH_SHELLS_CONF $PATH_SHELLS_CONF.DTC.removed
	        echo -n > $PATH_SHELLS_CONF
	        cat < $TMP_FILE >> $PATH_SHELLS_CONF
	        rm $TMP_FILE
	fi

	if [ -z "$PATH_SSH_CONF" ] ; then
	        PATH_SSH_CONF=/etc/ssh/sshd_config
	fi
	echoIfVerbose "===> Uninstalling inclusion from $PATH_SSH_CONF"
	if grep "Configured by DTC" $PATH_SSH_CONF >/dev/null 2>&1
	then
	        start_line=`grep -n "Configured by DTC" $PATH_SSH_CONF | cut -d":" -f1`
		end_line=`grep -n "End of DTC configuration" $PATH_SSH_CONF | cut -d":" -f1`
		nbr_line=`cat $PATH_SSH_CONF | wc -l`
		TMP_FILE=`${MKTEMP} DTC_uninstall.ssh.XXXXXX` || exit 1
		cat $PATH_SSH_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
		cat $PATH_SSH_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
		cp -f $PATH_SSH_CONF $PATH_SSH_CONF.DTC.removed
		echo -n > $PATH_SSH_CONF
		cat < $TMP_FILE >> $PATH_SSH_CONF
		rm $TMP_FILE
	fi

	# stuff to remove from NSS mysql config / password

	if [ -z "$PATH_NSS_CONF" ] ; then
	        PATH_NSS_CONF=/etc/nss-mysql.conf
	fi
	echoIfVerbose "===> Uninstalling inclusion from $PATH_NSS_CONF"
	if grep "Configured by DTC" $PATH_NSS_CONF >/dev/null 2>&1
	then
	        start_line=`grep -n "Configured by DTC" $PATH_NSS_CONF | cut -d":" -f1`
	        end_line=`grep -n "End of DTC configuration" $PATH_NSS_CONF | cut -d":" -f1`
	        nbr_line=`cat $PATH_NSS_CONF | wc -l`
	        TMP_FILE=`${MKTEMP} DTC_uninstall.nss-mysql.XXXXXX` || exit 1
	        cat $PATH_NSS_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
	        cat $PATH_NSS_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
	        cp -f $PATH_NSS_CONF $PATH_NSS_CONF.DTC.removed
	        echo -n > $PATH_NSS_CONF
	        cat < $TMP_FILE >> $PATH_NSS_CONF
	        rm $TMP_FILE
	fi

	# stuff to remove from NSS mysql root config / shadow

	if [ -z "$PATH_NSS_ROOT_CONF" ] ; then
	        PATH_NSS_ROOT_CONF=/etc/nss-mysql-root.conf
	fi
	echoIfVerbose "===> Uninstalling inclusion from $PATH_NSS_ROOT_CONF"
	if grep "Configured by DTC" $PATH_NSS_ROOT_CONF >/dev/null 2>&1
	then
	        start_line=`grep -n "Configured by DTC" $PATH_NSS_ROOT_CONF | cut -d":" -f1`
	        end_line=`grep -n "End of DTC configuration" $PATH_NSS_ROOT_CONF | cut -d":" -f1`
	        nbr_line=`cat $PATH_NSS_ROOT_CONF | wc -l`
	        TMP_FILE=`${MKTEMP} DTC_uninstall.nss-mysql-root.XXXXXX` || exit 1
	        cat $PATH_NSS_ROOT_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
	        cat $PATH_NSS_ROOT_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
	        cp -f $PATH_NSS_ROOT_CONF $PATH_NSS_ROOT_CONF.DTC.removed
	        echo -n > $PATH_NSS_ROOT_CONF
	        cat < $TMP_FILE >> $PATH_NSS_ROOT_CONF
	        rm $TMP_FILE
	fi

	if [ -z "$PATH_NSSWITCH_CONF" ] ; then
	        PATH_NSSWITCH_CONF=/etc/nsswitch.conf
	fi

	# remove the stuff from nsswitch.conf
	echoIfVerbose "===> Uninstalling inclusion from $PATH_NSSWITCH_CONF"
	if grep "Configured by DTC" $PATH_NSSWITCH_CONF >/dev/null 2>&1
	then
	        start_line=`grep -n "Configured by DTC" $PATH_NSSWITCH_CONF | cut -d":" -f1`
	        end_line=`grep -n "End of DTC configuration" $PATH_NSSWITCH_CONF | cut -d":" -f1`
	        nbr_line=`cat $PATH_NSSWITCH_CONF | wc -l`
	        TMP_FILE=`${MKTEMP} DTC_uninstall.nsswitch.XXXXXX` || exit 1
	        cat $PATH_NSSWITCH_CONF | head -n $(($start_line - 1 )) > $TMP_FILE
	        cat $PATH_NSSWITCH_CONF | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
	        cp -f $PATH_NSSWITCH_CONF $PATH_NSSWITCH_CONF.DTC.removed
	        echo -n > $PATH_NSSWITCH_CONF
	        cat < $TMP_FILE >> $PATH_NSSWITCH_CONF
	        rm $TMP_FILE
	fi
}

uninstallETC_CONFD_APACHE2 () {
	APACHE2_CONFD="/etc/conf.d/apache2"
	if [ -e ${APACHE2_CONFD} ] ; then
		echoIfVerbose "===> Uninstalling inclusion from $APACHE2_CONFD"
		if grep "Configured by DTC" $APACHE2_CONFD >/dev/null 2>&1
		then
			start_line=`grep -n "Configured by DTC" $APACHE2_CONFD | cut -d":" -f1`
			end_line=`grep -n "End of DTC configuration" $APACHE2_CONFD | cut -d":" -f1`
			nbr_line=`cat $APACHE2_CONFD | wc -l`
			TMP_FILE=`${MKTEMP} DTC_uninstall.conf.d_apache2.XXXXXX` || exit 1
			cat $APACHE2_CONFD | head -n $(($start_line - 1 )) > $TMP_FILE
			cat $APACHE2_CONFD | tail -n $(($nbr_line - $end_line )) >> $TMP_FILE
			cp -f $APACHE2_CONFD $APACHE2_CONFD.DTC.removed
			echo -n > $APACHE2_CONFD
			cat < $TMP_FILE >> $APACHE2_CONFD
			rm $TMP_FILE
		fi
	fi
}

############################ HERE STARTS THE GENERAL CALLING SCRIPTS ###############################
saveConfig () {
	if [ -z ""$DTC_SAVED_INSTALL_CONFIG ] ; then
		DTC_SAVED_INSTALL_CONFIG="/root/.dtc_saved_config"
	fi
	oldumask=`umask`
	umask 0700
        echo "
conf_mysqlautoconfig=\"${conf_mysqlautoconfig}\"
conf_mysql_host=\"${conf_mysql_host}\"
conf_mysql_login=\"${conf_mysql_login}\"
conf_mysql_pass=\"${conf_mysql_pass}\"
conf_mysql_db=\"${conf_mysql_db}\"
conf_mysql_change_root=\"${conf_mysql_change_root}\"
conf_mta_type=${conf_mta_type}
conf_use_cyrus=${conf_use_cyrus}
conf_cyrus_pass=\"${conf_cyrus_pass}\"
dtc_admin_subdomain=\"${dtc_admin_subdomain}\"
main_domain_name=\"${main_domain_name}\"
conf_enforce_adm_encryption=\"${conf_enforce_adm_encryption}\"
conf_adm_login=\"${conf_adm_login}\"
conf_adm_pass=\"${conf_adm_pass}\"
conf_ip_addr=${conf_ip_addr}
conf_use_nated_vhosts=\"${conf_use_nated_vhosts}\"
conf_nated_vhosts_ip=${conf_nated_vhosts_ip}
conf_apache_version=${conf_apache_version}
conf_hosting_path=\"${conf_hosting_path}\"
conf_chroot_path=\"${conf_chroot_path}\"
conf_eth2monitor=\"${conf_eth2monitor}\"
conf_recipient_delim=\"${conf_recipient_delim}\"
conf_mx_mail=\"${conf_mx_mail}\"
conf_dnsbl_list=\"${conf_dnsbl_list}\"
conf_report_setup=${conf_report_setup}
conf_omit_dev_mknod=${conf_omit_dev_mknod}
conf_gen_ssl_cert=${conf_gen_ssl_cert}
conf_cert_passphrase=\"${conf_cert_passphrase}\"
conf_cert_countrycode=${conf_cert_countrycode}
conf_cert_statecode=${conf_cert_statecode}
conf_cert_locality=\"${conf_cert_locality}\"
conf_cert_organization=\"${conf_cert_organization}\"
conf_cert_unit=\"${conf_cert_unit}\"
conf_cert_email=\"${conf_cert_email}\"
conf_cert_challenge_pass=\"${conf_cert_challenge_pass}\"
" >${DTC_SAVED_INSTALL_CONFIG}
	if [ -n "${conf_ftp_type}" ] ; then
		echo "conf_ftp_type=\"${conf_ftp_type}\"" >>${DTC_SAVED_INSTALL_CONFIG}
	fi
	if [ -n "${conf_mta_type}" ] ; then
		echo "conf_mta_type=\"${conf_mta_type}\"" >>${DTC_SAVED_INSTALL_CONFIG}
	fi
	chmod 0600 ${DTC_SAVED_INSTALL_CONFIG}
	umask $oldumask
}

applyAllDTCPatches () {
	if [ "$UNIX_TYPE" = "debian" ] ; then
		dtcPatchFile /etc/default/spamassassin ${PATH_DTC_ADMIN}/patches/spamassassin_default_start.patch  0bfc320c160847ca4525f957833b345e ac43b86acaa45965020a3492991f684d
	fi
}

deApplyAllDTCPatches () {
	if [ "$UNIX_TYPE" = "debian" ] ; then
		dtcUnpatchFile /etc/default/spamassassin ${PATH_DTC_ADMIN}/patches/spamassassin_default_start.patch  0bfc320c160847ca4525f957833b345e ac43b86acaa45965020a3492991f684d
	fi
}

DTCsearchConfigFiles () {
	searchPATH_PHP_CGI
	searchPHPversion
	searchPATH_PHP_INI_APACHE
	searchPATH_PHP_INI_CLI
	searchDebianVersion
	searchMYSQL_DB_SOCKET_PATH
	searchPATH_SUDO
	setDtcdbPassword
}

DTCinstallPackage () {
	createDTCuserAndGroup
	DTCsearchConfigFiles

	if [ "$UNIX_TYPE" = "debian" ] ; then
		if [ "$DEBIAN_VERSION" = "3.1" ] ; then
			modifyPHP_INI_EXTENSIONS
		fi
	fi
	if [ "$UNIX_TYPE" = "debian" ] ; then
		saveConfig
	fi
}

DTCuninstallPackage () {
	createDTCuserAndGroup
	DTCsearchConfigFiles
	deleteGeneratedFiles
}

DTCuninstallDaemons () {
	deApplyAllDTCPatches
	createDTCuserAndGroup
	DTCsearchConfigFiles
	uninstallCrontab
	uninstallNamed
	uninstallHttpdConfig
	uninstallETC_CONFD_APACHE2
	uninstallCourierConfig
	uninstallDevecotConfig
	uninstallProftpdConfig
	uninstallPostfix
	uninstallAmavisConf
	uninstallQmail
	uninstallSshVhostsConfig
}

DTCsetupDaemons () {
	createDTCuserAndGroup
	DTCsearchConfigFiles

	if [ -z ${DTC_SAVED_INSTALL_CONFIG} ] ; then
		DTC_SAVED_INSTALL_CONFIG=/root/.dtc_saved_config
	fi

	. ${DTC_SAVED_INSTALL_CONFIG}

	# These are moved from install package to setup daemons
	generateMySQLConfigPHPfile
	createDTCRootShellScript
	createApachePIDSymLink
	enableApache2Modules
	findHtpasswdBinary
	createApacheAdminProtectedDir
	generateOpenSSLApacheCert
	createCyrusAuthPhp
	createRRDFiles
	reportingInstall

	applyAllDTCPatches
#	dtcGenDebianLocales

	modifyResolvConf
	createChrootTemplate
	findHtpasswdBinary
	if [ ! "$UNIX_TYPE" = "debian" ] ; then
		changeMySQLPassword
	fi
	setupDTCDatabase
	createHostingDirAndFiles
	chownSquirrelAndFastcgiToDtcUserAndGroup
	modifySUODERS_DOT_CONF
	increasePhpIniMemAndExecTime
	changeApacheUserAndGroup
	modifyHTTPD_CONF
	modifyETC_CONFD_APACHE2
	modifyNamedConf
	linkQmailFilesToGenerated
	setupAmavisConf
	modifyClamavConf
	modifyCyrusPath
	# CL: Skip saslauthd when using sasl_sql
	if [ ! -f $PATH_SASLLIB/libsql.so ] ; then
  	modifySaslStartAndSaslStartup
	else
		echoIfVerbose "Using sasl_sql instead of saslauthd, skipping configuration of saslauthd"
	fi
	modifyPostfixConfig
	modifyCyrusImapdConf
	prepareMlmmjSpool
	# CL: don't call Courier Config if using cyrus! This will break the installation
	# /var/lib/dtc/etc/quotawarnmsg: No such file or directory
	if [ ""$conf_use_cyrus != "true" ] ; then
	  modifyCourierConfig
	fi
	modifyDovecotConfig
	modifyPureFtpdMySQLConfig
	configProftpd
	configFreeRadius
	modifyAWStatsConfig
	modifySSHDConfig
	modifyNSSConfig
	modifyMysqmail
	modifyCrontab
	fixesExtplorer
	if [ $UNIX_TYPE = freebsd ]
	then
		if grep "End of DTC configuration" /etc/rc.conf >/dev/null ; then
			#/etc/rc.conf already configured before
			echo -n ""
		else
			echo "### End of DTC configuration - please do not remove" >>/etc/rc.conf
		fi
	fi

	startPhpCronScript
	echoEndMessage
	exit 0
}
