#!/bin/bash
#
# This script is written by DirectAdmin and Martynas Bendorius (smtalk)

# Global environment variables that controls CB:
#   CB_TIMESTAMP      UNIX timestamp when CB script is started, used in the log-file name

WORKDIR=/usr/local/directadmin/custombuild
OPTIONS_CONF=${WORKDIR}/options.conf
PHP_EXTENSIONS_CONF=${WORKDIR}/php_extensions.conf
VERSIONS_FILE=${WORKDIR}/versions.txt
VERSIONS_FILE_CUSTOM=${WORKDIR}/custom_versions.txt
PIDFILE=${WORKDIR}/.custombuild
LOCKFILE=${WORKDIR}/.custombuild.lock
LOGFILE=${WORKDIR}/custombuild.log
CB_TMP_DIR=${WORKDIR}/tmp
CB_CACHE_DIR=${WORKDIR}/cache
OUTPUT_LOG_FILE="/var/log/directadmin/custombuild.${CB_TIMESTAMP:-$(date +%s)}.$$.log"
DA_BIN=/usr/local/directadmin/directadmin
LSWS_HOME=/usr/local/lsws
CB_LOGROTATE=${WORKDIR}/configure/logrotate
CB_CUST_LOGROTATE=${WORKDIR}/custom/logrotate
SYSTEMDDIR=/etc/systemd/system
CB_SYSTEMD=${WORKDIR}/configure/systemd
CB_CUST_SYSTEMD=${WORKDIR}/custom/systemd
CB_ARGS_STRING=$*
SYSTEMD_SCRIPTS=/usr/libexec


# To make sure there are no default grep options set in .bashrc, no longer
# by grep > 2.10, can be removed after CentOS 7 is EOL.
export GREP_OPTIONS=""

# To have uniform output format and avoid locale warnings.
export LANG=C

# Make sure apt-get does not wait for user input and omit debconf warnings.
export DEBIAN_FRONTEND=noninteractive
export DEBCONF_NOWARNINGS=yes

################################################################################
# Helper functions                                                             #
################################################################################

# distro_is_debian returns true if host is running debian or debian derivative
# distro. It is recommended to use this function as it caches the distro test
# result making multiple checks cheaper.
distro_is_debian() {
	if [ -z "${distro_is_debian_rc:-}" ]; then
		if [ -e /etc/debian_version ]; then
			distro_is_debian_rc=0
			distro_is_debian_version=$(grep -m 1 -o '^[^/\.]*' /etc/debian_version)
			case "${distro_is_debian_version}" in
				woody|sarge) distro_is_debian_version=3 ;;
				etch)        distro_is_debian_version=4 ;;
				lenny)       distro_is_debian_version=5 ;;
				squeeze)     distro_is_debian_version=6 ;;
				wheezy)      distro_is_debian_version=7 ;;
				jessie)      distro_is_debian_version=8 ;;
				stretch)     distro_is_debian_version=9 ;;
				buster)      distro_is_debian_version=10 ;;
				bullseye)    distro_is_debian_version=11 ;;
				bookworm)    distro_is_debian_version=12 ;;
				trixie)      distro_is_debian_version=13 ;;
				forky)       distro_is_debian_version=14 ;;
			esac
		else
			distro_is_debian_rc=1
			distro_is_debian_version=""
		fi
	fi
	return "${distro_is_debian_rc}"
}

debian_version() {
	# We rely on `distro_is_debian` to set this variable.
	distro_is_debian && echo "${distro_is_debian_version}"
}

debian_version_is() {
	if distro_is_debian && [ "${distro_is_debian_version}" = "$1" ]; then
		return 0
	fi
	return 1
}

# distro_is_rhel returns true ifhost is running RHEL or RHEL derivative distro.
distro_is_rhel() {
	if [ -z "${distro_is_rhel_rc:-}" ]; then
		if [ -e /etc/redhat-release ]; then
			distro_is_rhel_rc=0
			distro_is_rhel_version=$(grep -m 1 -o '[0-9]\+' /etc/redhat-release | head -n 1)
		else
			distro_is_rhel_rc=1
		fi
	fi
	return "${distro_is_rhel_rc}"
}

rhel_version() {
	# We rely on `distro_is_rhel` to set this variable.
	distro_is_rhel && echo "${distro_is_rhel_version}"
}

rhel_version_is() {
	if distro_is_rhel && [ "${distro_is_rhel_version}" = "$1" ]; then
		return 0
	fi
	return 1
}

is_cloudlinux_solo() {
	if [ -e /etc/cloudlinux-edition-solo ]; then
		return 0
	fi
	return 1
}

is_freebsd() {
	if [ "$(uname)" = "FreeBSD" ]; then
		return 0
	fi
	return 1
}

is_arm64() {
	if [ -z "${uname_m:-}" ]; then
		uname_m=$(uname -m)
	fi
	if [ "${uname_m}" = "aarch64" ]; then
		return 0
	fi
	return 1
}

ensure_fresh_apt_cache() {
	if [ -z "${fresh_apt_cache:-}" ]; then
		apt-get --quiet --yes update
		fresh_apt_cache=yes
	fi
}

# install_debs takes package list as an argument and ensures
# that these packages are installed.
#
# It is safe to call this function on non debian hosts it will be a noop.
install_debs() {
	if ! distro_is_debian; then
		return 0
	fi

	if has_debs_installed "$@"; then
		return 0
	fi

	ensure_fresh_apt_cache

	local rc=1
	local attempts=3
	for i in $(seq 1 "${attempts}"); do
		if apt-get --quiet --yes install "$@"; then
			rc=0
			break
		fi
		echo "Installing packages '$*' using apt-get attempt ${i}/${attempts} failed" >&2
		if [ "$i" -ne "${attempts}" ]; then
			sleep 5
		fi
	done
	return $rc
}

# reinstall_debs - ensures a list of packages are re-installed, one of the
# following actions will always be performed:
#     - package is installed if it was not present on the system
#     - package is upgraded if newer version is available
#     - package is re-installed if it is already up to date
reinstall_debs() {
	if ! distro_is_debian; then
		return 0
	fi
	ensure_fresh_apt_cache
	apt-get --quiet --yes --reinstall install "$@"
}

# has_debs_installed will exit with RC=0 if all packages passed as
# arguments are installed.
has_debs_installed() {
	local count
	count=$(dpkg-query -W --showformat='${db:Status-Status}\n' "$@" 2>&1 | grep -c '^installed')
	if [ "${count}" -ne "$#" ]; then
		return 1
	fi
	return 0
}

# enable_epel_repo ensures EPEL repository is enabled.
enable_epel_repo() {
	local epel_package=epel-release
	if [ -e /etc/yum.repos.d/oracle-linux-ol8.repo ]; then
		epel_package=oraclelinux-release-el8
	fi
	if has_rpms_installed "${epel_package}"; then
		return 0
	fi
	yum --quiet --assumeyes install "${epel_package}"
}

# enable_crb_repo make sure Code Ready Builder (or anologous) repository is
# enabled.
enable_crb_repo() {
	local repo
	repo=$(grep -m 1 -h '\[\(powertools\|crb\|PowerTools\|cloudlinux-PowerTools\|ol8_codeready_builder\|codeready-builder-for-rhel-8-x86_64-rpms\)]' /etc/yum.repos.d/* | head -n 1 | tr -d '[]')
	if [ -n "${repo}" ]; then
		if ! has_rpms_installed dnf-plugins-core; then
			yum --quiet --assumeyes install dnf-plugins-core
		fi
		dnf config-manager --set-enabled "${repo}"
	fi
}

ensure_rhel_distros_enabled() {
	if [ -z "${rhel_distros_enabled:-}" ]; then
		enable_epel_repo
		enable_crb_repo
		rhel_distros_enabled=true
	fi
}

# install_rpms takes package list an argument and ensured that
# these packages are installed.
#
# It is safe to call this function on non RHEL hosts it will be a noop.
install_rpms() {
	if ! distro_is_rhel; then
		return 0
	fi

	if has_rpms_installed "$@"; then
		return 0
	fi
	ensure_rhel_distros_enabled
	yum --quiet --assumeyes install "$@"
}

# reinstall_rpms - ensures a list of packages are re-installed, one of the
# following actions will always be performed:
#     - package is installed if it was not present on the system
#     - package is upgraded if newer version is available
#     - package is re-installed if it is already up to date
reinstall_rpms() {
	if ! distro_is_rhel; then
		return 0
	fi

	ensure_rhel_distros_enabled
	if ! has_rpms_installed "$@"; then
		yum --quiet --assumeyes install "$@"
		return
	fi
	yum --quiet --quiet check-update "$@" > /dev/null
	if [ $? -eq 100 ]; then
		yum --quiet --assumeyes update "$@"
		return
	fi
	yum --quiet --assumeyes reinstall "$@"
}

# has_rpms_installed will exit with RC=0 if all packages passed as
# arguments are installed.
has_rpms_installed() {
	rpm --quiet --query "$@"
}

raw_url_encode() {
	local string="${1}"
	local strlen=${#string}
	local encoded=""
	local pos c o

	for (( pos=0 ; pos<strlen ; pos++ )); do
		c=${string:$pos:1}
		case "$c" in
			[-_.~a-zA-Z0-9])
				o="${c}"
				;;
			*)
				printf -v o '%%%02X' "'$c"
				;;
		esac
		encoded+="${o}"
	done
	echo "${encoded}"
}

send_da_message() {
	local subject message
	subject=$(raw_url_encode "$1")
	message=$(raw_url_encode "$2")

	"${DA_BIN}" taskq --run "action=notify&value=admin&subject=${subject}&message=${message}"
}

enable_logging() {
	exec 99>&2 > >(tee -ia "${OUTPUT_LOG_FILE}") 2> >(tee -ia "${OUTPUT_LOG_FILE}" 1>&99)
	# Remove old log files, leave 30 last ones
	# shellcheck disable=SC2010
	(cd /var/log/directadmin && ls -tp | grep '^custombuild\..*\.log$' | tail -n +31 | xargs -d '\n' -r rm --)
	writeLog "called: ${CB_ARGS_STRING}"
}

has_mariadb() {
	if [ -z "${has_mariadb_rc:-}" ]; then
		${MYSQL_BIN} --version | grep -q MariaDB
		has_mariadb_rc=$?
	fi
	return "${has_mariadb_rc}"
}

# load_php_extensions_conf does:
#   - create `php_extensions_conf` hashmap with values configured in config file
#     or passed via environment as `php_...` variables.
#   - make sure config file exists and has all config lines, missing ones are
#     added with default values.
#
# This function needs to be called at the begining of CB to ensure
# `php_extensions_conf` is available for the rest of the script.
load_php_extensions_conf() {
	declare -gA php_extensions_conf

	# Load variable defaults, allow exported variables to override them
	declare -A from_defaults
	local setting
	for setting in ${PHP_EXT_SETTINGS}; do
		local def_var="PHP_${setting}_DEF"
		local env_var="php_${setting,,}"
		if [ -n "${!env_var}" ]; then
			from_defaults[${setting,,}]=${!env_var}
		else
			from_defaults[${setting,,}]=${!def_var}
		fi
	done

	# Load variables from file
	declare -A from_file
	declare -A found
	if [ -f "${PHP_EXTENSIONS_CONF}" ]; then
		local key
		local val
		while IFS='=' read -r key val; do
			if [ -z "${found[${key##php_}]}" ]; then
				from_file[${key##php_}]=$val
				found[${key##php_}]=yes
			fi
		done < <(grep -o "^[^#=]\+=[^# ]\+" "${PHP_EXTENSIONS_CONF}")
	fi

	# Merge defaults and options from file
	local key
	for key in "${!from_defaults[@]}"; do
		if [ -z "${from_file[$key]}" ]; then
			php_extensions_conf[$key]="${from_defaults[$key]}"
		else
			php_extensions_conf[$key]="${from_file[$key]}"
		fi
	done
}

write_php_extensions_conf() {
	if [[ ! -v php_extensions_conf[@] ]]; then
		load_php_extensions_conf
	fi

	local tmp_file
	if ! tmp_file=$(mktemp --tmpdir="${CB_TMP_DIR}" --suffix=.php_extensions.conf); then
		echo "${FUNCNAME[0]}: failed to create temp file in '${CB_TMP_DIR}'" 1>&2
		return 1
	fi

	(
		trap 'rm -f "${tmp_file}"' EXIT
		set -e
		echo "# ${PHP_EXT_SETTINGS_DESC}" >> "${tmp_file}"
		local setting
		for setting in ${PHP_EXT_SETTINGS}; do
			setting=${setting,,}
			echo "${setting}=${php_extensions_conf[${setting}]}" >> "${tmp_file}"
		done
		chmod 644 "${tmp_file}"
		mv -f "${tmp_file}" "${PHP_EXTENSIONS_CONF}"
	)
}


# load_options_conf does:
#   - create `options_conf` hashmap with values configured in config file
#     or passed via environment as variables.
#   - create `options_conf_php` hashmap, which stores PHP configuration as a map
#     from "php{n}_release" value to "php{n}_mode" value.
#   - make sure config file exists and has all config lines, missing ones are
#     added with default values.
#
# This function needs to be called at the begining of CB to ensure
# `options_conf` is available for the rest of the script.
load_options_conf() {
	declare -gA options_conf
	declare -gA options_conf_php

	# Load variable defaults, allow exported variables to override them
	declare -A from_defaults
	local setting section
	for section in $ALL_SECTIONS; do
		if [ "${section}" = "PHP_EXT_SETTINGS" ]; then
			continue
		fi
		for setting in ${!section}; do
			local def_var="${setting}_DEF"
			local env_var="${setting,,}"
			if [ -n "${!env_var}" ]; then
				from_defaults[${setting,,}]=${!env_var}
			else
				from_defaults[${setting,,}]=${!def_var}
			fi
		done
	done

	# Load variables from file
	declare -A from_file
	declare -A found
	if [ -f "${OPTIONS_CONF}" ]; then
		local key val
		while IFS='=' read -r key val; do
			if [ -z "${found[${key}]}" ]; then
				from_file[${key}]=$val
				found[${key}]=yes
			fi
		done < <(grep -o "^[^#=]\+=[^# ]\+" "${OPTIONS_CONF}")
	fi

	# Merge defaults and options from file
	local key
	for key in "${!from_defaults[@]}"; do
		if [ -z "${from_file[$key]}" ]; then
			options_conf[$key]="${from_defaults[$key]}"
		else
			options_conf[$key]="${from_file[$key]}"
		fi
	done

	local i
	for i in 1 2 3 4; do
		local release=${options_conf["php${i}_release"]}
		local mode=${options_conf["php${i}_mode"]}
		if [ -z "${release}" ] || [ "${release}" == "no" ]; then
			continue
		fi
		options_conf_php["${release}"]="${mode}"
	done
}

write_options_conf() {
	if [[ ! -v load_options_conf[@] ]]; then
		load_options_conf
	fi

	local tmp_file
	if ! tmp_file=$(mktemp --tmpdir="${CB_TMP_DIR}" --suffix=.options.conf); then
		echo "${FUNCNAME[0]}: failed to create temp file in '${CB_TMP_DIR}'" 1>&2
		return 1
	fi

	(
		trap 'rm -f "${tmp_file}"' EXIT
		set -e
		local section setting
		for section in $ALL_SECTIONS; do
			if [ "${section}" = "PHP_EXT_SETTINGS" ]; then
				continue
			fi
			local desc_var="${section}_DESC"
			echo "# ${!desc_var}" >> "${tmp_file}"
			for setting in ${!section}; do
				setting=${setting,,}
				echo "${setting}=${options_conf[${setting}]}" >> "${tmp_file}"
			done
			echo "" >> "${tmp_file}"
		done
		chmod 644 "${tmp_file}"
		mv -f "${tmp_file}" "${OPTIONS_CONF}"
	)
}

exec_with_lock() {
	local rc
        (
		if ! flock --exclusive --nonblock 199; then
			echo "Another instance of custombuild (PID $(cat "${PIDFILE}")) is holding the lock on \"${LOCKFILE}\", exiting" 1>&2
			exit 199
		fi
		echo $$ > "${PIDFILE}"
		trap 'rm -f "${PIDFILE}"' EXIT
		"$@"
	) 199> "${LOCKFILE}"
	rc=$?
	if [ "${rc}" -ne 0 ]; then
		exit "${rc}"
        fi
}

clean_after() {
	local rc

	"$@"
	rc=$?

	if [ "${CLEAN_OPT}" = "yes" ]; then
		legacy_doClean
	fi
	return "${rc}"
}

safe_download() {
	local dst=$1     # /usr/local/directadmin/custombuild/cache/some-file_v1.2.3.tar.gz
	local url=$2     # https://example.com/some-file_v1.2.3.tar.gz
	local tmp_file

	if ! tmp_file=$(mktemp --tmpdir="${CB_TMP_DIR}" --suffix=.safe_download); then
		echo "${FUNCNAME[0]}: failed to create temp file in '${CB_TMP_DIR}'" 1>&2
		return 1
	fi

	# We could use --retry-all-errors but it is only supported starting curl
	# 7.71.0. Until oldest distro has at least 7.71.0 we need manual retry.
	local attempt=0 attempts=3
	while ! curl --location --progress-bar --connect-timeout 10 --retry 3 --fail -o "${tmp_file}" "${url}"; do
		((attempt++))
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: downloading '${url}' to '${tmp_file}' failed (${attempt}/${attempts})" 1>&2
		if [ "${attempt}" -eq "${attempts}" ]; then
			return 1
		fi
		sleep 3
	done

	if ! mv -f "${tmp_file}" "${dst}"; then
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: failed to rename '${tmp_file}' to '${dst}'" 1>&2
		return 1
	fi
}

download_with_cache() {
	local dst=$1
	local url=$2

	if [ -s "${dst}" ]; then
		echo "${FUNCNAME[0]}: using cached '${dst}' file"
		return 0
	fi

	echo "${FUNCNAME[0]}: downloading '${url}' to '${dst}'"
	safe_download "${dst}" "${url}"
}

path_to_custom_file() {
	# $1=exim/exim.conf
	local main_file="${WORKDIR}/configure/$1"
	local custom_file="${WORKDIR}/custom/$1"

	if [ -e "${custom_file}" ]; then
		echo "${custom_file}"
	else
		echo "${main_file}"
	fi
}

install_custom_file() {
	local file=$1       # exim/exim.conf
	local dst=$2        # /etc/exim.conf
	local file_mode=$3  # 600
	local file_owner=$4 # root:root

	local src
	src=$(path_to_custom_file "${file}")

	local tmp_file
	if ! tmp_file=$(mktemp --tmpdir="$(dirname "${dst}")" --suffix=".$(basename "${dst}")"); then
		echo "${FUNCNAME[0]}: failed to create temp file for '${dst}'" 1>&2
		return 1
	fi
	if ! cp -f "${src}" "${tmp_file}"; then
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: failed to copy '${src}' to '${tmp_file}'" 1>&2
		return 1
	fi
	if ! chmod "${file_mode}" "${tmp_file}"; then
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: chmod '${tmp_file}' to '${file_mode}'" 1>&2
		return 1
	fi
	if ! chown "${file_owner}" "${tmp_file}"; then
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: failed to chown '${tmp_file}' to '${file_owner}'" 1>&2
		return 1
	fi
	if ! mv -f "${tmp_file}" "${dst}"; then
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: failed to rename '${tmp_file}' to '${dst}'" 1>&2
		return 1
	fi
}

install_file() {
	local src=$1        # /usr/local/directadmin/conf/cacert.pem.combined
	local dst=$2        # /etc/exim.cert
	local file_mode=$3  # 600
	local file_owner=$4 # root:root

	local tmp_file
	if ! tmp_file=$(mktemp --tmpdir="$(dirname "${dst}")" --suffix=".$(basename "${dst}")"); then
		echo "${FUNCNAME[0]}: failed to create temp file for '${dst}'" 1>&2
		return 1
	fi

	if ! cp -f "${src}" "${tmp_file}"; then
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: failed to copy '${src}' to '${tmp_file}'" 1>&2
		return 1
	fi
	if ! chmod "${file_mode}" "${tmp_file}"; then
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: chmod '${tmp_file}' to '${file_mode}'" 1>&2
		return 1
	fi
	if ! chown "${file_owner}" "${tmp_file}"; then
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: failed to chown '${tmp_file}' to '${file_owner}'" 1>&2
		return 1
	fi
	if ! mv -f "${tmp_file}" "${dst}"; then
		rm -f "${tmp_file}"
		echo "${FUNCNAME[0]}: failed to rename '${tmp_file}' to '${dst}'" 1>&2
		return 1
	fi
}

compile_pecl_package() {
	local package=$1      # phalcon
	local version=$2      # 5.1.1
	local php_vv=$3       # 81
	local download_url=$4 # https://pecl.php.net/get/${package}-${version}.tgz
	local cached_file="${CB_CACHE_DIR}/${package}-pecl-${version}.tgz"

	download_with_cache "${cached_file}" "${download_url}" || return 1

	(
		local tmp_dir
		if ! tmp_dir=$(mktemp --directory --tmpdir="${CB_TMP_DIR}" --suffix=".${package}-pecl-${version}"); then
			echo "${FUNCNAME[0]}: failed to create temp dir for extracting '${cached_file}'" 1>&2
			return 1
		fi
		trap 'rm -rf "${tmp_dir}"' EXIT

		if ! tar xzf "${cached_file}" --strip-components=1 -C "${tmp_dir}"; then
			echo "${FUNCNAME[0]}: failed to extract '${cached_file}' into '${tmp_dir}'" 1>&2
			return 1
		fi

		set -e
		cd "${tmp_dir}"
		"/usr/local/php${php_vv}/bin/phpize"
		./configure --with-php-config="/usr/local/php${php_vv}/bin/php-config"
		make
		make install
	)
}

################################################################################
# Command handlers                                                             #
################################################################################

command_install() {
	if ! write_options_conf; then
		echo "failed to create/update options.conf file" 1>&2
	fi
	if ! write_php_extensions_conf; then
		echo "failed to create/update php_extensions.conf file" 1>&2
	fi
}

command_all() {
	CB_MESSAGE_ON_EXIT=yes
	if ! doAll; then
		send_da_message \
			"CustomBuild installation has failed" \
			"CustomBuild installation has failed, please check the following file for more information:"$'\n'"${OUTPUT_LOG_FILE}"
		return 1
	fi

	send_da_message \
		"CustomBuild installation has finished" \
		"CustomBuild installation has finished, to check the full log please check:"$'\n'"${OUTPUT_LOG_FILE}"
}

command_set_php() {
	local key="$1"    # PHP extensions option name
	local val="$2"    # PHP extensions option value

	if [[ ! -v php_extensions_conf[@] ]]; then
		load_php_extensions_conf
	fi

	local def_var="PHP_${key^^}_DEF"
	if [ -z "${!def_var}" ]; then
		echo "${key} is not a valid option."
		EXIT_CODE=50
		return
	fi

	if [ "${php_extensions_conf[$key]}" = "${val}" ]; then
		if [ "${HIDE_CHANGES}" = "0" ]; then
			echo "${boldon}${key}${boldoff} is already set to ${boldon}${val}${boldoff}"
		fi
		return
	fi

	local valid="no"
	local set_var="PHP_${key^^}_SET"
	local i
	for i in ${!set_var}; do
		if [ "${i}" = "${val}" ]; then
			valid="yes"
			break
		fi
	done
	if [ "${valid}" = "no" ]; then
		echo "${val} is not a valid setting for ${key} option."
		EXIT_CODE=51
		return
	fi

	local key_escaped
	local val_escaped
	key_escaped=$(sed 's/[.[\*^\/&$]/\\&/g' <<< "${key}")
	val_escaped=$(sed 's/[.[\*^\/&$]/\\&/g' <<< "${val}")
	sed -i "s/^${key_escaped}=.*\$/${key_escaped}=${val_escaped}/" "${PHP_EXTENSIONS_CONF}"

	if [ "${HIDE_CHANGES}" = "0" ]; then
		echo "Changed ${boldon}${key}${boldoff} option from ${boldon}${php_extensions_conf[$key]}${boldoff} to ${boldon}${val}${boldoff}"
	fi
}

command_set() {
	local key="$1"        # $1 is option name
	local val="$2"        # $2 is value

	if [[ ! -v options_conf[@] ]]; then
		load_options_conf
	fi

	local def_var="${key^^}_DEF"
	if [ -z "${!def_var}" ]; then
		echo "${key} is not a valid option."
		EXIT_CODE=50
		return
	fi

	if [ "${options_conf[$key]}" = "${val}" ]; then
		if [ "${HIDE_CHANGES}" = "0" ]; then
			echo "${boldon}${key}${boldoff} is already set to ${boldon}${val}${boldoff}"
		fi
		return
	fi

	local valid="no"
	local set_var="${key^^}_SET"
	local i
	for i in ${!set_var}; do
		if [ "${i}" = "${val}" ] || [ "${i}" = "userinput" ]; then
			valid="yes"
			break
		fi
	done
	if [ "${valid}" = "no" ]; then
		echo "${val} is not a valid setting for ${key} option."
		EXIT_CODE=51
		return
	fi

	local key_escaped
	local val_escaped
	key_escaped=$(sed 's/[.[\*^\/&$]/\\&/g' <<< "${key}")
	val_escaped=$(sed 's/[.[\*^\/&$]/\\&/g' <<< "${val}")
	sed -i "s/^${key_escaped}=.*\$/${key_escaped}=${val_escaped}/" "${OPTIONS_CONF}"

	if [ "${HIDE_CHANGES}" = "0" ]; then
		echo "Changed ${boldon}${key}${boldoff} option from ${boldon}${options_conf[$key]}${boldoff} to ${boldon}${val}${boldoff}"
	fi
}

command_clean_cache() {
	echo "cleaning up download cache dir '${CB_CACHE_DIR}'"
	find "${CB_CACHE_DIR}" -mindepth 1 -maxdepth 1 -exec rm -rvf '{}' \;
}

command_clean() {
	command_clean_cache
	legacy_doClean
}

################################################################################

cd ${WORKDIR}

if [ "$(id -u)" != "0" ]; then
	echo "Script must be executed as root" 1>&2
	exit 1
fi
if is_freebsd; then
	echo "FreeBSD is not supported" 1>&2
	exit 1
fi
if distro_is_debian && [ "$(debian_version)" -lt 9 ]; then
	echo "Debian $(debian_version) is not supported" 1>&2
	exit 1
fi
if distro_is_rhel && [ "$(rhel_version)" -lt 7 ]; then
	echo "RHEL/CentOS $(rhel_version) is not supported" 1>&2
	exit 1
fi


doHook(){
	if [ ! -z "${1}" ] && [ ! -z "${2}" ]; then
		if [ -d ${WORKDIR}/custom/hooks/${1}/${2} ]; then
			find ${WORKDIR}/custom/hooks/${1}/${2} -type f -name '*.sh' | while read line; do
				echo "Executing '$line'..."
				.  "$line"
			done
			HOOK_ERROR_CODE=$?
			if [ ${HOOK_ERROR_CODE} -ne 0 ]; then
				echo "Hook exited with error code: ${HOOK_ERROR_CODE}. Exiting..."
				exit ${HOOK_ERROR_CODE}
			fi

		fi
	fi
}

PROFTPD_PREFIX=/usr

EXEC_CL_COMMANDS_ONCE=false
CL_COMPONENT_UPDATE=false

CPU_CORES=1

EXIT_CODE=0

doKill() {
	if [ -s ${PIDFILE} ]; then
		CB_PID=`cat ${PIDFILE}`
		for process in `ps -ef | awk -v cb_pid=${CB_PID} '{ if ( $3 == cb_pid ) { print $2 }}'`; do
			kill ${process}
		done
		kill -9 ${CB_PID}
		rm -f ${PIDFILE}
		exit 0
	else
		echo "There is no CustomBuild process running."
	fi
	exit 0
}

getTimezone() {
	if distro_is_debian && [ -e /etc/timezone ]; then
			DATETIMEZONE="`cat /etc/timezone`"
	fi
	if distro_is_rhel; then
		if [ -e /etc/sysconfig/clock ]; then
			DATETIMEZONE="`grep -m1 '^ZONE=' /etc/sysconfig/clock | cut -d'"' -f2 | cut -d= -f2`"
		elif [ -e /usr/bin/timedatectl ]; then
			DATETIMEZONE="`timedatectl | grep -m1 'Time.*zone:' | cut -d: -f2 | awk '{print $1}'`"
		fi
	fi
	if [ "${DATETIMEZONE}" = "" ]; then
		DATETIMEZONE="Europe/London"
	fi
	echo ${DATETIMEZONE} | awk '{print $1}'
}

random_pass() {
	#No special characters yet, because they'd cause problems with regexes and PEAR::DB to split the DNS string correctly in roundcube config.inc.php
	RPC=`awk -v min=10 -v max=17 'BEGIN{srand(); print int(min+rand()*(max-min+1))}'`
	tr -cd 'a-zA-Z0-9' < /dev/urandom 2>/dev/null | head -c${RPC} # perl generates a random integer between 10 and 16
}

remove_file() {
	if [ "$1" = "" ]; then
		do_exit 1 "File not specified for remove_file..."
	fi

	if [ -e "$1" ]; then
		echo "Removing file: $1..."
		rm -f "$1"
	fi
}

remove_directory() {
	if [ "$1" = "" ]; then
		do_exit 1 "File not specified for remove_file..."
	fi

	COUNT_SLASHES="`echo \"$1\" | grep -o '/' | wc -l`"
	if [ "${COUNT_SLASHES}" -lt 2 ]; then
		do_exit 1 "Too dangerous path to remove: $1. Exiting..."
	fi

	if [ -d $1 ]; then
		echo "Removing directory: $1..."
		rm -rf $1
	fi
}


create_da_conf_certs() {
    local conf_dir=/usr/local/directadmin/conf
	if [ ! -s "${conf_dir}/cakey.pem" ] || [ ! -s "${conf_dir}/cacert.pem" ]; then
	    openssl req -x509 -newkey rsa:2048 -keyout "${conf_dir}/cakey.pem" -out "${conf_dir}/cacert.pem" -days 9999 -nodes -config ${WORKDIR}/${APCERTCONF} || return 1
	    : > "${conf_dir}/carootcert.pem"  || return 1
        cat "${conf_dir}/cacert.pem" "${conf_dir}/carootcert.pem" > "${conf_dir}/cacert.pem.combined" || return 1
		return 0
	fi

    if [ ! -f "${conf_dir}/carootcert.pem" ]; then
        : > "${conf_dir}/carootcert.pem"  || return 1
    fi

    if [ ! -s "${conf_dir}/cacert.pem.combined" ]; then
        cat "${conf_dir}/cacert.pem" "${conf_dir}/carootcert.pem" > "${conf_dir}/cacert.pem.combined" || return 1
    fi
}

HOSTNAME="`hostname -f 2>/dev/null`"
if [ -z "${HOSTNAME}" ] && [ -x /usr/bin/hostnamectl ]; then
	HOSTNAME=`/usr/bin/hostnamectl --static | head -n1`
	if ! echo "${HOSTNAME}" | grep  -m1 -q '\.'; then
		HOSTNAME=`grep -m1 -o "${HOSTNAME}\.[^ ]*" /etc/hosts`
	fi
fi
if [ -z "${HOSTNAME}" ]; then
	HOSTNAME="your.server.com"
fi

#There are used in other sections, so must be executed everytime
PHP1_RELEASE_SET="5.3 5.4 5.5 5.6 7.0 7.1 7.2 7.3 7.4 8.0 8.1 8.2"
PHP1_SHORTRELEASE_SET="${PHP1_RELEASE_SET//./}"

#################################################
#ALL SETTINGS
#SECTIONS OF OPTIONS
ALL_SECTIONS="PHP_SETTINGS MYSQL_SETTINGS WEBSERVER_SETTINGS WEBAPPS_SETTINGS CLAMAV_SETTINGS MAIL_SETTINGS FTP_SETTINGS STATS_SETTINGS PHP_EXT_SETTINGS CUSTOMBUILD_SETTINGS CRON_SETTINGS CLOUDLINUX_SETTINGS ADVANCED_SETTINGS"

PHP_EXT_SETTINGS="BZ2 GMP IONCUBE IMAP OPCACHE HTSCANNER IGBINARY IMAGICK LDAP PHALCON READLINE REDIS SNUFFLEUPAGUS SUHOSIN XMLRPC ZEND"
PHP_SETTINGS="PHP1_RELEASE PHP1_MODE PHP2_RELEASE PHP2_MODE PHP3_RELEASE PHP3_MODE PHP4_RELEASE PHP4_MODE SECURE_PHP PHP_INI PHP_TIMEZONE PHP_INI_TYPE X_MAIL_HEADER"
MYSQL_SETTINGS="MYSQL MARIADB MYSQL_INST MYSQL_BACKUP MYSQL_BACKUP_GZIP MYSQL_BACKUP_DIR MYSQL_FORCE_COMPILE"
WEBSERVER_SETTINGS="UNIT WEBSERVER HTTP_METHODS LITESPEED_SERIALNO MODSECURITY MODSECURITY_RULESET APACHE_MPM MOD_RUID2 USERDIR_ACCESS HARDEN_SYMLINKS_PATCH USE_HOSTNAME_FOR_ALIAS REDIRECT_HOST REDIRECT_HOST_HTTPS"
WEBAPPS_SETTINGS="PHPMYADMIN PHPMYADMIN_PUBLIC SQUIRRELMAIL ROUNDCUBE WEBAPPS_INBOX_PREFIX"
MAIL_SETTINGS="EXIM EXIMCONF BLOCKCRACKING EASY_SPAM_FIGHTER SPAMD SA_UPDATE DOVECOT DOVECOT_CONF MAIL_COMPRESS PIGEONHOLE"
CLAMAV_SETTINGS="CLAMAV CLAMAV_EXIM MODSECURITY_UPLOADSCAN PROFTPD_UPLOADSCAN PUREFTPD_UPLOADSCAN SUHOSIN_PHP_UPLOADSCAN"
FTP_SETTINGS="FTPD"
STATS_SETTINGS="AWSTATS WEBALIZER"
CUSTOMBUILD_SETTINGS="BOLD CLEAN CLEAN_OLD_TARBALLS CLEAN_OLD_WEBAPPS"
CRON_SETTINGS="CRON CRON_FREQUENCY EMAIL NOTIFICATIONS UPDATES WEBAPPS_UPDATES"
CLOUDLINUX_SETTINGS="CLOUDLINUX CAGEFS"
ADVANCED_SETTINGS="CSF SSL_CONFIGURATION REDIS"

PHP_EXT_SETTINGS_DESC="PHP Extension Settings"
PHP_SETTINGS_DESC="PHP Settings"
MYSQL_SETTINGS_DESC="MySQL Settings"
WEBSERVER_SETTINGS_DESC="WEB Server Settings"
WEBAPPS_SETTINGS_DESC="WEB Applications Settings"
CLAMAV_SETTINGS_DESC="ClamAV-related Settings"
MAIL_SETTINGS_DESC="Mail Settings"
FTP_SETTINGS_DESC="FTP Settings"
STATS_SETTINGS_DESC="Statistics Settings"
CUSTOMBUILD_SETTINGS_DESC="CustomBuild Settings"
CRON_SETTINGS_DESC="Cronjob Settings"
CLOUDLINUX_SETTINGS_DESC="CloudLinux Settings"
ADVANCED_SETTINGS_DESC="Advanced Settings"

YESNO_SET="yes no"

#OPTIONS.CONF
PHP1_RELEASE_DEF="8.1"
PHP1_MODE_SET="php-fpm fastcgi lsphp"
if distro_is_debian; then
	PHP1_MODE_DEF="php-fpm"
fi
if distro_is_rhel; then
	if uname -a | grep -m1 -q '\.lve' || uname -a | grep -m1 -q 'el7h'; then
		if is_cloudlinux_solo; then
			PHP1_MODE_DEF="php-fpm"
		else
			PHP1_MODE_DEF="lsphp"
		fi
	else
		PHP1_MODE_DEF="php-fpm"
	fi
fi
PHP1_RELEASE_DESC="Default version of PHP."
PHP1_MODE_DESC="Mode of the default PHP version. lsphp is only compatible with LiteSpeed, OpenLiteSpeed WWW servers or CloudLinux+Apache except CloudLinux Solo Edition. For nginx (not as a reverse proxy for apache) php-fpm must be chosen."

PHP2_RELEASE_SET="${PHP1_RELEASE_SET} no"
PHP2_RELEASE_DEF="no"
PHP2_MODE_SET="${PHP1_MODE_SET}"
PHP2_MODE_DEF="php-fpm"
PHP2_RELEASE_DESC="Additional version of PHP."
PHP2_MODE_DESC="Mode of the additional PHP version."

PHP3_RELEASE_SET="${PHP2_RELEASE_SET}"
PHP3_RELEASE_DEF="${PHP2_RELEASE_DEF}"
PHP3_MODE_SET="${PHP2_MODE_SET}"
PHP3_MODE_DEF="${PHP2_MODE_DEF}"
PHP3_RELEASE_DESC="${PHP2_RELEASE_DESC}"
PHP3_MODE_DESC="${PHP2_MODE_DESC}"

PHP4_RELEASE_SET="${PHP2_RELEASE_SET}"
PHP4_RELEASE_DEF="${PHP2_RELEASE_DEF}"
PHP4_MODE_SET="${PHP2_MODE_SET}"
PHP4_MODE_DEF="${PHP2_MODE_DEF}"
PHP4_RELEASE_DESC="${PHP2_RELEASE_DESC}"
PHP4_MODE_DESC="${PHP2_MODE_DESC}"

SECURE_PHP_SET="${YESNO_SET}"
SECURE_PHP_DEF="no"
SECURE_PHP_DESC="Disable dangerous PHP functions."

EOL_COMMENT="Not in active development anymore, thus not recommended."

#php_extensions.conf things start with PHP_, but they're listed without PHP_ inside the file
PHP_HTSCANNER_SET="${YESNO_SET}"
PHP_HTSCANNER_DEF="no"
PHP_HTSCANNER_DESC="htscanner for Apache (allows to confige php in .htaccess files using PHP)."

PHP_BZ2_SET="${YESNO_SET}"
PHP_BZ2_DEF="no"
PHP_BZ2_DESC="Bz2 extension for PHP."

PHP_GMP_SET="${YESNO_SET}"
PHP_GMP_DEF="no"
PHP_GMP_DESC="GMP extension for PHP."

PHP_LDAP_SET="${YESNO_SET}"
PHP_LDAP_DEF="no"
PHP_LDAP_DESC="LDAP extension for PHP."

PHP_OPCACHE_SET="${YESNO_SET}"
PHP_OPCACHE_DEF="no"
PHP_OPCACHE_DESC="opCache opcode cacher for PHP."

PHP_IONCUBE_SET="${YESNO_SET}"
PHP_IONCUBE_DEF="no"
PHP_IONCUBE_DESC="PHP loader for ionCube Secured Files."

PHP_IMAGICK_SET="${YESNO_SET}"
PHP_IMAGICK_DEF="no"
PHP_IMAGICK_DESC="ImageMagick extension for PHP."

PHP_PSR_SET="${YESNO_SET}"
PHP_PSR_DEF="no"
PHP_PSR_DESC="Psr extension for PHP."

PHP_PHALCON_SET="${YESNO_SET}"
PHP_PHALCON_DEF="no"
PHP_PHALCON_DESC="Phalcon extension for PHP."

PHP_REDIS_SET="${YESNO_SET}"
PHP_REDIS_DEF="no"
PHP_REDIS_DESC="Redis extension for PHP."

PHP_READLINE_SET="${YESNO_SET}"
PHP_READLINE_DEF="no"
PHP_READLINE_DESC="Readline extension for PHP."

PHP_IMAP_SET="${YESNO_SET}"
PHP_IMAP_DEF="no"
PHP_IMAP_DESC="IMAP extension for PHP."

PHP_XMLRPC_SET="${YESNO_SET}"
PHP_XMLRPC_DEF="no"
PHP_XMLRPC_DESC="XMLRPC extension for PHP."

PHP_SNUFFLEUPAGUS_SET="${YESNO_SET}"
PHP_SNUFFLEUPAGUS_DEF="no"
PHP_SNUFFLEUPAGUS_DESC="Snuffleupagus security module."

PHP_IGBINARY_SET="${YESNO_SET}"
PHP_IGBINARY_DEF="no"
PHP_IGBINARY_DESC="Drop in replacement for the standard php serializer."

PHP_SUHOSIN_SET="${YESNO_SET}"
PHP_SUHOSIN_DEF="no"
PHP_SUHOSIN_DESC="Suhosin advanced protection system for PHP. ${EOL_COMMENT}"

PHP_ZEND_SET="${YESNO_SET}"
PHP_ZEND_DEF="no"
PHP_ZEND_DESC="Zend Guard Loader is a free runtime application that enables PHP to run the scripts encoded by Zend Guard. ${EOL_COMMENT}"
###end of php_extensions.conf

PHP_INI_SET="${YESNO_SET}"
PHP_INI_DEF="no"
PHP_INI_DESC="Enables ability to update php.ini file of PHP (rewrites any customizations!)."

PHP_TIMEZONE_SET="userinput"
PHP_TIMEZONE_DEF="$(getTimezone)"
PHP_TIMEZONE_DESC="date.timezone setting in php.ini file of PHP. https://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone."

PHP_INI_TYPE_SET="production development"
PHP_INI_TYPE_DEF="production"
PHP_INI_TYPE_DESC="Type of php.ini file. php.ini-development contains settings recommended for use in development environments. php.ini-production contains settings recommended for use in production environments."

REDIS_SET="${YESNO_SET}"
REDIS_DEF="no"
REDIS_DESC="Redis key-value database."

SUHOSIN_PHP_UPLOADSCAN_SET="${YESNO_SET}"
SUHOSIN_PHP_UPLOADSCAN_DEF="no"
SUHOSIN_PHP_UPLOADSCAN_DESC="Scan PHP uploaded scripts using suhosin upload verification script and ClamAV antivirus (clamdscan). ClamAV must be installed and suhosin option should be enabled for the setting to work."

#OUTPUT AS x-mail-header
X_MAIL_HEADER_SET="${YESNO_SET}"
X_MAIL_HEADER_DEF="yes"
X_MAIL_HEADER_DESC="mail.add_x_header setting in php.ini file of PHP. https://www.php.net/manual/en/mail.configuration.php#ini.mail.add-x-header"

UNIT_SET="${YESNO_SET}"
UNIT_DEF="no"
UNIT_DESC="Nginx Unit. Dynamic Application Server. ALPHA support."

WEBSERVER_SET="apache nginx nginx_apache litespeed openlitespeed"
WEBSERVER_DEF="apache"
WEBSERVER_DESC="WWW Server."

HTTP_METHODS_SET="userinput"
HTTP_METHODS_DEF="ALL"
HTTP_METHODS_DESC="Allowed HTTP methods. Enabled with rewrite_confs or webserver update."

LITESPEED_SERIALNO_SET="userinput"
LITESPEED_SERIALNO_DEF="trial"
LITESPEED_SERIALNO_DESC="Serial number of LiteSpeed Enterprise license."

MODSECURITY_SET="${YESNO_SET}"
MODSECURITY_DEF="no"
MODSECURITY_DESC="ModSecurity - Web application firewall."

MODSECURITY_RULESET_SET="comodo owasp no"
MODSECURITY_RULESET_DEF="owasp"
MODSECURITY_RULESET_DESC="ModSecurity rule set. Set to 'no' to use no ruleset. Comodo option provides Comodo Rule Set for ModSecurity: https://modsecurity.comodo.com/. OWASP ModSecurity Core Rule Set: https://www.owasp.org/index.php/Category:OWASP_ModSecurity_Core_Rule_Set_Project. Add custom rules to custom/modsecurity/conf, they'd be added automatically to /etc/modsecurity.d after './build modsecurity' or './build modsecurity_rules' is ran."

APACHE_MPM_SET="prefork event worker auto"
APACHE_MPM_DEF="auto"
APACHE_MPM_DESC="Apache Multi-Processing Module. 'auto' mode sets MPM to be event and is reserved for the future if any new modes appear."

USERDIR_ACCESS_SET="${YESNO_SET}"
USERDIR_ACCESS_DEF="no"
USERDIR_ACCESS_DESC="Allows accessing contents of public_html using https://hostname/~user, if enabled."

#mod_ruid2 is no longer supported
MOD_RUID2_SET="no"
MOD_RUID2_DEF="no"
MOD_RUID2_DESC="Not supported, still available to detect legacy system configuration."

#OUTPUT as harden-symlinks-patch
HARDEN_SYMLINKS_PATCH_SET="${YESNO_SET}"
HARDEN_SYMLINKS_PATCH_DEF="yes"
HARDEN_SYMLINKS_PATCH_DESC="Patches apache to include hardened symlinks patch. https://files.directadmin.com/services/custombuild/harden-symlinks-2.4.patch."

USE_HOSTNAME_FOR_ALIAS_SET="${YESNO_SET} auto"
USE_HOSTNAME_FOR_ALIAS_DEF="no"
USE_HOSTNAME_FOR_ALIAS_DESC="Redirects WEB appplications addresses to server hostname. Useful with FastCGI mode of PHP ('auto' option enables it for FastCGI mode of PHP only)."

REDIRECT_HOST_SET="userinput"
REDIRECT_HOST_DEF="${HOSTNAME}"
REDIRECT_HOST_DESC="Hostname used for use_hostname_for_alias setting."

REDIRECT_HOST_HTTPS_SET="${YESNO_SET}"
REDIRECT_HOST_HTTPS_DEF="no"
REDIRECT_HOST_HTTPS_DESC="Enables SSL redirection for use_hostname_for_alias setting."

MYSQL_INST_SET="mysql mariadb no"
if [ -e /root/.skip_mysql_install ]; then
	MYSQL_INST_DEF="no"
else
	MYSQL_INST_DEF="mariadb"
fi
MYSQL_INST_DESC="Enables management of MySQL/MariaDB using CustomBuild."

MYSQL_DESC="MySQL version."

MARIADB_DESC="MariaDB version."

MYSQL_BACKUP_SET="${YESNO_SET}"
MYSQL_BACKUP_DEF="yes"
MYSQL_BACKUP_DESC="Backups MySQL databases before the installation of MySQL/MariaDB server."

MYSQL_BACKUP_GZIP_SET="${YESNO_SET}"
MYSQL_BACKUP_GZIP_DEF="no"
MYSQL_BACKUP_GZIP_DESC="Compress MySQL database backups."

MYSQL_BACKUP_DIR_SET="userinput"
MYSQL_BACKUP_DIR_DEF="/usr/local/directadmin/custombuild/mysql_backups"
MYSQL_BACKUP_DIR_DESC="Sets full path for mysql_backup option were MySQL backups should be placed."

MYSQL_FORCE_COMPILE_SET="${YESNO_SET}"
MYSQL_FORCE_COMPILE_DEF="no"
if is_arm64; then
	MYSQL_FORCE_COMPILE_DEF="yes"
fi
MYSQL_FORCE_COMPILE_DESC="Force compilation of MySQL/MariaDB instead of using system packages (RPM, DEB)"

PHPMYADMIN_SET="${YESNO_SET}"
if [ -e /root/.skip_mysql_install ]; then
	PHPMYADMIN_DEF="no"
else
	PHPMYADMIN_DEF="yes"
fi
PHPMYADMIN_DESC="Enables management of phpMyAdmin (Web application to manage MySQL databases) using CustomBuild."

PHPMYADMIN_PUBLIC_SET="${YESNO_SET}"
PHPMYADMIN_PUBLIC_DEF="yes"
PHPMYADMIN_PUBLIC_DESC="Makes phpMyAdmin accessible over /phpMyAdmin/ for everyone, if set to 'yes'. Setting this option to 'no' would make it available only from DirectAdmin (single-sign-on)."

SQUIRRELMAIL_SET="${YESNO_SET}"
SQUIRRELMAIL_DEF="no"
SQUIRRELMAIL_DESC="Enables management of SquirrelMail webmail using CustomBuild."

ROUNDCUBE_SET="${YESNO_SET}"
if [ -e /root/.skip_mysql_install ]; then
	ROUNDCUBE_DEF="no"
else
	ROUNDCUBE_DEF="yes"
fi
ROUNDCUBE_DESC="Enables management of RoundCube webmail using CustomBuild."

WEBAPPS_INBOX_PREFIX_SET="${YESNO_SET}"
WEBAPPS_INBOX_PREFIX_DEF="no"
WEBAPPS_INBOX_PREFIX_DESC="Adds INBOX. prefix to all of the mailbox folders in SquirrelMail/RoundCube (like: INBOX.Sent instead of just Sent)"

EXIM_SET="${YESNO_SET}"
EXIM_DEF="yes"
EXIM_DESC="Enables management of Exim MTA (Mail Transfer Agent) using CustomBuild."

EXIMCONF_SET="${YESNO_SET}"
EXIMCONF_DEF="yes"
EXIMCONF_DESC="Enables ability to update exim.conf and exim.pl files of Exim MTA (rewrites any customizations!)."

BLOCKCRACKING_SET="${YESNO_SET}"
BLOCKCRACKING_DEF="no"
BLOCKCRACKING_DESC="Enables BlockCracking in exim.conf for outgoing spam mitigation. Requires exim configuration version 4.3 or higher. More information: https://forum.directadmin.com/showthread.php?t=50059."

EASY_SPAM_FIGHTER_SET="${YESNO_SET}"
EASY_SPAM_FIGHTER_DEF="no"
EASY_SPAM_FIGHTER_DESC="Enables Easy Spam Figher in exim.conf for incoming spam mitigation. Requires exim configuration version 4.3 or higher. More information: https://forum.directadmin.com/showthread.php?t=50059."

CLAMAV_SET="${YESNO_SET}"
CLAMAV_DEF="no"
CLAMAV_DESC="Enables management of ClamAV antivirus engine using CustomBuild. Enables ClamAV automatically in Exim configuration."

CLAMAV_EXIM_SET="${YESNO_SET}"
CLAMAV_EXIM_DEF="yes"
CLAMAV_EXIM_DESC="Enables ClamAV automatically in Exim configuration together with the installation of ClamAV."

SPAMD_SET="rspamd spamassassin no"
SPAMD_DEF="no"
SPAMD_DESC="Enables management of Rspamd or SpamAssassin spam filters using CustomBuild. Enables Rspamd or SpamAssassin automatically in Exim configuration."

SA_UPDATE_SET="no daily weekly monthly"
SA_UPDATE_DEF="daily"
SA_UPDATE_DESC="Installs a cronjob for sa-update to update SpamAssassin Spam Filter Rules daily, weekly or monthly using CustomBuild. Takes effect only if SpamAssassin is enabled on the server, at the installation time of SpamAssassin, CustomBuild cronjob or 'spamassassin_cron' call."

DOVECOT_SET="${YESNO_SET}"
DOVECOT_DEF="yes"
DOVECOT_DESC="Enables management of Dovecot IMAP and POP3 email server using CustomBuild."

DOVECOT_CONF_SET="${YESNO_SET}"
DOVECOT_CONF_DEF="yes"
DOVECOT_CONF_DESC="Enables management of Dovecot configuration files using CustomBuild."

PIGEONHOLE_SET="${YESNO_SET}"
PIGEONHOLE_DEF="yes"
PIGEONHOLE_DESC="Enables management of Pigeonhole (enables Sieve language and the ManageSieve protocol, allows users to configure email filtering in their email clients) for Dovecot IMAP and POP3 email server using CustomBuild. When this setting is enabled, Pigeonhole is enabled with update/installation of Dovecot. RoundCube plugin to manage email filtering is enabled with update/installation of RoundCube."

MAIL_COMPRESS_SET="${YESNO_SET}"
MAIL_COMPRESS_DEF="no"
MAIL_COMPRESS_DESC="Enables gzip compression for new emails (using zlib in dovecot). Compressed emails take less space (when testing, compressed mail folders took ~20% of their initial disk space). To compress old emails manual action is needed (script to automate the process: dovecot_compress.sh)."

AWSTATS_SET="${YESNO_SET}"
AWSTATS_DEF="no"
AWSTATS_DESC="Enables management of AWstats (generates advanced web server statistics graphically) using CustomBuild."

WEBALIZER_SET="${YESNO_SET}"
WEBALIZER_DEF="yes"
WEBALIZER_DESC="Enables management of Webalizer (generates advanced web server statistics graphically) using CustomBuild."

MODSECURITY_UPLOADSCAN_SET="${YESNO_SET}"
MODSECURITY_UPLOADSCAN_DEF="no"
MODSECURITY_UPLOADSCAN_DESC="Scan HTTP uploaded files using ClamAV, when ModSecurity is enabled. ClamAV needs to be installed for this setting to work."

FTPD_SET="proftpd pureftpd no"
FTPD_DEF="pureftpd"
FTPD_DESC="FTP Server."

PUREFTPD_UPLOADSCAN_SET="${YESNO_SET}"
PUREFTPD_UPLOADSCAN_DEF="no"
PUREFTPD_UPLOADSCAN_DESC="Scan FTP uploaded files in Pure-FTPd using ClamAV. ClamAV needs to be installed for this setting to work."

PROFTPD_UPLOADSCAN_SET="${YESNO_SET}"
PROFTPD_UPLOADSCAN_DEF="no"
PROFTPD_UPLOADSCAN_DESC="Scan FTP uploaded files in ProFTPd using ClamAV. ClamAV needs to be installed for this setting to work."

SSL_CONFIGURATION_SET="modern intermediate old"
SSL_CONFIGURATION_DEF="intermediate"
SSL_CONFIGURATION_DESC="Auto-generated SSL ciphers/protocol list used in configuration, based on https://ssl-config.mozilla.org/."

BOLD_SET="${YESNO_SET}"
BOLD_DEF="yes"
BOLD_DESC="Enables bold effect for important output in terminal."

CLEAN_SET="${YESNO_SET}"
CLEAN_DEF="yes"
CLEAN_DESC="Cleans not needed folders in the CustomBuild directory. Folders are often left from the previous packge installations."

CLEAN_OLD_TARBALLS_SET="${YESNO_SET}"
CLEAN_OLD_TARBALLS_DEF="yes"
CLEAN_OLD_TARBALLS_DESC="Removes tarballs of old (unused) packages."

CLEAN_OLD_WEBAPPS_SET="${YESNO_SET}"
CLEAN_OLD_WEBAPPS_DEF="yes"
CLEAN_OLD_WEBAPPS_DESC="Removes old WEB application folders from /var/www/html. Takes effect when any WEB application is installed/updated."

CRON_SET="${YESNO_SET}"
CRON_DEF="yes"
CRON_DESC="Enables cronjob for CustomBuild scheduled jobs set."

CRON_FREQUENCY_SET="daily weekly monthly"
CRON_FREQUENCY_DEF="daily"
CRON_FREQUENCY_DESC="Sets the execution frequency of the Cronjob (scheduled jobs). Takes effect only when the 'cron' option is enabled."

EMAIL_SET="userinput"
EMAIL_DEF="email@domain.com"
EMAIL_DESC="Sets the email for notifications about the updates available. Takes effect only when 'cron' and 'notifications' options are enabled."

NOTIFICATIONS_SET="${YESNO_SET}"
NOTIFICATIONS_DEF="no"
NOTIFICATIONS_DESC="Sets the email for notifications about the updates available. Takes effect only when 'cron' option is enabled."

UPDATES_SET="${YESNO_SET}"
UPDATES_DEF="no"
UPDATES_DESC="Enables automatic updates of all available to update packages managed by the CustomBuild script. Takes effect only when 'cron' option is enabled. WARNING: not recommended in production!"

WEBAPPS_UPDATES_SET="${YESNO_SET}"
WEBAPPS_UPDATES_DEF="no"
WEBAPPS_UPDATES_DESC="Enables automatic updates of all WEB applications enabled. Takes effect only when 'cron' option is enabled."

CSF_SET="${YESNO_SET}"
CSF_DEF="no"
CSF_DESC="Enables ConfigServer Security & Firewall (csf)."

CLOUDLINUX_SET="${YESNO_SET}"
if uname -a | grep -m1 -q '\.lve' || uname -a | grep -m1 -q 'el7h'; then
	CLOUDLINUX_DEF="yes"
else
	CLOUDLINUX_DEF="no"
fi
CLOUDLINUX_DESC="Enables CloudLinux support in the CustomBuild script (automatic patching using CloudLinux patches for specific components). NOTE: CloudLinux needs to be installed on the system. https://www.cloudlinux.com."

CAGEFS_SET="${YESNO_SET}"
if [ -x /usr/sbin/cagefsctl ]; then
	CAGEFS_DEF="yes"
else
	CAGEFS_DEF="no"
fi
CAGEFS_DESC="Enables support of CageFS component by CloudLinux in the CustomBuild script (automatic updating of files in CageFS using 'cagefsctl --force-update'). NOTE: CloudLinux needs to be installed on the system. https://www.cloudlinux.com."
#################################################

showVersion() {
	echo "2.0.0"
}

doCSFpignore() {
	CSF_PIGNORE="/etc/csf/csf.pignore"
	CSF_PIGNORE_SOURCE="${WORKDIR}/configure/csf.pignore"
	if [ -s ${WORKDIR}/custom/csf.pignore ]; then
		CSF_PIGNORE_SOURCE="${WORKDIR}/custom/csf.pignore"
	fi
	if [ -s ${CSF_PIGNORE} ] && [ -s ${CSF_PIGNORE_SOURCE} ]; then
		#very nice&quick way to add missing lines in destination file
		grep -x -f ${CSF_PIGNORE_SOURCE} ${CSF_PIGNORE} | awk 'FNR==NR{a[$0]; next} !($0 in a)' - ${CSF_PIGNORE_SOURCE}  >> ${CSF_PIGNORE}
		#if file has been edited - restart lfd (suppress errors/warnings, as it could be disabled)
		find ${CSF_PIGNORE} -mmin -1 -type f -print -exec csf --lfd restart 2>&1 >/dev/null \;
	fi
}

initLogfile() {
	LOG_IP=localhost
	if [ "$(who | wc -l)" -gt 0 ]; then
		LOG_IP=`echo $SSH_CLIENT | cut -d' ' -f1`
	fi

	if [ ! -e ${LOGFILE} ]; then
		touch ${LOGFILE}
		chmod 600 ${LOGFILE}
	else
		LOGSIZE=`stat -c %s ${LOGFILE}`

		#Rotate the logfile if the filesize is >10MB
		if [ ${LOGSIZE} -gt 10485760 ]; then
			rm -f ${LOGFILE}.1
			mv ${LOGFILE} ${LOGFILE}.1
			touch ${LOGFILE}
			chmod 600 ${LOGFILE}
		fi
	fi
}

if [ "`grep -c processor /proc/cpuinfo`" -gt 0 ]; then
	CPU_CORES="`grep -c processor /proc/cpuinfo`"
fi
MEMORY=`grep -m1 'MemTotal' /proc/meminfo | awk '{print $2}'`

#Avoid OOM by making CB not cross-compile on boxes with low amount of memory
if [ ! -z "${MEMORY}" ]; then
	if [ ${MEMORY} -lt 2097152 ]; then
		CPU_CORES=1
	fi
fi

#check path for /usr/local/bin
if ! echo "${PATH}" | grep -qF -m1 '/usr/local/bin:'; then
	export PATH=/usr/local/bin:$PATH
fi

#check PKG_CONFIG_PATH for /usr/local/lib/pkgconfig
if ! echo "${PKG_CONFIG_PATH}" | grep -qF -m1 '/usr/local/lib/pkgconfig:'; then
	export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:${PKG_CONFIG_PATH}
fi

# Main variables
HTTPDDIR=/etc/httpd
HTTPDCONF=/etc/httpd/conf
HTTPD_CONF=${HTTPDCONF}/httpd.conf
PHPMODULES=${HTTPDCONF}/extra/httpd-phpmodules.conf

NGINXCONF=/etc/nginx

WWWDIR=/var/www/html

DACONF_FILE=/usr/local/directadmin/conf/directadmin.conf
DA_MY_CNF=/usr/local/directadmin/conf/my.cnf
SERVICES=/usr/local/directadmin/data/admin/services.status

DOVECOT_CONFIG=/etc/dovecot/dovecot.conf

doCheckIPV6() {
	if [ -z "${IPV6}" ]; then
		IPV6=0
		if [ -e ${DA_BIN} ]; then
			IPV6=`${DA_BIN} c | grep -m1 '^ipv6=' | cut -d= -f2`
		fi
	fi
}

HIDE_CHANGES=0

# Applications variables
APPUSER=webapps
APPGROUP=${APPUSER}
APP_TMP=/var/www/tmp

STRINGS=/usr/bin/strings
MYSQL_DATA=/var/lib/mysql
if distro_is_debian; then
	# If /var/lib/mysql doesn't exist, and /home/mysql is there - our datadir is /home/mysql, used on very old boxes only
	if [ -d /home/mysql ] && [ ! -d /var/lib/mysql/mysql ]; then
		MYSQL_DATA=/home/mysql
	fi
	MYSQL_BIN=/usr/local/mysql/bin/mysql
elif [ -x /usr/local/mysql/bin/mysql ]; then
	MYSQL_BIN=/usr/local/mysql/bin/mysql
elif [ ! -x /usr/bin/mysql ] && ! rhel_version_is 7 && ! rhel_version_is 8; then
	MYSQL_BIN=/usr/local/mysql/bin/mysql
else
	MYSQL_BIN=/usr/bin/mysql
fi

#Check if mysql database exists
if [ -d ${MYSQL_DATA}/mysql ]; then 
	SQL_PATH_IS_EMPTY=false
else
	SQL_PATH_IS_EMPTY=true
fi

CURL_CONNECT_OPTIONS="-L --progress-bar --connect-timeout 5 --retry 3 --fail"

#$1 = https://files1.da.com/some/exim.conf
#$2 = /etc/exim.conf
safeDownloadWithMove() {
	OUTPUT_FILE=$1
	DOWNLOAD_URL=$2
	TMP_FILE=$(mktemp --tmpdir=${CB_TMP_DIR} --suffix=safeDownloadWithMove)
	if [ -z "${TMP_FILE}" ]; then
		do_exit 1 "Unable to create temporary file ${TMP_FILE}, exiting..."
	fi

	TRY=0
	while ! curl ${CURL_CONNECT_OPTIONS} -o "${TMP_FILE}" "${DOWNLOAD_URL}"; do
		echo "Download of ${DOWNLOAD_URL} failed, re-downloading the file..."
		TRY=`expr ${TRY} + 1`
		if [ ${TRY} -eq 4 ]; then
			rm -f "${TMP_FILE}"
			do_exit 1 "Download of ${DOWNLOAD_URL} failed ${TRY} times, exiting..."
		fi
	done

	if ! mv -f "${TMP_FILE}" "${OUTPUT_FILE}"; then
		rm -f "${TMP_FILE}"
		do_exit 1 "Move from ${TMP_FILE} to ${OUTPUT_FILE} failed, exiting..."
	fi
}

MARIADB_DEF="10.6"
MYSQL_DEF="5.7"

if rhel_version_is 8; then
	#We don't have RPMs for EL8 of older versions in our mirrors
	MARIADB_SET="10.3 10.4 10.5 10.6"
	MYSQL_SET="8.0"
	MYSQL_DEF="8.0"
elif rhel_version_is 9; then
	#Even if we use binaries there, we still want to stay rpm-compatible
	MARIADB_SET="10.6"
	MYSQL_DEF="10.6"
	MYSQL_SET="8.0"
	MYSQL_DEF="8.0"
else
	MARIADB_SET="5.5 10.0 10.1 10.2 10.3 10.4 10.5 10.6"
	MYSQL_SET="5.5 5.6 5.7 8.0"
fi

# Check if workdir exists
if [ ! -d ${WORKDIR} ]; then
	do_exit 1 "Directory ${WORKDIR} does not exist."
fi

file_mtime="stat --format=%Y"

set_LoadModule() {
	# Add to httpd-phpmodules.conf
	MODULE_NAME=$1
	MODULE_FILENAME=$2
	MODULE_FULLPATH=/usr/lib/apache/${MODULE_FILENAME}
	if ! grep -m1 -q " ${MODULE_NAME} " ${PHPMODULES} && [ -e ${MODULE_FULLPATH} ]; then
		echo "LoadModule ${MODULE_NAME} /usr/lib/apache/${MODULE_FILENAME}" >> ${PHPMODULES}
	fi
	perl -pi -e "s|^LoadModule ${MODULE_NAME}|#LoadModule ${MODULE_NAME}|g" /etc/httpd/conf/httpd.conf
}

ensure_my_cnf() {
	#1 = path to cnf
	#2 = user
	#3 = pass
	#4 = optional source file to compare with. update 1 if 4 is newer.
	# host will be on the command line, as that's how DA already does it.

	E_MY_CNF=$1

	E_MY_CNF_DIR="`dirname ${E_MY_CNF}`"

	if [ ! -d ${E_MY_CNF_DIR} ]; then
		mkdir -p ${E_MY_CNF_DIR}
	fi

	W=0
	if [ ! -s ${E_MY_CNF} ]; then
		W=1
	fi

	if [ "${W}" = "0" ] && [ "${4}" != "" ]; then
		if [ ! -s $4 ]; then
			if [ -d "${MYSQL_DATA}" ]; then
				echo "ensure_my_cnf: cannot find $4"
			fi
			W=1
		else
			MY_CNF_T=`${file_mtime} ${E_MY_CNF}`
			SRC_CNF_T=`${file_mtime} ${4}`

			if [ "${MY_CNF_T}" -lt "${SRC_CNF_T}" ]; then
				echo "Found outdated ${E_MY_CNF}. Rewriting from ${4}"
				W=1
			fi
		fi
	fi

	if [ "${W}" = "1" ]; then
		echo '[client]' > ${E_MY_CNF}
		chmod 600 ${E_MY_CNF}
		echo "user=${2}" >> ${E_MY_CNF}
		ESC_PASS=`echo "${3}" | sed -e 's/\"/\\\"/'`
		echo "password=\"${ESC_PASS}\"" >> ${E_MY_CNF}
	fi
}

create_global_modsecurity_rules() {
	if [ ! -e /usr/local/directadmin/data/admin/modsecurity_rules ]; then
		touch /usr/local/directadmin/data/admin/modsecurity_rules
		chmod 600 /usr/local/directadmin/data/admin/modsecurity_rules
		chown diradmin:diradmin /usr/local/directadmin/data/admin/modsecurity_rules
	fi
}

initMySQL() {
	if [ "${MYSQL_OPT}" = "8.0" ] && [ "${MYSQL_INST_OPT}" = "mysql" ]; then
		SKIP_MYSQL_UPGRADE=true
	else
		SKIP_MYSQL_UPGRADE=false
	fi

	#MySQL settings
	DA_MYSQL=/usr/local/directadmin/conf/mysql.conf
	if [ -s ${DA_MYSQL} ]; then
		MYSQLUSER=`grep -m1 "^user=" ${DA_MYSQL} | cut -d= -f2`
		MYSQLPASSWORD=`grep -m1 "^passwd=" ${DA_MYSQL} | cut -d= -f2`
	else
		MYSQLUSER='da_admin'
		MYSQLPASSWORD='nothing'
	fi

	if [ -s $DA_MYSQL ] && [ "$(grep -m1 -c -e "^host=" ${DA_MYSQL})" -gt 0 ]; then
		MYSQLHOST=`grep -m1 "^host=" ${DA_MYSQL} | cut -d= -f2`
	else
		MYSQLHOST=localhost
	fi

	#Where connections to mysql are from. Usualy the server IP, unless on a LAN.
	MYSQL_ACCESS_HOST=localhost
	if [ "$MYSQLHOST" != "localhost" ]; then
		MYSQL_ACCESS_HOST="`grep -r -l -m1 '^status=server$' /usr/local/directadmin/data/admin/ips | cut -d/ -f8`"
		if [ "${MYSQL_ACCESS_HOST}" = "" ]; then
			MYSQL_ACCESS_HOST="`grep -im1 ${HOSTNAME} /etc/hosts | awk '{print $1}'`"
			if [ "${MYSQL_ACCESS_HOST}" = "" ]; then
				if [ -s ${WORKDIR}/scripts/setup.txt ]; then
					MYSQL_ACCESS_HOST=`cat ${WORKDIR}/scripts/setup.txt | grep -m1 -e '^ip=' | cut -d= -f2`
				fi
				if [ "${MYSQL_ACCESS_HOST}" = "" ]; then
					echo "Unable to detect your server IP in /etc/hosts. Please enter it: "
					read MYSQL_ACCESS_HOST
				fi
			fi
		fi
	fi

	ensure_my_cnf ${DA_MY_CNF} "${MYSQLUSER}" "${MYSQLPASSWORD}" "${DA_MYSQL}"
	chown diradmin:diradmin ${DA_MY_CNF}
}

load_php_extensions_conf
load_options_conf

####################################################

cagefsctl_update() {
	if [ "${CAGEFS_OPT}" = "yes" ] && [ -e /usr/sbin/cagefsctl ]; then
		echo "CageFS: Executing 'cagefsctl --force-update'..."
		if [ -e /usr/bin/ionice ]; then
			/usr/bin/ionice -c3 /usr/sbin/cagefsctl --force-update
		else
			/usr/sbin/cagefsctl --force-update
		fi
		cagefsctl --remount-all
	fi
}

writeLog() {
	initLogfile
	echo "`date +'%Y-%m-%d %H:%M:%S'` ${LOG_IP}: $*" >> ${LOGFILE}
}

get_line_from_file() {
	#$1 is any part of the name, make sure it wouldn't have duplicates, as it'd select only the first instance of the match
	#$2 is full path to txt file
	if [ ! -s $2 ]; then
		do_exit 1 "$2 does not exist."
	fi

	if grep -m1 -q "^$1" $2; then
		RESULT="`grep -m1 \"^$1\" ${WORKDIR}/$2`"
	else
		RESULT=""
	fi
	
	echo "${RESULT}"
}

do_exit() {
	if [ "$2" != "" ]; then
		echo "$2"
	fi
	if [ -n "${CB_MESSAGE_ON_EXIT:-}" ]; then
		send_da_message "CustomBuild installation has failed" "CustomBuild installation has failed, please check the following file for more information:"$'\n'"${OUTPUT_LOG_FILE}"
	fi
	exit "$1"
}

have_php_system() {
	#Checks to see if we can use system() based on the disable_functions
	if [ ! -s "${PHP_INI}" ]; then
		echo 1
		return
	fi

	C=`grep -m1 -c ^disable_functions ${PHP_INI}`
	if [ "${C}" -eq 0 ]; then
		echo 1
		return
	fi

	C=`grep -m1 ^disable_functions ${PHP_INI} | grep -m1 -c system`
	if [ "${C}" -eq 1 ]; then
		echo 0
		return
	fi

	echo 1
	return
}

secure_phpini() {
	if [ -e $1 ]; then
		if grep -m1 -q -e disable_functions $1; then
			CURRENT_DISABLE_FUNCT="`grep -m1 'disable_functions' $1`"
			if [ -s ${WORKDIR}/custom/php_disable_functions ]; then
				NEW_DISABLE_FUNCT="`head -n1 ${WORKDIR}/custom/php_disable_functions`"
			else
				NEW_DISABLE_FUNCT="exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname"
			fi
			perl -pi -e "s#${CURRENT_DISABLE_FUNCT}#disable_functions \= ${NEW_DISABLE_FUNCT}#" $1
		else
			echo "disable_functions = ${NEW_DISABLE_FUNCT}" >> $1
		fi

		perl -pi -e 's/^register_globals = On/register_globals = Off/' $1

		perl -pi -e 's/^mysql.allow_local_infile = On/mysql.allow_local_infile = Off/' $1
		perl -pi -e 's/^mysqli.allow_local_infile = On/mysqli.allow_local_infile = Off/' $1
		perl -pi -e 's/^;mysqli.allow_local_infile = On/mysqli.allow_local_infile = Off/' $1

		perl -pi -e 's/^expose_php = On/expose_php = Off/' $1
		
		writeLog "secure_phpini: $1 secured"
	fi
}

####################################################

secure_php() {
	if [ "${SECURE_PHP_OPT}" != "yes" ]; then
		command_set secure_php yes
	fi
	secure_phpini ${PHP_INI}
	for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
		EVAL_PHP_INI_VAR=PHP_INI_FPM${php_shortrelease}
		secure_phpini ${!EVAL_PHP_INI_VAR}
	done
	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		if [ -e /etc/cl.selector/global_php.ini ]; then
			secure_phpini /etc/cl.selector/global_php.ini
			if [ -e /usr/sbin/cagefsctl ]; then
				/usr/sbin/cagefsctl --setup-cl-selector
			fi
		fi
	fi
	echo "PHP has been secured."
	RESTART_APACHE="1"
	if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
		echo "Restarting php-fpm${PHP1_SHORTRELEASE}."
		control_service php-fpm${PHP1_SHORTRELEASE} restart
		RESTART_APACHE="0"
	fi
	if [ "${PHP2_MODE_OPT}" = "php-fpm" ] && [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		echo "Restarting php-fpm${PHP2_SHORTRELEASE}."
		control_service php-fpm${PHP2_SHORTRELEASE} restart
	fi
	if [ "${PHP3_MODE_OPT}" = "php-fpm" ] && [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		echo "Restarting php-fpm${PHP3_SHORTRELEASE}."
		control_service php-fpm${PHP3_SHORTRELEASE} restart
	fi
	if [ "${PHP4_MODE_OPT}" = "php-fpm" ] && [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		echo "Restarting php-fpm${PHP4_SHORTRELEASE}."
		control_service php-fpm${PHP4_SHORTRELEASE} restart
	fi

	if [ "${RESTART_APACHE}" = "1" ]; then
		control_service httpd restart
	fi
}

#Used to set values ON/OFF in the services.status.
#set_service name ON|OFF|delete
set_service() {
	if [ ! -e ${SERVICES} ]; then
		if [ ! -d /usr/local/directadmin/data/admin ]; then
			mkdir -p /usr/local/directadmin/data/admin
			chown diradmin:diradmin /usr/local/directadmin/data/admin
			chown diradmin:diradmin /usr/local/directadmin/data
			chmod 700 /usr/local/directadmin/data/admin
			chmod 711 /usr/local/directadmin/data
		fi
		touch ${SERVICES}
		chown diradmin:diradmin ${SERVICES}
		chmod 600 ${SERVICES}
	fi

	if [ "$2" = "delete" ]; then
		if ! grep -q "^$1=" ${SERVICES}; then
			return
		else
			perl -pi -e "s/^${1}=.*\n//" ${SERVICES}
		fi
		return
	fi

	if [ "$2" = "ON" ] || [ "$2" = "OFF" ]; then
		if ! grep -q "^$1=" ${SERVICES}; then
			echo "$1=$2" >> ${SERVICES}
		else
			perl -pi -e "s/^$1=.*/$1=$2/" ${SERVICES}
		fi

		return
	fi

	echo "setService $1: unknown option: $2"
}

control_service() {
	SERVICE_NAME=$1
	SERVICE_ACTION=$2

	systemctl ${SERVICE_ACTION} ${SERVICE_NAME}.service
}


#sets the value of $1 to $2 in the file $3
setVal() {
	if [ ! -e $3 ]; then
		return
	fi

	if ! grep -m1 -q "^${1}=" ${3}; then
		#ok, it's not there, add it.
		echo "$1=$2" >> $3
		return
	else
		#ok, the value is already in the file $3, so use perl to regex it.
		perl -pi -e "s/^`grep -m1 "^${1}=" ${3}`/${1}=${2}/" ${3}
	fi
}

#A > B: 1
#A = B: 0
#A < B: -1
#3rd option is descriptor
version_cmp() {
	A=`echo $1 | cut -d- -f1`
	B=`echo $2 | cut -d- -f1`

	if [ "$A" = "" ] || [ "$B" = "" ]; then
		echo "version_cmp has a blank value when checking $3"
		return
	fi

	if ! echo "$A" | grep -m1 -q '^[0-9]' || ! echo "$B" | grep -m1 -q '^[0-9]'; then
		echo "version_cmp has a wrong version when checking $3 for version comparison, ${A} vs. ${B}"
		return
	fi
	
	#swap underscore with dot.
	A=`echo $A | tr '_' '.'`
	B=`echo $B | tr '_' '.'`
	
	A1=`echo $A | cut -d. -f1`
	B1=`echo $B | cut -d. -f1`

	if [ "$A1" -gt "$B1" ]; then
		echo  1
		return
	fi

	if [ "$A1" -lt "$B1" ]; then
		echo  -1
		return
	fi

	A2=`echo $A | cut -d. -f2`
	B2=`echo $B | cut -d. -f2`

	if [ "$A2" -gt "$B2" ]; then
		echo  1
		return
	fi

	if [ "$A2" -lt "$B2" ]; then
		echo  -1
		return
	fi

	A3=`echo $A | cut -d. -f3`
	B3=`echo $B | cut -d. -f3`

	if [ "$A3" = "" ] && [ "$B3" = "" ]; then
		echo 0
		return
	fi

	if [ "$A3" = "" ]; then
		if [ "$B3" = "0" ]; then
			echo 0;
		else
			echo 1
		fi
		return
	fi

	if [ "$B3" = "" ]; then
		if [ "$A3" = "0" ]; then
			echo 0;
		else
			echo -1
		fi
		return
	fi

	if [ "$A3" -gt "$B3" ]; then
		echo  1
		return
	fi

	if [ "$A3" -lt "$B3" ]; then
		echo  -1
		return
	fi

	echo 0
}

####################################################

GCCOPTIONS_CACHE=0

getGccOptions() {
	if [ "${GCCOPTIONS_CACHE}" = "0" ]; then
		# Exim always takes /usr/bin/gcc, even if it exists in /usr/local/bin/gcc. Other components built in /usr, not /usr/local might take it form there too.
		if [ -s /usr/bin/gcc ]; then
			GCC_VERSION="`/usr/bin/gcc --version | head -n1 | grep -o '[0-9]*\.[0-9]*' | head -n1`"
		else
			GCC_VERSION="`gcc --version | head -n1 | grep -o '[0-9]*\.[0-9]*' | head -n1`"
		fi
		if [ "`version_cmp ${GCC_VERSION} 4.9 'gcc ver check'`" -ge 0 ]; then
			GCCOPTIONS_CACHE="-fstack-protector-strong"
		else
			GCCOPTIONS_CACHE="-fstack-protector --param ssp-buffer-size=4"
		fi
	fi
	echo ${GCCOPTIONS_CACHE}
}

#These are needed for some functions outside
BOLD_OPT=${options_conf[bold]}

# Variables for bolded text
boldon=""
boldoff=""
if [ "${BOLD_OPT}" = "yes" ]; then
	boldon="`tput -Txterm bold`"
	boldoff="`tput -Txterm sgr0`"
fi
CLEAN_OPT=${options_conf[clean]}
MYSQL_FORCE_COMPILE_OPT=${options_conf[mysql_force_compile]}
DOWNLOADSERVER_OPT=files.directadmin.com
WEBPATH=https://${DOWNLOADSERVER_OPT}/services/custombuild
WEBPATH_SERVICES=https://${DOWNLOADSERVER_OPT}/services
WEBPATH_CL=https://repo.cloudlinux.com/cloudlinux/sources/da

getWebserverPorts() {
	# 443 and 80 ports
	PORT_80=$(${DA_BIN} config-get port_80)
	PORT_443=$(${DA_BIN} config-get port_443)

	# Reverse proxy ports
	PORT_8080=$(${DA_BIN} config-get port_8080)
	PORT_8081=$(${DA_BIN} config-get port_8081)
}

CSF_OPT=${options_conf[csf]}
#CloudLinux
CLOUDLINUX_OPT=${options_conf[cloudlinux]}
CAGEFS_OPT=${options_conf[cagefs]}

# Read options.conf
FTPD_OPT=${options_conf[ftpd]}
PUREFTPD_UPLOADSCAN_OPT=${options_conf[pureftpd_uploadscan]}
PROFTPD_UPLOADSCAN_OPT=${options_conf[proftpd_uploadscan]}

SPAMD_OPT=${options_conf[spamd]}
SA_UPDATE_OPT=${options_conf[sa_update]}
CLAMAV_OPT=${options_conf[clamav]}
CLAMAV_EXIM_OPT=${options_conf[clamav_exim]}
MODSECURITY_UPLOADSCAN_OPT=${options_conf[modsecurity_uploadscan]}
UNIT_OPT=${options_conf[unit]}
WEBSERVER_OPT=${options_conf[webserver]}
HTTP_METHODS_OPT=${options_conf[http_methods]}
LITESPEED_SERIALNO_OPT=${options_conf[litespeed_serialno]}
MODSECURITY_OPT=${options_conf[modsecurity]}
MODSECURITY_RULESET_OPT=${options_conf[modsecurity_ruleset]}

REDIRECT_HOST_OPT=${options_conf[redirect_host]}
REDIRECT_HOST_HTTPS_OPT=${options_conf[redirect_host_https]}
USE_HOSTNAME_FOR_ALIAS_OPT=${options_conf[use_hostname_for_alias]}

PHP_TIMEZONE_OPT=${options_conf[php_timezone]}

#Apache
APACHE_MPM_OPT=${options_conf[apache_mpm]}

USERDIR_ACCESS_OPT=${options_conf[userdir_access]}
HARDEN_SYMLINKS_PATCH_OPT=${options_conf[harden_symlinks_patch]}

#PHP
PHP1_RELEASE_OPT=${options_conf[php1_release]}
PHP2_RELEASE_OPT=${options_conf[php2_release]}
PHP3_RELEASE_OPT=${options_conf[php3_release]}
PHP4_RELEASE_OPT=${options_conf[php4_release]}

PHP1_SHORTRELEASE=${PHP1_RELEASE_OPT//./}
PHP2_SHORTRELEASE=${PHP2_RELEASE_OPT//./}
PHP3_SHORTRELEASE=${PHP3_RELEASE_OPT//./}
PHP4_SHORTRELEASE=${PHP4_RELEASE_OPT//./}

PHP1_MODE_OPT=${options_conf[php1_mode]}
PHP2_MODE_OPT=${options_conf[php2_mode]}
PHP3_MODE_OPT=${options_conf[php3_mode]}
PHP4_MODE_OPT=${options_conf[php4_mode]}

SECURE_PHP_OPT=${options_conf[secure_php]}
PHP_INI_TYPE_OPT=${options_conf[php_ini_type]}
REDIS_OPT=${options_conf[redis]}

#php_extensions.conf options
PHP_BZ2_OPT=${php_extensions_conf[bz2]}
PHP_GMP_OPT=${php_extensions_conf[gmp]}
PHP_HTSCANNER_OPT=${php_extensions_conf[htscanner]}
PHP_IGBINARY_OPT=${php_extensions_conf[igbinary]}
PHP_IMAGICK_OPT=${php_extensions_conf[imagick]}
PHP_IMAP_OPT=${php_extensions_conf[imap]}
PHP_IONCUBE_OPT=${php_extensions_conf[ioncube]}
PHP_LDAP_OPT=${php_extensions_conf[ldap]}
PHP_OPCACHE_OPT=${php_extensions_conf[opcache]}
PHP_PHALCON_OPT=${php_extensions_conf[phalcon]}
PHP_REDIS_OPT=${php_extensions_conf[redis]}
PHP_READLINE_OPT=${php_extensions_conf[readline]}
PHP_SUHOSIN_OPT=${php_extensions_conf[suhosin]}
PHP_SNUFFLEUPAGUS_OPT=${php_extensions_conf[snuffleupagus]}
PHP_XMLRPC_OPT=${php_extensions_conf[xmlrpc]}
PHP_ZEND_OPT=${php_extensions_conf[zend]}

#backwards compatibility
IONCUBE_OPT=${PHP_IONCUBE_OPT}
OPCACHE_OPT=${PHP_OPCACHE_OPT}
HTSCANNER_OPT=${PHP_HTSCANNER_OPT}
ZEND_OPT=${PHP_ZEND_OPT}
IMAGICK_OPT=${PHP_IMAGICK_OPT}
SUHOSIN_OPT=${PHP_SUHOSIN_OPT}

SUHOSIN_PHP_UPLOADSCAN_OPT=${options_conf[suhosin_php_uploadscan]}
X_MAIL_HEADER_OPT=${options_conf[x_mail_header]}

APCONF=ap2

HAVE_FPM_CGI=no
HAVE_FCGID=no
HAVE_LSPHP=no

load_configure_scripts() {
	declare -A scripts=(
		[apache]="ap2/configure.apache"
		[nginx]="nginx/configure.nginx"
		[nginx_reverse]="nginx_reverse/configure.nginx"
		[dovecot]="dovecot/configure.dovecot"
		[proftpd]="proftpd/configure.proftpd"
		[pureftpd]="pureftpd/configure.pureftpd"
		[imagemagick]="imagemagick/configure.imagemagick"
		[unit]="unit/configure.unit"
		[openlitespeed]="openlitespeed/configure.openlitespeed"
		[modsecurity]="modsecurity/configure.modsecurity"
		[apache_modsecurity]="ap2/configure.modsecurity"
	)

	declare -A exceptions
	local rel short
	for rel in ${PHP1_RELEASE_SET}; do
		short=${rel//./}
		scripts[php${short}]="php/configure.php${short}"          # For CB plugin
		scripts[php${short}_php-fpm]="php/configure.php${short}"
		scripts[php${short}_fastcgi]="php/configure.php${short}"
		scripts[php${short}_lsphp]="php/configure.php${short}"

		# Lower priority legacy file locations
		exceptions[php${short}_php-fpm]="${WORKDIR}/custom/fpm/configure.php${short}"
		exceptions[php${short}_fastcgi]="${WORKDIR}/custom/fastcgi/configure.php${short}"
		exceptions[php${short}_lsphp]="${WORKDIR}/custom/litespeed/configure.php${short}"
	  done


	declare -gA configure_scripts_main
	declare -gA configure_scripts_custom
	declare -gA configure_scripts_active
	local key
	for key in "${!scripts[@]}"; do
		configure_scripts_main[$key]="${WORKDIR}/configure/${scripts[$key]}"
		configure_scripts_custom[$key]="${WORKDIR}/custom/${scripts[$key]}"
		if [ -f "${configure_scripts_custom[$key]}" ]; then
			configure_scripts_active[$key]="${configure_scripts_custom[$key]}"
		elif [ -n "${exceptions[$key]}" ] && [ -f "${exceptions[$key]}" ]; then
			configure_scripts_active[$key]=${exceptions[$key]}
		else
			configure_scripts_active[$key]="${configure_scripts_main[$key]}"
		fi
	done
}

load_configure_scripts

for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
	declare "HAVE_FPM${php_shortrelease}_CGI=no"
	declare "HAVE_FCGID${php_shortrelease}=no"
	declare "HAVE_LSPHP${php_shortrelease}=no"
done

if [ "${PHP1_RELEASE_OPT}" != "no" ] && [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
	HAVE_FPM_CGI=yes
	declare "HAVE_FPM${PHP1_SHORTRELEASE}_CGI=yes"
fi
if [ "${PHP2_RELEASE_OPT}" != "no" ] && [ "${PHP2_MODE_OPT}" = "php-fpm" ]; then
	HAVE_FPM_CGI=yes
	declare "HAVE_FPM${PHP2_SHORTRELEASE}_CGI=yes"
fi
if [ "${PHP3_RELEASE_OPT}" != "no" ] && [ "${PHP3_MODE_OPT}" = "php-fpm" ]; then
	HAVE_FPM_CGI=yes
	declare "HAVE_FPM${PHP3_SHORTRELEASE}_CGI=yes"
fi
if [ "${PHP4_RELEASE_OPT}" != "no" ] && [ "${PHP4_MODE_OPT}" = "php-fpm" ]; then
	HAVE_FPM_CGI=yes
	declare "HAVE_FPM${PHP4_SHORTRELEASE}_CGI=yes"
fi

if [ "${PHP1_RELEASE_OPT}" != "no" ] && [ "${PHP1_MODE_OPT}" = "fastcgi" ]; then
	HAVE_FCGID=yes
	declare "HAVE_FCGID${PHP1_SHORTRELEASE}=yes"
fi
if [ "${PHP2_RELEASE_OPT}" != "no" ] && [ "${PHP2_MODE_OPT}" = "fastcgi" ]; then
	HAVE_FCGID=yes
	declare "HAVE_FCGID${PHP2_SHORTRELEASE}=yes"
fi
if [ "${PHP2_RELEASE_OPT}" != "no" ] && [ "${PHP3_MODE_OPT}" = "fastcgi" ]; then
	HAVE_FCGID=yes
	declare "HAVE_FCGID${PHP3_SHORTRELEASE}=yes"
fi
if [ "${PHP2_RELEASE_OPT}" != "no" ] && [ "${PHP4_MODE_OPT}" = "fastcgi" ]; then
	HAVE_FCGID=yes
	declare "HAVE_FCGID${PHP4_SHORTRELEASE}=yes"
fi

if [ "${PHP1_RELEASE_OPT}" != "no" ] && [ "${PHP1_MODE_OPT}" = "lsphp" ]; then
	HAVE_LSPHP=yes
	declare "HAVE_LSPHP${PHP1_SHORTRELEASE}=yes"
fi
if [ "${PHP2_RELEASE_OPT}" != "no" ] && [ "${PHP2_MODE_OPT}" = "lsphp" ]; then
	HAVE_LSPHP=yes
	declare "HAVE_LSPHP${PHP2_SHORTRELEASE}=yes"
fi
if [ "${PHP3_RELEASE_OPT}" != "no" ] && [ "${PHP3_MODE_OPT}" = "lsphp" ]; then
	HAVE_LSPHP=yes
	declare "HAVE_LSPHP${PHP3_SHORTRELEASE}=yes"
fi
if [ "${PHP4_RELEASE_OPT}" != "no" ] && [ "${PHP4_MODE_OPT}" = "lsphp" ]; then
	HAVE_LSPHP=yes
	declare "HAVE_LSPHP${PHP4_SHORTRELEASE}=yes"
fi

#MySQL
MYSQL_INST_OPT=${options_conf[mysql_inst]}

MYSQL_BACKUP_OPT=${options_conf[mysql_backup]}
MYSQL_OPT=${options_conf[mysql]}
MARIADB_OPT=${options_conf[mariadb]}
MYSQL_BACKUP_GZIP_OPT=${options_conf[mysql_backup_gzip]}
MYSQL_BACKUP_DIR_OPT=${options_conf[mysql_backup_dir]}

MYSQLNAME="MySQL"
if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
	MYSQLNAME="MariaDB"
fi

#Email
DOVECOT_OPT=${options_conf[dovecot]}
DOVECOT_CONF_OPT=${options_conf[dovecot_conf]}
PIGEONHOLE_OPT=${options_conf[pigeonhole]}
MAIL_COMPRESS_OPT=${options_conf[mail_compress]}

EXIM_OPT=${options_conf[exim]}
EXIMCONF_OPT=${options_conf[eximconf]}
BLOCKCRACKING_OPT=${options_conf[blockcracking]}
EASY_SPAM_FIGHTER_OPT=${options_conf[easy_spam_fighter]}

#Applications
PHPMYADMIN_OPT=${options_conf[phpmyadmin]}
PHPMYADMIN_PUBLIC_OPT=${options_conf[phpmyadmin_public]}
SQUIRRELMAIL_OPT=${options_conf[squirrelmail]}
ROUNDCUBE_OPT=${options_conf[roundcube]}
WEBAPPS_INBOX_PREFIX_OPT=${options_conf[webapps_inbox_prefix]}

#Statistics software
AWSTATS_OPT=${options_conf[awstats]}
WEBALIZER_OPT=${options_conf[webalizer]}

SSL_CONFIGURATION_OPT=${options_conf[ssl_configuration]}

#CustomBuild
CLEAN_OLD_TARBALLS_OPT=${options_conf[clean_old_tarballs]}
CLEAN_OLD_WEBAPPS_OPT=${options_conf[clean_old_webapps]}

#Cron
CRON_OPT=${options_conf[cron]}
CRON_FREQUENCY_OPT=${options_conf[cron_frequency]}
EMAIL_OPT=${options_conf[email]}
NOTIFICATIONS_OPT=${options_conf[notifications]}
UPDATES_OPT=${options_conf[updates]}
WEBAPPS_UPDATES_OPT=${options_conf[webapps_updates]}

allSettings() {
	for section in $ALL_SECTIONS; do
		PHP_EXT_SETTINGS_SECTION=false
		PHP_EXT_SETTINGS_SECTION_PREFIX=""
		if [ ${section} = "PHP_EXT_SETTINGS" ]; then
			PHP_EXT_SETTINGS_SECTION=true
			PHP_EXT_SETTINGS_SECTION_PREFIX="PHP_"
		fi
		DESC=${section}_DESC
		echo "------------------------------------------"
		echo "${!DESC}"
		echo "------------------------------------------"
		for setting in ${!section}; do
			SETTING_NAME=`echo $setting | tr "[A-Z]" "[a-z]"`
			POSSIBLE_VALUES_VAR=${PHP_EXT_SETTINGS_SECTION_PREFIX}${setting}_SET
			POSSIBLE_VALUES="`echo ${!POSSIBLE_VALUES_VAR} | awk -v OFS=", " '$1=$1'`"
			DEFAULT_VALUE=${PHP_EXT_SETTINGS_SECTION_PREFIX}${setting}_DEF
			CURRENT_VALUE=${PHP_EXT_SETTINGS_SECTION_PREFIX}${setting}_OPT
			echo -n "${SETTING_NAME}: ${POSSIBLE_VALUES}. Current value: ${!CURRENT_VALUE}. Default value: ${!DEFAULT_VALUE}."
			if [ "$1" = "full" ]; then
				DESCRIPTION="${PHP_EXT_SETTINGS_SECTION_PREFIX}${setting}_DESC"
				echo " Description: ${!DESCRIPTION}"
			else
				echo ""
			fi
		done
		echo ""
	done
}

allSettingsJSON() {
	echo "{"
	NUM_OF_SECTIONS=`echo $ALL_SECTIONS | wc -w`
	CUR_SECTION=0
	for section in $ALL_SECTIONS; do
		PHP_EXT_SETTINGS_SECTION=false
		PHP_EXT_SETTINGS_SECTION_PREFIX=""
		if [ ${section} = "PHP_EXT_SETTINGS" ]; then
			PHP_EXT_SETTINGS_SECTION=true
			PHP_EXT_SETTINGS_SECTION_PREFIX="PHP_"
		fi
		CUR_SECTION=`expr ${CUR_SECTION} + 1`
		NUM_OF_SETTINGS=`echo "${!section}" | wc -w`
		CUR_SETTING=0
		LOWERCASE_SECTION=`echo $section | tr "[A-Z]" "[a-z]"`
		SECTION_DESC=${section}_DESC
		printf "\t\"${LOWERCASE_SECTION}\": {\n"
		printf "\t\t\"description\": \"${!SECTION_DESC}\",\n"
		for setting in ${!section}; do
			CUR_SETTING=`expr ${CUR_SETTING} + 1`
			SETTING_NAME=`echo $setting | tr "[A-Z]" "[a-z]"`

			POSSIBLE_VALUES_VAR=${PHP_EXT_SETTINGS_SECTION_PREFIX}${setting}_SET
			POSSIBLE_VALUES=""
			NUM_OF_VALUES=`echo ${!POSSIBLE_VALUES_VAR} | wc -w`
			CUR_VALUE=0
			for value in ${!POSSIBLE_VALUES_VAR}; do
				CUR_VALUE=`expr ${CUR_VALUE} + 1`
				if [ ${CUR_VALUE} -ne ${NUM_OF_VALUES} ]; then
					POSSIBLE_VALUES="${POSSIBLE_VALUES}\"$value\","
				else
					POSSIBLE_VALUES="${POSSIBLE_VALUES}\"${value}\""
				fi
			done
			DEFAULT_VALUE=${PHP_EXT_SETTINGS_SECTION_PREFIX}${setting}_DEF
			CURRENT_VALUE=${PHP_EXT_SETTINGS_SECTION_PREFIX}${setting}_OPT
			DESCRIPTION="${setting}_DESC"

			printf "\t\t\"${SETTING_NAME}\": {\n"
				printf "\t\t\t\"values\": [${POSSIBLE_VALUES}],\n"
				printf "\t\t\t\"default\": \"${!DEFAULT_VALUE}\",\n"
				printf "\t\t\t\"current\": \"${!CURRENT_VALUE}\",\n"
				printf "\t\t\t\"description\": \"${!DESCRIPTION}\"\n"
			if [ ${CUR_SETTING} -ne ${NUM_OF_SETTINGS} ]; then
				printf "\t\t},\n"
			else
				printf "\t\t}\n"
			fi
		done
		if [ ${CUR_SECTION} -ne ${NUM_OF_SECTIONS} ]; then
			printf "\t},\n"
		else
			printf "\t}\n"
		fi
	done
	echo "}"
}
OPENSSL_VERSION_CACHE=0
openssl_version() {
	if [ "${OPENSSL_VERSION_CACHE}" = "0" ] && [ -x /usr/bin/openssl ]; then
		#doesn't include letters!
		OPENSSL_VERSION_CACHE=`/usr/bin/openssl version | head -n1 | cut -d\  -f2 | cut -d- -f1 | tr -d '[a-z]'`
	fi
	echo $OPENSSL_VERSION_CACHE
}

MYSQL_VERSION_CACHE=0
mysql_version() {
	if [ "${MYSQL_VERSION_CACHE}" = "0" ] && [ -x ${MYSQL_BIN} ]; then
		MYSQL_VERSION_CACHE=`${MYSQL_BIN} --version | grep -m1 -o '[0-9]*\.[0-9]*\.[0-9]*'`
	fi
	echo $MYSQL_VERSION_CACHE	
}

MYSQL_MAIN_CACHE=0
mysql_main() {
	if [ "${MYSQL_MAIN_CACHE}" = "0" ] && [ -x ${MYSQL_BIN} ]; then
		MYSQL_MAIN_CACHE=`${MYSQL_BIN} --version | grep -m1 -o '[0-9]*\.[0-9]*\.[0-9]*' | cut -d. -f1,2`
	fi
	echo $MYSQL_MAIN_CACHE
}

####################################################

doRestartDA() {
	"${DA_BIN}" taskq --run 'action=directadmin&value=reload'
}

doDeprecationChecks() {
	local forum_post_footer=$'\n\n'"More information: https://forum.directadmin.com/threads/directadmin-custombuild-removal-of-outdated-software.67157/"

	# has EOL MySQL
	IS_MYSQL_EOL=false
	CURRENT_MYSQLV=`mysql --defaults-extra-file=/usr/local/directadmin/conf/my.cnf -e "SELECT VERSION();" -sss 2>/dev/null | cut -d. -f1,2`
	case "${CURRENT_MYSQLV}" in
		5.5) IS_MYSQL_EOL=true ;;
		5.6) IS_MYSQL_EOL=true ;;
		10.0) IS_MYSQL_EOL=true ;;
		10.1) IS_MYSQL_EOL=true ;;
		10.2) IS_MYSQL_EOL=true ;;
	esac

	if ${IS_MYSQL_EOL}; then
		send_da_message "Your MySQL/MariaDB version ${CURRENT_MYSQLV} is EOL" "Support of MySQL/MariaDB ${CURRENT_MYSQLV} will be removed soon, please switch to a newer version.${forum_post_footer}"
	fi
}

doChecks() {
	doCSFpignore

	if [ -s ${WORKDIR}/config.json ]; then
		if grep -m1 -q 8372 ${WORKDIR}/config.json; then
			rm -f ${WORKDIR}/config.json
		fi
	fi

	if [ ! -s /etc/mime.types ]; then
		curl ${CURL_CONNECT_OPTIONS} ${WEBPATH}/mime.types -o /etc/mime.types
	fi

	if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
		CORRECT_MARIADB_VER="`echo ${MARIADB_SET} | grep -c ${MARIADB_OPT}`"
		if [ "${CORRECT_MARIADB_VER}" = "0" ]; then
			do_exit 1 "Incorrect mysql value (used to specify MariaDB release) set in the options.conf file. Set: ${MARIADB_OPT}. Available values: ${MARIADB_SET}."
		fi
		if [ "${MARIADB_OPT}" != "5.5" ] && [ "${MARIADB_OPT}" != "10.0" ] && [ "${MARIADB_OPT}" != "10.1" ] && [ "${MARIADB_OPT}" != "10.2" ] && [ "${MARIADB_OPT}" != "10.3" ] && [ "${MARIADB_OPT}" != "10.4" ] && [ "${MARIADB_OPT}" != "10.5" ] && [ "${MARIADB_OPT}" != "10.6" ]; then
			do_exit 1 "Wrong mariadb value set in ${OPTIONS_CONF}."
		fi
	elif [ "${MYSQL_INST_OPT}" = "mysql" ]; then
		CORRECT_MYSQL_VER="`echo ${MYSQL_SET} | grep -c ${MYSQL_OPT}`"
		if [ "${CORRECT_MYSQL_VER}" = "0" ]; then
			do_exit 1 "Incorrect mysql value (used to specify MySQL release) set in the options.conf file. Set: ${MYSQL_OPT}. Available values: ${MYSQL_SET}."
		fi
		if [ "${MYSQL_OPT}" != "5.5" ] && [ "${MYSQL_OPT}" != "5.6" ] && [ "${MYSQL_OPT}" != "5.7" ] && [ "${MYSQL_OPT}" != "8.0" ]; then
			do_exit 1 "Wrong mysql value set in ${OPTIONS_CONF}."
		fi
	fi

	if [ "${PHP_INI_TYPE_OPT}" != "development" ] && [ "${PHP_INI_TYPE_OPT}" != "production" ]; then
		do_exit 1 "Wrong php_ini_type set in options.conf."
	fi

	if [ "${WEBSERVER_OPT}" = "nginx" ]; then
		if [ "${HAVE_FCGID}" = "yes" ] || [ "${HAVE_LSPHP}" = "yes" ]; then
			do_exit 1 "nginx webserver is only compatible with php-fpm PHP mode."
		fi
	fi

	if [ "${WEBSERVER_OPT}" != "openlitespeed" ] && [ "${WEBSERVER_OPT}" != "litespeed" ] && [ "${SSL_CONFIGURATION_OPT}" = "modern" ]; then
		OFFER_MODERN_SSL_SET=true
		if debian_version_is 9; then
			OFFER_MODERN_SSL_SET=false
			OS_NAME="Debian 9"
		fi
		if rhel_version_is 7; then
			OFFER_MODERN_SSL_SET=false
			OS_NAME="CentOS/RHEL/CloudLinux 7"
		fi
		if ! ${OFFER_MODERN_SSL_SET}; then
			do_exit 1 "${WEBSERVER_OPT} webserver does not support 'modern' ssl_configuration option due to lack of support of TLSv1.3 in OpenSSL package on ${OS_NAME}."
		fi
	fi

	if [ "${options_conf[mod_ruid2]}" != "no" ]; then
		do_exit 1 "mod_ruid2 is not supported anymore, please set mod_ruid2=no in CustomBuild 'options.conf'."
	fi

	if [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		if [ "${PHP1_MODE_OPT}" != "lsphp" ]; then
			do_exit 1 "php1_mode must be set to lsphp when using ${WEBSERVER_OPT} WEB server."
		fi
		if [ "${PHP2_MODE_OPT}" != "lsphp" ] && [ "${PHP2_RELEASE_OPT}" != "no" ]; then
			do_exit 1 "php2_mode must be set to lsphp when using ${WEBSERVER_OPT} WEB server."
		fi
		if [ "${PHP3_MODE_OPT}" != "lsphp" ] && [ "${PHP3_RELEASE_OPT}" != "no" ]; then
			do_exit 1 "php3_mode must be set to lsphp when using ${WEBSERVER_OPT} WEB server."
		fi
		if [ "${PHP4_MODE_OPT}" != "lsphp" ] && [ "${PHP4_RELEASE_OPT}" != "no" ]; then
			do_exit 1 "php4_mode must be set to lsphp when using ${WEBSERVER_OPT} WEB server."
		fi
	elif [ "${CLOUDLINUX_OPT}" != "yes" ] || is_cloudlinux_solo; then
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			if [ "${PHP1_MODE_OPT}" = "lsphp" ]; then
				do_exit 1 "php1_mode cannot be set to lsphp when using ${WEBSERVER_OPT} WEB server and CloudLinux disabled."
			fi
			if [ "${PHP2_MODE_OPT}" = "lsphp" ] && [ "${PHP2_RELEASE_OPT}" != "no" ]; then
				do_exit 1 "php2_mode cannot be set to lsphp when using ${WEBSERVER_OPT} WEB server and CloudLinux disabled."
			fi
			if [ "${PHP3_MODE_OPT}" = "lsphp" ] && [ "${PHP3_RELEASE_OPT}" != "no" ]; then
				do_exit 1 "php3_mode cannot be set to lsphp when using ${WEBSERVER_OPT} WEB server and CloudLinux disabled."
			fi
			if [ "${PHP4_MODE_OPT}" = "lsphp" ] && [ "${PHP4_RELEASE_OPT}" != "no" ]; then
				do_exit 1 "php4_mode cannot be set to lsphp when using ${WEBSERVER_OPT} WEB server and CloudLinux disabled."
			fi
		fi
	fi

	if [ "${PHP1_MODE_OPT}" != "php-fpm" ] && [ "${PHP1_MODE_OPT}" != "fastcgi" ] && [ "${PHP1_MODE_OPT}" != "lsphp" ]; then
		do_exit 1 "PHP mode '${PHP1_MODE_OPT}' is not supported, please set php1_release=php-fpm|fastcgi|lsphp in CustomBuild 'options.conf'."
	fi
	if [ "${PHP2_MODE_OPT}" != "php-fpm" ] && [ "${PHP2_MODE_OPT}" != "fastcgi" ] && [ "${PHP2_MODE_OPT}" != "lsphp" ]; then
		do_exit 1 "PHP mode '${PHP2_MODE_OPT}' is not supported, please set php2_release=php-fpm|fastcgi|lsphp in CustomBuild 'options.conf'."
	fi
	if [ "${PHP3_MODE_OPT}" != "php-fpm" ] && [ "${PHP3_MODE_OPT}" != "fastcgi" ] && [ "${PHP3_MODE_OPT}" != "lsphp" ]; then
		do_exit 1 "PHP mode '${PHP3_MODE_OPT}' is not supported, please set php3_release=php-fpm|fastcgi|lsphp in CustomBuild 'options.conf'."
	fi
	if [ "${PHP4_MODE_OPT}" != "php-fpm" ] && [ "${PHP4_MODE_OPT}" != "fastcgi" ] && [ "${PHP4_MODE_OPT}" != "lsphp" ]; then
		do_exit 1 "PHP mode '${PHP4_MODE_OPT}' is not supported, please set php4_release=php-fpm|fastcgi|lsphp in CustomBuild 'options.conf'."
	fi

	PHP1_RELEASE_CHECK=0
	for i in ${PHP1_RELEASE_SET}; do
		if [ "${PHP1_RELEASE_OPT}" = "$i" ]; then
			PHP1_RELEASE_CHECK=1
		fi
	done

	PHP2_RELEASE_CHECK=0
	for i in ${PHP2_RELEASE_SET}; do
		if [ "${PHP2_RELEASE_OPT}" = "$i" ]; then
			PHP2_RELEASE_CHECK=1
		fi
	done

	PHP3_RELEASE_CHECK=0
	for i in ${PHP3_RELEASE_SET}; do
		if [ "${PHP3_RELEASE_OPT}" = "$i" ]; then
			PHP3_RELEASE_CHECK=1
		fi
	done
	
	PHP4_RELEASE_CHECK=0
	for i in ${PHP4_RELEASE_SET}; do
		if [ "${PHP4_RELEASE_OPT}" = "$i" ]; then
			PHP4_RELEASE_CHECK=1
		fi
	done

	if [ "${PHP1_RELEASE_CHECK}" = "0" ]; then
		do_exit 1 "Wrong php1_release set in the options.conf: ${PHP1_RELEASE_OPT}."
	elif [ "${PHP2_RELEASE_CHECK}" = "0" ]; then
		do_exit 1 "Wrong php2_release set in the options.conf: ${PHP2_RELEASE_OPT}."
	elif [ "${PHP3_RELEASE_CHECK}" = "0" ]; then
		do_exit 1 "Wrong php3_release set in the options.conf: ${PHP3_RELEASE_OPT}."
	elif [ "${PHP4_RELEASE_CHECK}" = "0" ]; then
		do_exit 1 "Wrong php4_release set in the options.conf: ${PHP4_RELEASE_OPT}."
	fi
	
	# Check for the same versions set
	SAME_PHP_VERSION=false
	if [ "${PHP1_RELEASE_OPT}" = "${PHP2_RELEASE_OPT}" ] || [ "${PHP1_RELEASE_OPT}" = "${PHP3_RELEASE_OPT}" ] || [ "${PHP1_RELEASE_OPT}" = "${PHP4_RELEASE_OPT}" ]; then
		SAME_PHP_VERSION=true
	fi
	if  [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		if [ "${PHP2_RELEASE_OPT}" = "${PHP3_RELEASE_OPT}" ] || [ "${PHP2_RELEASE_OPT}" = "${PHP4_RELEASE_OPT}" ]; then
			SAME_PHP_VERSION=true
		fi
	fi
	if [ "${PHP4_RELEASE_OPT}" != "no" ] && [ "${PHP3_RELEASE_OPT}" = "${PHP4_RELEASE_OPT}" ]; then
		SAME_PHP_VERSION=true
	fi
	
	if ${SAME_PHP_VERSION}; then
		do_exit 1 "Cannot install the same version of PHP for both releases."
	fi
	
	#ensure php2/3/4_release is not set twice
	for php_number in {2..4}; do {
		C=`grep -c -e "^php${php_number}_release=" ${OPTIONS_CONF}`
		if [ "${C}" -gt 1 ]; then
			grep -e "^php${php_number}_release=" ${OPTIONS_CONF}
			do_exit 1 "php${php_number}_release has been set twice in the options.conf.  This will cause problems. Edit it to remove one of them."
		fi
		C=`grep -c -e "^php${php_number}_mode=" ${OPTIONS_CONF}`
		if [ "${C}" -gt 1 ]; then
			grep -e "^php${php_number}_mode=" ${OPTIONS_CONF}
			do_exit 1 "php${php_number}_mode has been set twice in the options.conf.  This will cause problems. Edit it to remove one of them."
		fi
	};
	done

# WARNING: REPETITION IS EVIL BUSINESS: it might be better to write it as a for loop

	#php 5.5 and older will never compile with openssl 1.1.0
	if [ "${PHP1_RELEASE_OPT}" = "5.3" ] || [ "${PHP1_RELEASE_OPT}" = "5.4" ] || [ "${PHP1_RELEASE_OPT}" = "5.5" ] || [ "${PHP2_RELEASE_OPT}" = "5.3" ] || [ "${PHP2_RELEASE_OPT}" = "5.4" ] || [ "${PHP2_RELEASE_OPT}" = "5.5" ] || [ "${PHP3_RELEASE_OPT}" = "5.3" ] || [ "${PHP3_RELEASE_OPT}" = "5.4" ] || [ "${PHP3_RELEASE_OPT}" = "5.5" ] || [ "${PHP4_RELEASE_OPT}" = "5.3" ] || [ "${PHP4_RELEASE_OPT}" = "5.4" ] || [ "${PHP4_RELEASE_OPT}" = "5.5" ]; then
		OV=`openssl_version | cut -d. -f1,2`
		if [ "${OV}" != "" ] && [ "`version_cmp ${OV} 1.1 'php 5.x vs openssl 1.1.0 ver check'`" -ge 0 ] && [ ! -e ${WORKDIR}/custom/fpm/.custom_openssl ]; then
			do_exit 1 "php 5.3, 5.4, 5.5 cannot compile against openssl 1.1.0 or higher. Try php 5.6 or higher."
		fi
	fi
	#php 8.0 and older will never compile with openssl 3.0
	if echo "${PHP1_RELEASE_OPT}" | grep -q '^5\|^7\|^8\.0' || echo "${PHP2_RELEASE_OPT}" | grep -q '^5\|^7\|^8\.0' || echo "${PHP3_RELEASE_OPT}" | grep -q '^5\|^7\|^8\.0' || echo "${PHP4_RELEASE_OPT}" | grep -q '^5\|^7\|^8\.0'; then
		OV=`openssl_version | cut -d. -f1,2`
		if [ "${OV}" != "" ] && [ "`version_cmp ${OV} 3.0 'php 5.x and 7.x vs openssl 3.0 ver check'`" -ge 0 ] && [ ! -e ${WORKDIR}/custom/fpm/.custom_openssl ]; then
			do_exit 1 "php 5.x, 7.x and 8.0 cannot compile against openssl 3.0 or higher. Try php 8.1 or higher."
		fi
	fi	

	if [ "${FTPD_OPT}" = "pureftpd" ]; then
		if [ -s "$DACONF_FILE" ]; then
			UNIFIED_FTP=`/usr/local/directadmin/directadmin c | grep -m1 unified_ftp_password_file | cut -d= -f2`
			if [ "$UNIFIED_FTP" != "1" ]; then
				echo "unified_ftp_password_file is not set to 1.  You must convert before you can use pureftpd"
				echo "Please read this guide: https://www.directadmin.com/features.php?id=1134"
				echo ""
				echo "Simulation:"
				echo "     cd /usr/local/directadmin"
				echo "     echo 'action=convert&value=unifiedftp&simulate=yes' >> data/task.queue"
				echo "     ./dataskq d1"
				echo ""
				echo "Conversion:"
				echo "     cd /usr/local/directadmin"
				echo "     echo 'unified_ftp_password_file=1' >> conf/directadmin.conf"
				echo "     echo 'action=convert&value=unifiedftp' >> data/task.queue"
				echo "     ./dataskq d1"
				do_exit 1 ""
			fi
		fi
	fi

	if [ "${CRON_FREQUENCY_OPT}" != "daily" ] && [ "${CRON_FREQUENCY_OPT}" != "weekly" ] && [ "${CRON_FREQUENCY_OPT}" != "monthly" ]; then
		echo "Wrong cron_frequency value set in ${OPTIONS_CONF}"
		echo "Current value: ${CRON_FREQUENCY_OPT}"
		do_exit 1 "Valid values: daily, weekly, or monthly"
	fi
	
	if [ "${SA_UPDATE_OPT}" != "no" ] && [ "${SA_UPDATE_OPT}" != "daily" ] && [ "${SA_UPDATE_OPT}" != "weekly" ] && [ "${SA_UPDATE_OPT}" != "monthly" ]; then
		echo "Wrong sa_update value set in ${OPTIONS_CONF}"
		echo "Current value: ${SA_UPDATE_OPT}"
		do_exit 1 "Valid values: no, daily, weekly, or monthly"
	fi
    
	if [ "${EASY_SPAM_FIGHTER_OPT}" = "yes" ] && [ "${SPAMD_OPT}" != "spamassassin" ] && [ "${SPAMD_OPT}" != "rspamd" ]; then
		echo "easy_spam_fighter requires spamassassin or rspamd to be enabled."
		do_exit 1 "Install rspamd or SpamAssassin"
	fi

	if [ -e /usr/include/sys/select.h ] && [ ! -s /usr/include/sys/select.h ] && distro_is_rhel; then
		echo "Found broken glibc-headers package, reinstalling..."
		yum -y reinstall glibc-headers
	fi
}

#not sure if we need it anymore? after final commit will do some compilation tests
appendLdSoConf() {
	# Check if ld.so.conf has /usr/local/lib
	if [ ! -e /etc/ld.so.conf ] || [ "`grep -m1 -c -E '/usr/local/lib$' /etc/ld.so.conf`" = "0" ]; then
		echo "/usr/local/lib" >> /etc/ld.so.conf
		/sbin/ldconfig
	fi

	# Check if ld.so.conf has /usr/local/lib64
	if [ -d /usr/local/lib64 ]; then
		if [ ! -e /etc/ld.so.conf ] || [ "`grep -m1 -c -E '/usr/local/lib64$' /etc/ld.so.conf`" = "0" ]; then
			echo "/usr/local/lib64" >> /etc/ld.so.conf
			/sbin/ldconfig
		fi
	fi
}

addYumExcludes() {
	#Add some yum excludes on RHEL based systems
	if [ -s /etc/yum.conf ]; then
		if ! grep -q '^exclude=' /etc/yum.conf; then
			echo "exclude=apache* nginx* httpd* mod_* mysql* MySQL* mariadb* da_* *ftpd exim* sendmail* php* bind-chroot* dovecot*" >> /etc/yum.conf
		fi
	fi
}

####################################################

add_to_system_backup() {
	SB_TYPE=$1
	SB_WHERE=$2

	F=/usr/local/sysbk/mod/custom.$SB_TYPE
	if [ ! -e ${F} ]; then
		return
	fi
	
	if [ ! -e ${SB_WHERE} ]; then
		echo "add_to_system_backups: cannot find $SB_WHERE to add to $F";
		return
	fi
	
	C=`grep -c -e "^${SB_WHERE}\$" $F`
	if [ "$C" -gt 0 ]; then
		return
	fi
	
	echo "${SB_WHERE}" >> $F
	echo "$SB_WHERE added to $F"
}

####################################################

# Rewrite directadmin-vhosts.conf
doVhosts() {
	PATHNAME=${HTTPDCONF}/extra

	if [ "${WEBSERVER_OPT}" = "nginx" ]; then
		PATHNAME=${NGINXCONF}
	elif [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		PATHNAME=${LSWS_HOME}/conf
	fi

	if [ ! -d ${PATHNAME} ]; then
		mkdir -p ${PATHNAME}
	fi
	echo -n '' > ${PATHNAME}/directadmin-vhosts.conf
	if [ "${WEBSERVER_OPT}" = "nginx" ]; then
		for i in /usr/local/directadmin/data/users/*/nginx.conf; do
			echo "include $i;" >> ${PATHNAME}/directadmin-vhosts.conf
		done
	elif [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		for i in /usr/local/directadmin/data/users/*/httpd.conf; do
			echo "Include $i" >> ${PATHNAME}/directadmin-vhosts.conf
		done
	elif [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		for i in /usr/local/directadmin/data/users/*/openlitespeed.conf; do
			echo "include $i" >> ${PATHNAME}/directadmin-vhosts.conf
		done
	elif [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo -n '' > ${NGINXCONF}/directadmin-vhosts.conf
		for i in /usr/local/directadmin/data/users/*/nginx.conf; do
			echo "include $i;" >> ${NGINXCONF}/directadmin-vhosts.conf
		done
		for i in /usr/local/directadmin/data/users/*/httpd.conf; do
			echo "Include $i" >> ${PATHNAME}/directadmin-vhosts.conf
		done
	fi
}

####################################################

# We need this up for compatibility purposes
PHP_INI_OPT=${options_conf[php_ini]}

roundcube_version() {
	RCVERFILE=/var/www/html/roundcube/program/include/iniset.php
	if [ ! -e $RCVERFILE ]; then
		echo 0
		return
	fi
	grep -m1 "RCMAIL_VERSION" $RCVERFILE | cut -d\' -f4 | cut -d\  -f1
}

exim_version() {
	/usr/sbin/exim -bV 2>/dev/null | grep -m1 'built' | head -n1 | awk '{ print $3 }' | tr '_' '.'
}

exim_conf_version() {
	COUNT=0
	T_EXIMCONFV=0
	if [ -e /etc/exim.conf ]; then
		COUNT=`head -n1 /etc/exim.conf | grep -c 'Version'`
		if [ "${COUNT}" -gt 0 ]; then
			T_EXIMCONFV="`head -n1 /etc/exim.conf | awk '{ print $6 }'`"
		fi
		
		if [ "${T_EXIMCONFV}" = "0" ]; then
			COUNT=`head -n2 /etc/exim.conf | grep -c release`
			if [ "${COUNT}" -gt 0 ]; then
				T_EXIMCONFV="`head -n2 /etc/exim.conf | grep release | awk '{ print $2 }' | cut -d. -f4,5,6 | cut -d- -f1`"
			fi
		fi
	fi
	
	if [ "${T_EXIMCONFV}" = "0" ]; then
		writeLog "exim_conf_version: Cannot determine version of /etc/exim.conf";
	fi

	echo $T_EXIMCONFV
}


rspamd_conf_version() {
	local v
	v=$(head -n 1 /etc/exim/rspamd/connect.conf 2>/dev/null | cut -s -d '#' -f 2)
	if [ -z "${v}" ]; then
		# For backwards compatibility, old installations will not have a
		# version in the `connect.conf` file. Can be removed after we
		# bump rspamd version at least once. Even on old systems it will
		# show an update from `0` to the new version if this
		# compatibility block is removed.
		v=$(head -n 1 /etc/exim/rspamd/README.txt 2>/dev/null | cut -s -d '#' -f 2)
	fi
	if [ -z "${v}" ]; then
		v=0
	fi
	echo "${v}"
}

loadVersionsTxt() {
	declare -gA versions_txt
	local file key val
	for file in "${VERSIONS_FILE}" "${VERSIONS_FILE_CUSTOM}"; do
		if [ ! -f "${file}" ]; then
			continue
		fi
		while IFS=':' read -r key val _; do
			if [ -z "${key}" ]; then
				continue
			fi
			versions_txt[$key]=$val
		done < "${file}"
	done
}

loadVersionsTxt

#The following one needs an exception:
ROUNDCUBE_VER=${versions_txt["roundcubemail"]}
ROUNDCUBE_DOWNLOADURL="${WEBPATH_SERVICES}/all/roundcube/roundcubemail-${ROUNDCUBE_VER}.tar.gz"
ROUNDCUBE_MAJOR_VER=`echo ${ROUNDCUBE_VER} | cut -d. -f1`
if [ "${PHP1_RELEASE_OPT}" = "5.3" ]; then
	SQUIRRELMAIL_VER=${versions_txt["squirrelmail"]}
else
	SQUIRRELMAIL_VER=${versions_txt["squirrelmail_svn"]}
fi
SQUIRRELMAIL_DOWNLOADURL="${WEBPATH_SERVICES}/all/squirrelmail-${SQUIRRELMAIL_VER}.tar.gz"

if [ "$1" != "list_configs_json" ]; then
	#####################################################
	# User Variables
	MOD_LSAPI_VER=${versions_txt["mod_lsapi"]}
	MOD_HOSTINGLIMITS_VER=${versions_txt["mod_hostinglimits"]}
	MOD_PROCTITLE_VER=${versions_txt["mod_proctitle"]}
	CL_PHP_LSAPI_VER=${versions_txt["cl-php-litespeed"]}
	NGINX_VER=${versions_txt["nginx"]}
	NGINX_DOWNLOADURL="${WEBPATH}/nginx-${NGINX_VER}.tar.gz"
	NGX_CACHE_PURGE_VER=${versions_txt["ngx_cache_purge"]}
	NGX_CACHE_PURGE_DOWNLOADURL="${WEBPATH}/ngx_cache_purge-${NGX_CACHE_PURGE_VER}.tar.gz"

	APACHE2_VER=${versions_txt["apache2.4"]}
	APACHE2_DOWNLOADURL="${WEBPATH}/httpd-${APACHE2_VER}.tar.gz"

	APR_VER=${versions_txt["apr"]}
	APR_DOWNLOADURL="${WEBPATH}/apr-${APR_VER}.tar.gz"
	APR_UTIL_VER=${versions_txt["apr-util"]}
	APR_UTIL_DOWNLOADURL="${WEBPATH}/apr-util-${APR_UTIL_VER}.tar.gz"

	for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
		PHP_VERSION_NUMBER=${versions_txt["php${php_shortrelease}"]}
		declare "PHP${php_shortrelease}_VER=${PHP_VERSION_NUMBER}"
		declare "PHP${php_shortrelease}_DOWNLOADURL=${WEBPATH}/php-${PHP_VERSION_NUMBER}.tar.gz"
	done

	PHP1_VERSION_EVAL_VAR=PHP${PHP1_SHORTRELEASE}_VER
	PHP1_RELEASE_VER=${!PHP1_VERSION_EVAL_VAR}

	PHP2_RELEASE_VER=no
	if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		PHP2_VERSION_EVAL_VAR=PHP${PHP2_SHORTRELEASE}_VER
		PHP2_RELEASE_VER=${!PHP2_VERSION_EVAL_VAR}
	fi

	PHP3_RELEASE_VER=no
	if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		PHP3_VERSION_EVAL_VAR=PHP${PHP3_SHORTRELEASE}_VER
		PHP3_RELEASE_VER=${!PHP3_VERSION_EVAL_VAR}
	fi

	PHP4_RELEASE_VER=no
	if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		PHP4_VERSION_EVAL_VAR=PHP${PHP4_SHORTRELEASE}_VER
		PHP4_RELEASE_VER=${!PHP4_VERSION_EVAL_VAR}
	fi

	MODSECURITY_VER=${versions_txt["modsecurity"]}
	MODSECURITY_FILENAME=modsecurity
	MODSECURITY_DOWNLOADURL="${WEBPATH}/${MODSECURITY_FILENAME}-${MODSECURITY_VER}.tar.gz"
	LIBMODSECURITY_VER=${versions_txt["modsecurity3"]}
	LIBMODSECURITY_FILENAME=modsecurity
	LIBMODSECURITY_DOWNLOADURL="${WEBPATH}/${LIBMODSECURITY_FILENAME}-v${LIBMODSECURITY_VER}.tar.gz"
	MODSECURITY_NGINX_CONNECTOR_VER=${versions_txt["modsecurity3_nginx"]}
	MODSECURITY_NGINX_CONNECTOR_FILENAME=modsecurity-nginx
	MODSECURITY_NGINX_CONNECTOR_DOWNLOADURL="${WEBPATH}/${MODSECURITY_NGINX_CONNECTOR_FILENAME}-${MODSECURITY_NGINX_CONNECTOR_VER}.tar.gz"
	MODSECURITY_APACHE_CONNECTOR_VER=${versions_txt["modsecurity3_apache"]}
	MODSECURITY_APACHE_CONNECTOR_FILENAME=modsecurity-apache
	MODSECURITY_APACHE_CONNECTOR_DOWNLOADURL="${WEBPATH}/${MODSECURITY_APACHE_CONNECTOR_FILENAME}-${MODSECURITY_APACHE_CONNECTOR_VER}.tar.gz"

	CWAF_RULES_VER=${versions_txt["cwaf_rules"]}
	CWAF_RULES_DOWNLOADURL="${WEBPATH}/cwaf/cwaf_rules-${CWAF_RULES_VER}.tgz"
	CWAF_RULES_NGINX_DOWNLOADURL="${WEBPATH}/cwaf/cwaf_rules_nginx_3-${CWAF_RULES_VER}.tgz"
	CWAF_RULES_LS_DOWNLOADURL="${WEBPATH}/cwaf/cwaf_rules_ls-${CWAF_RULES_VER}.tgz"

	OWASP_RULES_VER=${versions_txt["owasp3_rules"]}
	OWASP_RULES_DOWNLOADURL="${WEBPATH}/owasp-modsecurity-crs-${OWASP_RULES_VER}.tar.gz"
	HTSCANNER_VER=${versions_txt["htscanner"]}
	HTSCANNER_DOWNLOADURL="${WEBPATH}/htscanner-${HTSCANNER_VER}.tgz"
	MOD_ACLR2_VER=${versions_txt["mod_aclr2"]}
	MOD_ACLR2_DOWNLOADURL="${WEBPATH}/mod_aclr2-${MOD_ACLR2_VER}.tar.gz"
	MOD_FCGID_VER=${versions_txt["mod_fcgid"]}
	MOD_FCGID_DOWNLOADURL="${WEBPATH}/mod_fcgid-${MOD_FCGID_VER}.tar.gz"

	MYSQL55_VER=${versions_txt["mysql5.5"]}
	MYSQL55_DOWNLOADURL="${WEBPATH_SERVICES}/all/mysql/5.5/${MYSQL55_VER}/64-bit/mysql-${MYSQL55_VER}-linux-glibc2.12-x86_64.tar.gz"

	MYSQL56_VER=${versions_txt["mysql5.6"]}
	MYSQL55_DOWNLOADURL="${WEBPATH_SERVICES}/all/mysql/5.6/${MYSQL56_VER}/64-bit/mysql-${MYSQL56_VER}-linux-glibc2.12-x86_64.tar.gz"

	MYSQL57_VER=${versions_txt["mysql5.7"]}
	MYSQL55_DOWNLOADURL="${WEBPATH_SERVICES}/all/mysql/5.7/${MYSQL57_VER}/64-bit/mysql-${MYSQL57_VER}-linux-glibc2.12-x86_64.tar.gz"

	MYSQL80_VER=${versions_txt["mysql8.0"]}
	MYSQL55_DOWNLOADURL="${WEBPATH_SERVICES}/all/mysql/8.0/${MYSQL80_VER}/64-bit/mysql-${MYSQL80_VER}-linux-glibc2.12-x86_64.tar.xz"

	MARIADB55_VER=${versions_txt["mariadb5.5"]}
	MARIADB55_DOWNLOADURL="${WEBPATH_SERVICES}/all/mariadb/5.5/${MARIADB55_VER}/mariadb-${MARIADB55_VER}-linux-systemd-x86_64.tar.gz"

	MARIADB100_VER=${versions_txt["mariadb10.0"]}
	MARIADB100_DOWNLOADURL="${WEBPATH_SERVICES}/all/mariadb/10.0/${MARIADB100_VER}/mariadb-${MARIADB100_VER}-linux-systemd-x86_64.tar.gz"

	MARIADB101_VER=${versions_txt["mariadb10.1"]}
	MARIADB101_DOWNLOADURL="${WEBPATH_SERVICES}/all/mariadb/10.1/${MARIADB101_VER}/mariadb-${MARIADB101_VER}-linux-systemd-x86_64.tar.gz"

	MARIADB102_VER=${versions_txt["mariadb10.2"]}
	MARIADB102_DOWNLOADURL="${WEBPATH_SERVICES}/all/mariadb/10.2/${MARIADB102_VER}/mariadb-${MARIADB102_VER}-linux-systemd-x86_64.tar.gz"

	MARIADB103_VER=${versions_txt["mariadb10.3"]}
	MARIADB103_DOWNLOADURL="${WEBPATH_SERVICES}/all/mariadb/10.3/${MARIADB103_VER}/mariadb-${MARIADB103_VER}-linux-systemd-x86_64.tar.gz"

	MARIADB104_VER=${versions_txt["mariadb10.4"]}
	MARIADB104_DOWNLOADURL="${WEBPATH_SERVICES}/all/mariadb/10.4/${MARIADB104_VER}/mariadb-${MARIADB104_VER}-linux-systemd-x86_64.tar.gz"

	MARIADB105_VER=${versions_txt["mariadb10.5"]}
	MARIADB105_DOWNLOADURL="${WEBPATH_SERVICES}/all/mariadb/10.5/${MARIADB105_VER}/mariadb-${MARIADB105_VER}-linux-systemd-x86_64.tar.gz"

	MARIADB106_VER=${versions_txt["mariadb10.6"]}
	MARIADB106_DOWNLOADURL="${WEBPATH_SERVICES}/all/mariadb/10.6/${MARIADB106_VER}/mariadb-${MARIADB106_VER}-linux-systemd-x86_64.tar.gz"

	if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
		if [ "${MYSQL_OPT}" = "5.5" ]; then
			MYSQL_VER=${MYSQL55_VER}
		elif [ "${MYSQL_OPT}" = "5.6" ]; then
			MYSQL_VER=${MYSQL56_VER}
		elif [ "${MYSQL_OPT}" = "5.7" ]; then
			MYSQL_VER=${MYSQL57_VER}
		elif [ "${MYSQL_OPT}" = "8.0" ]; then
			MYSQL_VER=${MYSQL80_VER}
		else
			MYSQL_VER=0
		fi
	else
		if [ "${MARIADB_OPT}" = "5.5" ]; then
			MARIADB_VER=${MARIADB55_VER}
		elif [ "${MARIADB_OPT}" = "10.0" ]; then
			MARIADB_VER=${MARIADB100_VER}
		elif [ "${MARIADB_OPT}" = "10.1" ]; then
			MARIADB_VER=${MARIADB101_VER}
		elif [ "${MARIADB_OPT}" = "10.2" ]; then
			MARIADB_VER=${MARIADB102_VER}
		elif [ "${MARIADB_OPT}" = "10.3" ]; then
			MARIADB_VER=${MARIADB103_VER}
		elif [ "${MARIADB_OPT}" = "10.4" ]; then
			MARIADB_VER=${MARIADB104_VER}
		elif [ "${MARIADB_OPT}" = "10.5" ]; then
			MARIADB_VER=${MARIADB105_VER}
		elif [ "${MARIADB_OPT}" = "10.6" ]; then
			MARIADB_VER=${MARIADB106_VER}
		else
			MARIADB_VER=0
		fi
	fi

	DOVECOT_VER=${versions_txt["dovecot"]}
	DOVECOT_DOWNLOADURL="${WEBPATH}/dovecot-${DOVECOT_VER}.tar.gz"
	DOVECOT_REL=`echo ${DOVECOT_VER} | cut -d. -f1,2`
	PIGEONHOLE_VER=no
	if [ "${DOVECOT_REL}" = "2.3" ]; then
		DOVECOT_SHORTREL=23
		PIGEONHOLE_VER=${versions_txt["pigeonhole23"]}
	fi
	PIGEONHOLE_DOWNLOADURL="${WEBPATH}/dovecot-${DOVECOT_REL}-pigeonhole-${PIGEONHOLE_VER}.tar.gz"
	FTS_XAPIAN_VER=${versions_txt["fts-xapian"]}
	FTS_XAPIAN_DOWNLOADURL="${WEBPATH}/xapian/fts-xapian-${FTS_XAPIAN_VER}.tar.gz"
	XAPIAN_CORE_VER=${versions_txt["xapian-core"]}
	XAPIAN_CORE_DOWNLOADURL="${WEBPATH}/xapian/xapian-core-${XAPIAN_CORE_VER}.tar.xz"
	EXIM_VER=${versions_txt["exim"]}
	EXIM_DOWNLOADURL="${WEBPATH}/exim-${EXIM_VER}.tar.gz"
	BLOCKCRACKING_VER=${versions_txt["blockcracking"]}
	BLOCKCRACKING_DOWNLOADURL="${WEBPATH}/blockcracking/exim.blockcracking-${BLOCKCRACKING_VER}.tar.gz"
	EASY_SPAM_FIGHTER_VER=${versions_txt["easy_spam_figther"]}
	EASY_SPAM_FIGHTER_DOWNLOADURL="${WEBPATH}/easy_spam_fighter/exim.easy_spam_fighter-${EASY_SPAM_FIGHTER_VER}.tar.gz"

	PROFTPD_VER=${versions_txt["proftpd"]}
	PROFTPD_DOWNLOADURL="${WEBPATH}/proftpd-${PROFTPD_VER}.tar.gz"
	PUREFTPD_VER=${versions_txt["pureftpd"]}
	PUREFTPD_DOWNLOADURL="${WEBPATH}/pure-ftpd-${PUREFTPD_VER}.tar.gz"
	COMPOSER_VER=${versions_txt["composer"]}
	WP_VER=${versions_txt["wp-cli"]}
	WP_DOWNLOADURL="${WEBPATH}/wp/${WP_VER}/wp-cli.phar"
	IMAPSYNC_VER=${versions_txt["imapsync"]}
	IMAPSYNC_DOWNLOADURL="${WEBPATH}/imapsync/imapsync-${IMAPSYNC_VER}.tar.gz"
	LEGO_VER=${versions_txt["lego"]}
	LEGO_ARM64_DOWNLOADURL="${WEBPATH}/lego/lego_v${LEGO_VER}_linux_arm64.tar.gz"
	LEGO_AMD64_DOWNLOADURL="${WEBPATH}/lego/lego_v${LEGO_VER}_linux_amd64.tar.gz"
	LEGO_DOWNLOADURL=${LEGO_AMD64_DOWNLOADURL}
	LEGO_FILENAME=lego_v${LEGO_VER}_linux_amd64.tar.gz
	if is_arm64; then
		LEGO_DOWNLOADURL=${LEGO_ARM64_DOWNLOADURL}
		LEGO_FILENAME=lego_v${LEGO_VER}_linux_arm64.tar.gz
	fi
	IMAGICK_VER=${versions_txt["imagick"]}
	IMAGICK_DOWNLOADURL="${WEBPATH}/imagick/imagick-${IMAGICK_VER}.tgz"
	XMLRPC_VER=${versions_txt["xmlrpc"]}
	XMLRPC_DOWNLOADURL="${WEBPATH}/php_extensions/xmlrpc/xmlrpc-${XMLRPC_VER}.tgz"
	IMAGEMAGICK_VER=${versions_txt["imagemagick"]}
	IMAGEMAGICK_DOWNLOADURL="${WEBPATH}/imagick/ImageMagick-${IMAGEMAGICK_VER}.tar.gz"
	AWSTATS_VER=${versions_txt["awstats"]}
	AWSTATS_DOWNLOADURL="${WEBPATH_SERVICES}/all/awstats/awstats-${AWSTATS_VER}.tar.gz"
	UNIT_VER=${versions_txt["unit"]}
	UNIT_DOWNLOADURL="${WEBPATH}/unit/unit-${UNIT_VER}.tar.gz"
	SUHOSIN_VER=${versions_txt["suhosin"]}
	SUHOSIN_DOWNLOADURL="${WEBPATH}/suhosin-${SUHOSIN_VER}.tar.gz"
	OPCACHE_VER=${versions_txt["zendopcache"]}
	OPCACHE_DOWNLOADURL="${WEBPATH}/zendopcache-${OPCACHE_VER}.tgz"

	IGBINARY_VER=${versions_txt["igbinary"]}
	IGBINARY_DOWNLOADURL="https://pecl.php.net/get/igbinary-${IGBINARY_VER}.tgz"
	PSR_VER=${versions_txt["psr"]}
	PSR_DOWNLOADURL="https://pecl.php.net/get/psr-${PSR_VER}.tgz"
	PHALCON4_DOWNLOADURL="https://pecl.php.net/get/phalcon-${versions_txt["phalcon"]}.tgz"
	PHALCON5_DOWNLOADURL="https://pecl.php.net/get/phalcon-${versions_txt["phalcon5"]}.tgz"
	REDIS_VER=${versions_txt["redis"]}
	REDIS_DOWNLOADURL="${WEBPATH}/redis/redis-${REDIS_VER}.tar.gz"
	PHPREDIS_VER=${versions_txt["phpredis"]}
	PHPREDIS_DOWNLOADURL="${WEBPATH}/php_extensions/redis/redis-${PHPREDIS_VER}.tgz"
	SNUFFLEUPAGUS_VER=${versions_txt["snuffleupagus"]}
	SNUFFLEUPAGUS_DOWNLOADURL="${WEBPATH}/php_extensions/snuffleupagus/snuffleupagus-${SNUFFLEUPAGUS_VER}.tar.gz"
	IMAP_VER=${versions_txt["imap"]}
	IMAP_DOWNLOADURL="${WEBPATH_SERVICES}/all/imap/imap-${IMAP_VER}.tar.gz"

	IONCUBE_AMD64_DOWNLOADURL="${WEBPATH}/ioncube_${versions_txt["ioncube_loaders_lin_x86-64"]}/ioncube_loaders_lin_x86-64.tar.gz"
	IONCUBE_ARM64_DOWNLOADURL="${WEBPATH}/ioncube_${versions_txt["ioncube_loaders_lin_aarch64"]}/ioncube_loaders_lin_aarch64.tar.gz"
	IONCUBE_VER=${versions_txt["ioncube_loaders_lin_x86-64"]}
	IONCUBE_DOWNLOADURL=${IONCUBE_AMD64_DOWNLOADURL}
	if is_arm64; then
		IONCUBE_VER=${versions_txt["ioncube_loaders_lin_aarch64"]}
		IONCUBE_DOWNLOADURL=${IONCUBE_ARM64_DOWNLOADURL}
	fi

	# Applications versions
	PHPMYADMIN_VER=${versions_txt["phpmyadmin5"]}
	PHPMYADMIN_DOWNLOADURL="${WEBPATH}/phpMyAdmin/phpMyAdmin-${PHPMYADMIN_VER}.tar.gz"

	SQUIRRELMAIL_LOCALE_VER=${versions_txt["squirrelmail_locale"]}
	SQUIRRELMAIL_LOCALE_DOWNLOADURL="${WEBPATH_SERVICES}/all/squirrelmail/locales/all_locales-${SQUIRRELMAIL_LOCALE_VER}.tar.gz"
	SQUIRRELMAIL_LOGGER_VER=${versions_txt["squirrel_logger"]}
	SQUIRRELMAIL_LOGGER_DOWNLOADURL="${WEBPATH_SERVICES}/all/squirrelmail/squirrel_logger/squirrel_logger-${SQUIRRELMAIL_LOGGER_VER}.tar.gz"

	OPENLITESPEED_VER=${versions_txt["openlitespeed"]}
	OPENLITESPEED_DOWNLOADURL="${WEBPATH}/openlitespeed/openlitespeed-${OPENLITESPEED_VER}.tgz"
	OPENLITESPEED_SRC_DOWNLOADURL="${WEBPATH}/openlitespeed/openlitespeed-${OPENLITESPEED_VER}.src.tgz"
	
	LITESPEED_VER=${versions_txt["litespeed"]}

	# SpamAssassin versions
	SPAMASSASSIN_VER=${versions_txt["spamassassin"]}
	SPAMASSASSIN_DOWNLOADURL="${WEBPATH}/Mail-SpamAssassin-${SPAMASSASSIN_VER}.tar.gz"

	LITESPEED_TRIAL_KEY=${WORKDIR}/configure/litespeed/trial.key
	if [ -e ${WORKDIR}/custom/litespeed/trial.key ]; then
		LITESPEED_TRIAL_KEY=${WORKDIR}/custom/litespeed/trial.key
	fi
fi

# Variable for proftpd
PROFTPD_CONF=configure/proftpd/conf/proftpd.conf
if [ -e custom/proftpd/conf/proftpd.conf ]; then
	PROFTPD_CONF=custom/proftpd/conf/proftpd.conf
fi

# Variable for pureftpd
PUREFTPD_CONF=configure/pureftpd/pure-ftpd.conf
if [ -e custom/pureftpd/pure-ftpd.conf ]; then
	PUREFTPD_CONF=custom/pureftpd/pure-ftpd.conf
fi

# Variables for ModSecurity uploadscan
RUNAV_PL=configure/clamav/runav.pl
if [ -e custom/clamav/runav.pl ]; then
	RUNAV_PL=custom/clamav/runav.pl
fi
RUNAV_CONF=configure/clamav/runav.conf
if [ -e custom/clamav/runav.conf ]; then
	RUNAV_CONF=custom/clamav/runav.conf
fi

# Variable for OPCACHE
OPCACHE_INI=configure/opcache/opcache.ini
if [ -e custom/opcache/opcache.ini ]; then
	OPCACHE_INI=custom/opcache/opcache.ini
fi

# Variable for SUHOSIN
SUHOSIN_INI=configure/suhosin/suhosin.ini
if [ -e custom/suhosin/suhosin.ini ]; then
	SUHOSIN_INI=custom/suhosin/suhosin.ini
fi

EXIM_MAKEFILE=${WORKDIR}/configure/exim/Makefile
if [ -e custom/exim/Makefile ]; then
	EXIM_MAKEFILE=${WORKDIR}/custom/exim/Makefile
fi

# Dovecot variables
DOVECOTCONFDIR=${WORKDIR}/configure/dovecot/conf
DOVECOTCUSTOMCONFDIR=0
if [ -d ${WORKDIR}/custom/dovecot/conf ]; then
	DOVECOTCUSTOMCONFDIR=${WORKDIR}/custom/dovecot/conf
fi

DOVECTCONFFILE=${WORKDIR}/configure/dovecot/dovecot.conf
if [ -e ${WORKDIR}/custom/dovecot/dovecot.conf ]; then
	DOVECTCONFFILE=${WORKDIR}/custom/dovecot/dovecot.conf
fi

DOVECTCONFSIEVE=${WORKDIR}/configure/dovecot/conf.d/90-sieve.conf
if [ -e ${WORKDIR}/custom/dovecot/conf.d/90-sieve.conf ]; then
	DOVECTCONFSIEVE=${WORKDIR}/custom/dovecot/conf.d/90-sieve.conf
fi

DOVECTCONFFTS=${WORKDIR}/configure/dovecot/conf.d/90-fts-xapian.conf
if [ -e ${WORKDIR}/custom/dovecot/conf.d/90-fts-xapian.conf ]; then
	DOVECTCONFFTS=${WORKDIR}/custom/dovecot/conf.d/90-fts-xapian.conf
fi

DOVECTCONFQUOTA=${WORKDIR}/configure/dovecot/conf.d/90-quota.conf
if [ -e ${WORKDIR}/custom/dovecot/conf.d/90-quota.conf ]; then
	DOVECTCONFQUOTA=${WORKDIR}/custom/dovecot/conf.d/90-quota.conf
fi

DOVECOTCONFZLIB=${WORKDIR}/configure/dovecot/conf.d/90-zlib.conf
if [ -e ${WORKDIR}/custom/dovecot/conf.d/90-zlib.conf ]; then
	DOVECOTCONFZLIB=${WORKDIR}/custom/dovecot/conf.d/90-zlib.conf
fi

SA_UPDATE_FILE=${WORKDIR}/configure/spamassassin/sa-update.sh
if [ -e ${WORKDIR}/custom/spamassassin/sa-update.sh ]; then
	SA_UPDATE_FILE=${WORKDIR}/custom/spamassassin/sa-update.sh
fi

# Variables for spamd
SPAMD_CONF=configure/${SPAMD_OPT}/exim.spamd.conf
if [ -e custom/${SPAMD_OPT}/exim.spamd.conf ]; then
	SPAMD_CONF=custom/${SPAMD_OPT}/exim.spamd.conf
fi

# Variables for apache
PHP_HANDLERS_HTTPD=/etc/httpd/conf/extra/httpd-php-handlers.conf

APCONFDIR=${WORKDIR}/configure/${APCONF}/conf
APCUSTOMCONFDIR=0
#custom/configure isn't supposed to be there
if [ -d ${WORKDIR}/custom/configure/${APCONF}/conf ]; then
	APCUSTOMCONFDIR=${WORKDIR}/custom/configure/${APCONF}/conf
fi
if [ -d ${WORKDIR}/custom/${APCONF}/conf ]; then
	APCUSTOMCONFDIR=${WORKDIR}/custom/${APCONF}/conf
fi

APCERTCONF=configure/${APCONF}/cert_config.txt
if [ -e custom/configure/${APCONF}/cert_config.txt ]; then
APCERTCONF=custom/configure/${APCONF}/cert_config.txt
fi
if [ -e custom/${APCONF}/cert_config.txt ]; then
APCERTCONF=custom/${APCONF}/cert_config.txt
fi

# Variables for openlitespeed
OPENLITESPEEDCONFDIR=${WORKDIR}/configure/openlitespeed/conf
OPENLITESPEEDCUSTOMCONFDIR=0
if [ -d ${WORKDIR}/custom/openlitespeed/conf ]; then
	OPENLITESPEEDCUSTOMCONFDIR=${WORKDIR}/custom/openlitespeed/conf
fi

OPENLITESPEED_EXTPROCESSORS_TEMPLATE=configure/openlitespeed/httpd-extprocessors.template
if [ -e custom/openlitespeed/httpd-extprocessors.template ]; then
	OPENLITESPEED_EXTPROCESSORS_TEMPLATE=custom/openlitespeed/httpd-extprocessors.template
fi

OPENLITESPEED_WEBAPPS_EXTPROCESSOR_TEMPLATE=configure/openlitespeed/httpd-webapps-extprocessor.template
if [ -e custom/openlitespeed/httpd-webapps-extprocessor.template ]; then
	OPENLITESPEED_WEBAPPS_EXTPROCESSOR_TEMPLATE=custom/openlitespeed/httpd-webapps-extprocessor.template
fi

# Variables for nginx
if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
	NGINXCONFDIR=${WORKDIR}/configure/nginx_reverse/conf
	NGINXCUSTOMCONFDIR=0
	if [ -d ${WORKDIR}/custom/nginx_reverse/conf ]; then
		NGINXCUSTOMCONFDIR=${WORKDIR}/custom/nginx_reverse/conf
	fi
else
	NGINXCONFDIR=${WORKDIR}/configure/nginx/conf
	NGINXCUSTOMCONFDIR=0
	if [ -d ${WORKDIR}/custom/nginx/conf ]; then
		NGINXCUSTOMCONFDIR=${WORKDIR}/custom/nginx/conf
	fi
fi

NGINXTEMPLATESDIR=${WORKDIR}/configure/nginx_templates
NGINXCUSTOMEMPLATESDIR=0
if [ -d ${WORKDIR}/custom/nginx_templates ]; then
	NGINXCUSTOMEMPLATESDIR=${WORKDIR}/custom/nginx_templates
fi

MODSECURITY_APACHE_INCLUDE=${WORKDIR}/configure/ap2/conf/extra/httpd-modsecurity.conf
if [ -e ${WORKDIR}/custom/ap2/conf/extra/httpd-modsecurity.conf ]; then
	MODSECURITY_APACHE_INCLUDE=${WORKDIR}/custom/ap2/conf/extra/httpd-modsecurity.conf
fi

MODSECURITY_NGINX_INCLUDE=${WORKDIR}/configure/nginx/conf/nginx-modsecurity.conf
if [ -e ${WORKDIR}/custom/nginx/conf/nginx-modsecurity.conf ]; then
	MODSECURITY_NGINX_INCLUDE=${WORKDIR}/custom/nginx/conf/nginx-modsecurity.conf
fi
if [ -s ${WORKDIR}/configure/openlitespeed/conf/httpd-listeners.conf ]; then
	rm -f ${WORKDIR}/configure/openlitespeed/conf/httpd-listeners.conf
fi
MODSECURITY_OPENLITESPEED_INCLUDE=${WORKDIR}/configure/openlitespeed/conf/httpd-modsecurity.conf
if [ -e ${WORKDIR}/custom/openlitespeed/conf/httpd-modsecurity.conf ]; then
	MODSECURITY_OPENLITESPEED_INCLUDE=${WORKDIR}/custom/openlitespeed/conf/httpd-modsecurity.conf
fi

MODSECURITY_NGINX_REVERSE_INCLUDE=${WORKDIR}/configure/nginx_reverse/conf/nginx-modsecurity.conf
if [ -e ${WORKDIR}/custom/nginx_reverse/conf/nginx-modsecurity.conf ]; then
	MODSECURITY_NGINX_REVERSE_INCLUDE=${WORKDIR}/custom/nginx_reverse/conf/nginx-modsecurity.conf
fi

MODSECURITY_CUSTOM_RULES=${WORKDIR}/custom/modsecurity/conf

for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
	# Variables for php-fpm
	declare "PHP${php_shortrelease}_FPM_CONF=${WORKDIR}/configure/fpm/conf/php-fpm.conf.${php_shortrelease}"
	if [ -e ${WORKDIR}/custom/fpm/conf/php-fpm.conf.${php_shortrelease} ]; then
		declare "PHP${php_shortrelease}_FPM_CONF=${WORKDIR}/custom/fpm/conf/php-fpm.conf.${php_shortrelease}"
	fi
	declare "PHP_INI_FPM${php_shortrelease}=/usr/local/php${php_shortrelease}/lib/php.ini"
	declare "PHP_SBIN_FPM${php_shortrelease}=/usr/local/php${php_shortrelease}/sbin/php-fpm${php_shortrelease}"

	declare "PHP_BIN_PHP${php_shortrelease}=/usr/local/php${php_shortrelease}/bin/php${php_shortrelease}"

	declare "PHP_EXT_FPM${php_shortrelease}=/usr/local/php${php_shortrelease}/lib/php.conf.d/10-directadmin.ini"
done

PHP_CUSTOM_PHP_CONF_D_INI_PATH=${WORKDIR}/custom/php.conf.d

#php extensions file rewritten by DirectAdmin
PHP_EXT=/usr/local/lib/php.conf.d/10-directadmin.ini
PHP_INI=/usr/local/lib/php.ini
PHP_BIN=/usr/local/bin/php

PHP1_RELEASE_INI_EVAL="PHP_INI_FPM${PHP1_SHORTRELEASE}"
PHP1_INI_FILE="${!PHP1_RELEASE_INI_EVAL}"
PHP1_RELEASE_INI_EXT_EVAL="PHP_EXT_FPM${PHP1_SHORTRELEASE}"
PHP1_INI_EXT_FILE="${!PHP1_RELEASE_INI_EXT_EVAL}"

PHP1_INI_EXT_FILE_OLD="`echo ${PHP1_INI_EXT_FILE} | perl -p0 -e 's|10-directadmin.ini|directadmin.ini|'`"
if [ -e ${PHP1_INI_EXT_FILE_OLD} ] && [ ! -e ${PHP1_INI_EXT_FILE} ]; then
	mv -f ${PHP1_INI_EXT_FILE_OLD} ${PHP1_INI_EXT_FILE}
fi

PHP2_INI_FILE="no"
PHP2_INI_EXT_FILE="no"
if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
	PHP2_RELEASE_INI_EVAL="PHP_INI_FPM${PHP2_SHORTRELEASE}"
	PHP2_INI_FILE="${!PHP2_RELEASE_INI_EVAL}"
	PHP2_RELEASE_INI_EXT_EVAL="PHP_EXT_FPM${PHP2_SHORTRELEASE}"
	PHP2_INI_EXT_FILE="${!PHP2_RELEASE_INI_EXT_EVAL}"
	PHP2_INI_EXT_FILE_OLD="`echo ${PHP2_INI_EXT_FILE} | perl -p0 -e 's|10-directadmin.ini|directadmin.ini|'`"
	if [ -e ${PHP2_INI_EXT_FILE_OLD} ] && [ ! -e ${PHP2_INI_EXT_FILE} ]; then
		mv -f ${PHP2_INI_EXT_FILE_OLD} ${PHP2_INI_EXT_FILE}
	fi
fi

PHP3_INI_FILE="no"
PHP3_INI_EXT_FILE="no"
if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
	PHP3_RELEASE_INI_EVAL="PHP_INI_FPM${PHP3_SHORTRELEASE}"
	PHP3_INI_FILE="${!PHP3_RELEASE_INI_EVAL}"
	PHP3_RELEASE_INI_EXT_EVAL="PHP_EXT_FPM${PHP3_SHORTRELEASE}"
	PHP3_INI_EXT_FILE="${!PHP3_RELEASE_INI_EXT_EVAL}"
	PHP3_INI_EXT_FILE_OLD="`echo ${PHP3_INI_EXT_FILE} | perl -p0 -e 's|10-directadmin.ini|directadmin.ini|'`"
	if [ -e ${PHP3_INI_EXT_FILE_OLD} ] && [ ! -e ${PHP3_INI_EXT_FILE} ]; then
		mv -f ${PHP3_INI_EXT_FILE_OLD} ${PHP3_INI_EXT_FILE}
	fi
fi

PHP4_INI_FILE="no"
PHP4_INI_EXT_FILE="no"
if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
	PHP4_RELEASE_INI_EVAL="PHP_INI_FPM${PHP4_SHORTRELEASE}"
	PHP4_INI_FILE="${!PHP4_RELEASE_INI_EVAL}"
	PHP4_RELEASE_INI_EXT_EVAL="PHP_EXT_FPM${PHP4_SHORTRELEASE}"
	PHP4_INI_EXT_FILE="${!PHP4_RELEASE_INI_EXT_EVAL}"
	PHP4_INI_EXT_FILE_OLD="`echo ${PHP4_INI_EXT_FILE} | perl -p0 -e 's|10-directadmin.ini|directadmin.ini|'`"
	if [ -e ${PHP4_INI_EXT_FILE_OLD} ] && [ ! -e ${PHP4_INI_EXT_FILE} ]; then
		mv -f ${PHP4_INI_EXT_FILE_OLD} ${PHP4_INI_EXT_FILE}
	fi
fi

#suhosin uploadscan script
SUHOSIN_PHP_UPLOADSCAN_SCRIPT=${WORKDIR}/configure/suhosin/php_uploadscan.sh
if [ -e ${WORKDIR}/custom/suhosin/php_uploadscan.sh ]; then
	SUHOSIN_PHP_UPLOADSCAN_SCRIPT=${WORKDIR}/custom/suhosin/php_uploadscan.sh
fi

#pureftpd uploadscan script
PUREFTPD_UPLOADSCAN_SCRIPT=${WORKDIR}/configure/pureftpd/pureftpd_uploadscan.sh
if [ -e ${WORKDIR}/custom/pureftpd/pureftpd_uploadscan.sh ]; then
	PUREFTPD_UPLOADSCAN_SCRIPT=${WORKDIR}/custom/pureftpd/pureftpd_uploadscan.sh
fi

#pureftpd SNI script
PUREFTPD_PURE_CERTD_SCRIPT=${WORKDIR}/configure/pureftpd/pureftpd_sni.sh
if [ -e ${WORKDIR}/custom/pureftpd/pureftpd_sni.sh ]; then
	PUREFTPD_PURE_CERTD_SCRIPT=${WORKDIR}/custom/pureftpd/pureftpd_sni.sh
fi

PMA_MAIN_CONFIG=${WORKDIR}/configure/phpmyadmin/config.inc.php
PMA_CUSTOM_CONFIG=
if [ -s ${WORKDIR}/custom/phpmyadmin/config.inc.php ]; then
	PMA_CUSTOM_CONFIG=${WORKDIR}/custom/phpmyadmin/config.inc.php
fi

#custom script configs
WEBAPPS_LIST=${WORKDIR}/custom/webapps.list
PMA_HTACCESS=${WORKDIR}/custom/phpmyadmin/.htaccess
PMA_USER_INI=${WORKDIR}/custom/phpmyadmin/.user.ini
PMA_THEMES=${WORKDIR}/custom/phpmyadmin/themes
SQUIRREL_CONFIG=${WORKDIR}/custom/squirrelmail/config.php
ROUNDCUBE_CONFIG=${WORKDIR}/custom/roundcube/config.inc.php
ROUNDCUBE_CONFIG_DB=${ROUNDCUBE_CONFIG}
ROUNDCUBE_CONFIG_OLD=${WORKDIR}/custom/roundcube/main.inc.php
ROUNDCUBE_CONFIG_DB_OLD=${WORKDIR}/custom/roundcube/db.inc.php
if [ "${ROUNDCUBE_MAJOR_VER}" = "0" ]; then
	ROUNDCUBE_CONFIG=${ROUNDCUBE_CONFIG_OLD}
	ROUNDCUBE_CONFIG_DB=${ROUNDCUBE_CONFIG_DB_OLD}
fi
ROUNDCUBE_PLUGINS=${WORKDIR}/custom/roundcube/plugins
ROUNDCUBE_SKINS=${WORKDIR}/custom/roundcube/skins
ROUNDCUBE_VENDOR=${WORKDIR}/custom/roundcube/vendor
ROUNDCUBE_COMPOSER=${WORKDIR}/custom/roundcube/composer.json
ROUNDCUBE_PROGRAM=${WORKDIR}/custom/roundcube/program
ROUNDCUBE_HTACCESS=${WORKDIR}/custom/roundcube/.htaccess

if is_arm64; then
	IONCUBENAME=ioncube_loaders_lin_aarch64
else
	IONCUBENAME=ioncube_loaders_lin_x86-64
	ZENDNAME_PHP53=ZendGuardLoader-php-5.3-linux-glibc23-x86_64
	ZENDNAME_PHP54=ZendGuardLoader-70429-PHP-5.4-linux-glibc23-x86_64
	ZENDNAME_PHP55=zend-loader-php5.5-linux-x86_64
	ZENDNAME_PHP56=zend-loader-php5.6-linux-x86_64
fi

ZENDFILE_GUARD53=${ZENDNAME_PHP53}.tar.gz
ZENDFILE_GUARD54=${ZENDNAME_PHP54}.tar.gz
ZENDFILE_GUARD55=${ZENDNAME_PHP55}.tar.gz
ZENDFILE_GUARD56=${ZENDNAME_PHP56}.tar.gz
IONCUBEFILE=${IONCUBENAME}.tar.gz

WEBALIZER_VER=${versions_txt["webalizer"]}
WEBALIZER_DOWNLOADURL="${WEBPATH}/webalizer-${WEBALIZER_VER}-src.tgz"

####################################################

doCheckDownloadURLS() {
	set | grep -o '^[A-Z0-9_]*_DOWNLOADURL=' | tr -d = | while read -r var; do
		echo "${!var}"
	done
}

clean_tarball() {
	#clean_tarball name current_version extension
	if [ "$1" = "" ] || [ "$2" = "" ] || [ "$3" = "" ]; then
		echo "Skipping $1 tarball, needs more arguments in doclean_old_tarballs()."
		return
	fi
	for i in `ls ${WORKDIR} | grep "^${1}[-_][v0-9]" | grep -v "$2" | grep "$3$"`; do
		rm -f ${WORKDIR}/$i
		if [ "${CLEAN_OPT}" = "no" ]; then
			echo "Removing ${WORKDIR}/$i..."
		fi
	done
}

doclean_old_tarballs() {
	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		clean_tarball openlitespeed ${OPENLITESPEED_VER} tar.gz
	fi
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		clean_tarball nginx ${NGINX_VER} tar.gz
		clean_tarball mod_aclr2 ${MOD_ACLR2_VER} tar.gz
	fi
	clean_tarball lego ${LEGO_VER} tar.gz
	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ "${HAVE_FCGID}" = "yes" ]; then
			clean_tarball mod_fcgid ${MOD_FCGID_VER} tar.gz
		fi
		if [ "${HTSCANNER_OPT}" = "yes" ]; then
			clean_tarball mod_htscanner2 ${HTSCANNER_VER} tgz
		fi
	fi
	clean_tarball redis ${REDIS_VER} tar.gz
	clean_tarball imapsync ${IMAPSYNC_VER} tar.gz
	if [ "${MODSECURITY_OPT}" = "yes" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ]; then
			clean_tarball ${MODSECURITY_FILENAME} ${MODSECURITY_VER} tar.gz
		else
			clean_tarball ${LIBMODSECURITY_FILENAME} ${LIBMODSECURITY_VER} tar.gz
		fi
		clean_tarball owasp-modsecurity-crs ${OWASP_RULES_VER} tar.gz
		clean_tarball ${MODSECURITY_NGINX_CONNECTOR_FILENAME} ${MODSECURITY_NGINX_CONNECTOR_VER} tar.gz
		clean_tarball ${MODSECURITY_APACHE_CONNECTOR_FILENAME} ${MODSECURITY_APACHE_CONNECTOR_VER} tar.gz
		if [ "${MODSECURITY_RULESET_OPT}" = "comodo" ]; then
			if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
				clean_tarball cwaf_rules_ls ${CWAF_RULES_VER} tgz
			elif [ "${WEBSERVER_OPT}" = "apache" ]; then
				clean_tarball cwaf_rules ${CWAF_RULES_VER} tgz
			else
				clean_tarball cwaf_rules_nginx_3 ${CWAF_RULES_VER} tgz
			fi
		fi
	fi
	if [ "${SPAMD_OPT}" = "spamassassin" ]; then
		clean_tarball Mail-SpamAssassin ${SPAMASSASSIN_VER} tar.gz
	fi

	if [ "${IMAGICK_OPT}" = "yes" ]; then
		clean_tarball imagick ${IMAGICK_VER} tgz
		clean_tarball ImageMagick ${IMAGEMAGICK_VER} tar.gz
	fi

	if [ "${PHP_SNUFFLEUPAGUS_OPT}" = "yes" ]; then
		clean_tarball snuffleupagus ${SNUFFLEUPAGUS_VER} tar.gz
	fi

	if [ "${PHP_REDIS_OPT}" = "yes" ]; then
		clean_tarball redis ${PHPREDIS_VER} tgz
	fi

	if [ "${PHP_IMAP_OPT}" = "yes" ]; then
		clean_tarball imap ${IMAP_VER} tgz
	fi

	if [ "${EASY_SPAM_FIGHTER_OPT}" = "yes" ]; then
		clean_tarball exim.easy_spam_fighter ${EASY_SPAM_FIGHTER_VER} tar.gz
	fi
	if [ "${BLOCKCRACKING_OPT}" = "yes" ]; then
		clean_tarball exim.blockcracking ${BLOCKCRACKING_VER} tar.gz
	fi
	if [ "${PIGEONHOLE_OPT}" = "yes" ]; then
		clean_tarball pigeohole${DOVECOT_SHORTREL} ${PIGEONHOLE_VER} tar.gz
	fi
	if [ "${WEBALIZER_OPT}" = "yes" ]; then
		clean_tarball webalizer ${WEBALIZER_VER}-src tgz
	fi
	if [ "${FTPD_OPT}" = "proftpd" ]; then
		clean_tarball proftpd ${PROFTPD_VER} tar.gz
	else
		clean_tarball pure-ftpd ${PUREFTPD_VER} tar.gz
	fi
	if [ "${EXIM_OPT}" = "yes" ]; then
		clean_tarball exim ${EXIM_VER} tar.gz
	fi
	clean_tarball dovecot ${DOVECOT_VER} tar.gz
	clean_tarball fts-xapian ${FTS_XAPIAN_VER} tar.gz
	clean_tarball xapian-core ${XAPIAN_CORE_VER} tar.xz
	if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
		clean_tarball roundcubemail ${ROUNDCUBE_VER} tar.gz
	fi
	if [ "${SQUIRRELMAIL_OPT}" = "yes" ]; then
		clean_tarball squirrelmail ${SQUIRRELMAIL_VER} tar.gz
	fi
	if [ "${AWSTATS_OPT}" = "yes" ]; then
		clean_tarball awstats ${AWSTATS_VER} tar.gz
	fi
	if [ "${UNIT_OPT}" = "yes" ]; then
		clean_tarball unit ${UNIT_VER} tar.gz
	fi
	if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
		clean_tarball phpMyAdmin ${PHPMYADMIN_VER} tar.gz
	fi

	if [ "${SUHOSIN_OPT}" = "yes" ]; then
		clean_tarball suhosin ${SUHOSIN_VER} tgz
	fi
	if [ "${OPCACHE_OPT}" = "yes" ]; then
		clean_tarball zendopcache ${OPCACHE_VER} tgz
	fi

	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		clean_tarball mod_hostinglimits ${MOD_HOSTINGLIMITS_VER} tar.gz
		clean_tarball mod_proctitle ${MOD_PROCTITLE_VER} tar.gz
	fi

	#PHP bit needs to be different
	for i in `ls ${WORKDIR} | grep '^php-' | grep -v "${PHP53_VER}" | grep -v "${PHP54_VER}" | grep -v "${PHP55_VER}" | grep -v "${PHP56_VER}" | grep -v "${PHP70_VER}" | grep -v "${PHP71_VER}" | grep -v "${PHP72_VER}" | grep -v "${PHP73_VER}" | grep -v "${PHP74_VER}" | grep -v "${PHP80_VER}" | grep -v "${PHP81_VER}" | grep tar.gz`; do
		rm -f ${WORKDIR}/$i
		if [ "${CLEAN_OPT}" = "no" ]; then
			echo "Removing ${WORKDIR}/$i..."
		fi
	done

	#Clean MySQL/MariaDB tarballs
	if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
		for i in `ls /usr/local/ | grep ^mysql- | grep 'tar.gz$' | grep -v "^mysql-${MYSQL_VER}"`; do
			rm -f /usr/local/$i
			if [ "${CLEAN_OPT}" = "no" ]; then
				echo "Removing /usr/local/$i..."
			fi
		done
	fi
	if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
		for i in `ls /usr/local/ | grep ^mariadb- | grep 'tar.gz$' | grep -v "^mariadb-${MARIADB_VER}"`; do
			rm -f /usr/local/$i
			if [ "${CLEAN_OPT}" = "no" ]; then
				echo "Removing /usr/local/$i..."
			fi
		done
	fi
}

####################################################

doclean_old_webapps() {
	if [ "${CLEAN_OLD_WEBAPPS_OPT}" != "yes" ]; then
		do_exit 1 "You cannot clean webapps, because you do not have it set in options.conf file."
	fi

	#Clean phpMyAdmin
	if [ "${PHPMYADMIN_OPT}" = "yes" ] && [ -e /var/www/html/phpMyAdmin ]; then
		PHPMYADMIN_CUR=`ls -ld /var/www/html/phpMyAdmin | cut -d\> -f2 | cut -d- -f2,3,4`
		for i in `ls /var/www/html/ | grep phpMyAdmin- | grep -v "${PHPMYADMIN_CUR}"`; do
			rm -rf /var/www/html/$i
			if [ "${CLEAN_OPT}" = "no" ]; then
				echo "Removing /var/www/html/$i..."
			fi
		done
	fi

	#Clean SquirrelMail
	if [ "${SQUIRRELMAIL_OPT}" = "yes" ] && [ -e /var/www/html/squirrelmail ]; then
		SQUIRRELMAIL_CUR=`ls -ld /var/www/html/squirrelmail | cut -d\> -f2 | cut -d- -f2,3`
		for i in `ls /var/www/html/ | grep squirrelmail- | grep -v -e "${SQUIRRELMAIL_CUR}\$"`; do
			rm -rf /var/www/html/$i
			if [ "${CLEAN_OPT}" = "no" ]; then
				echo "Removing /var/www/html/$i..."
			fi
		done
	fi

	#Clean RoundCube
	if [ "${ROUNDCUBE_OPT}" = "yes" ] && [ -e /var/www/html/roundcube ]; then
		#ROUNDCUBE_CUR=`ls -ld /var/www/html/roundcube | cut -d\> -f2 | cut -d- -f2`
		ROUNDCUBE_CUR=`roundcube_version`
		for i in `ls /var/www/html/ | grep roundcubemail- | grep -v "${ROUNDCUBE_CUR}"`; do
			rm -rf /var/www/html/$i
			if [ "${CLEAN_OPT}" = "no" ]; then
				echo "Removing /var/www/html/$i..."
			fi
		done
	fi

	#Clean AWstats
	if [ "${AWSTATS_OPT}" = "yes" ] && [ -e /usr/local/awstats ]; then
		AWSTATS_CUR=`ls -ld /usr/local/awstats | cut -d\> -f2 | cut -d- -f2`
		for i in `ls /usr/local/ | grep awstats- | grep -v "${AWSTATS_CUR}"`; do
			rm -rf /usr/local/$i
			if [ "${CLEAN_OPT}" = "no" ]; then
				echo "Removing /usr/local/$i..."
			fi
		done
	fi
}

####################################################

legacy_doClean() {
	rm -rf "${WORKDIR}/temp"
	cd ${WORKDIR}
	rm -rf ${MODSECURITY_FILENAME}-${MODSECURITY_VER}
	rm -rf ${LIBMODSECURITY_FILENAME}-v${LIBMODSECURITY_VER}
	rm -rf ${MODSECURITY_APACHE_CONNECTOR_FILENAME}-${MODSECURITY_APACHE_CONNECTOR_VER}
	rm -rf ${MODSECURITY_NGINX_CONNECTOR_FILENAME}-${MODSECURITY_NGINX_CONNECTOR_VER}
	rm -rf mod_aclr2-${MOD_ACLR2_VER}
	rm -rf htscanner-${HTSCANNER_VER}
	rm -rf mod_fcgid-${MOD_FCGID_VER}
	rm -rf php-${PHP53_VER}
	rm -rf php-${PHP54_VER}
	rm -rf php-${PHP55_VER}
	rm -rf php-${PHP56_VER}
	rm -rf php-${PHP70_VER}
	rm -rf php-${PHP71_VER}
	rm -rf php-${PHP72_VER}
	rm -rf php-${PHP73_VER}
	rm -rf php-${PHP74_VER}
	rm -rf php-${PHP80_VER}
	rm -rf php-${PHP81_VER}
	rm -rf php-${PHP82_VER}
	rm -rf redis-${REDIS_VER}
	rm -rf imapsync-imapsync-${IMAPSYNC_VER}
	if [ "${UNIT_OPT}" = "yes" ]; then
		rm -rf unit-${UNIT_VER}
	fi
	rm -rf xapian-core-${XAPIAN_CORE_VER}
	if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		rm -rf lsws-${LITESPEED_VER}
	fi
	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		rm -rf openlitespeed-${OPENLITESPEED_VER}
	fi
	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		rm -rf mod_proctitle-${MOD_PROCTITLE_VER}
	fi
	if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
		rm -rf mysql-${MYSQL_VER}
	fi
	if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
		rm -rf mariadb-${MARIADB_VER}
	fi
	if [ "${PHP_IMAGICK_OPT}" = "yes" ]; then
		rm -rf imagick-${IMAGICK_VER}
		rm -rf ImageMagick-${IMAGEMAGICK_VER}
	fi
	if [ "${PHP_IMAP_OPT}" = "yes" ]; then
		rm -rf imap-${IMAP_VER}
	fi
	rm -rf nginx-${NGINX_VER}
	rm -rf easy_spam_fighter
	rm -rf ${ZENDNAME_PHP53}
	rm -rf ${ZENDNAME_PHP54}
	rm -rf ${ZENDNAME_PHP55}
	rm -rf ${ZENDNAME_PHP56}
	rm -rf webalizer-${WEBALIZER_VER}
	rm -rf proftpd-${PROFTPD_VER}
	rm -rf pure-ftpd-${PUREFTPD_VER}
	rm -rf httpd-${APACHE2_VER}
	rm -rf exim-${EXIM_VER}
	rm -rf dovecot-${DOVECOT_VER}
	rm -rf dovecot-ce-${DOVECOT_VER}
	rm -rf suhosin-${SUHOSIN_VER}
	rm -rf zendopcache-${OPCACHE_VER}
	rm -rf dovecot-${DOVECOT_REL}-pigeonhole-${PIGEONHOLE_VER}
	rm -rf Mail-SpamAssassin-${SPAMASSASSIN_VER}

	rm -rf ${ZENDNAME_PHP53}
	rm -rf ${ZENDNAME_PHP54}

	#Clean MySQL/MariaDB
	if [ -h /usr/local/mysql ] && [ "${MYSQL_INST_OPT}" != "no" ]; then
		MYSQL_CUR=`ls -ld /usr/local/mysql | cut -d\> -f2 | cut -d' ' -f2`
		for i in `ls /usr/local/ | grep '^mysql-\|^mariadb-' | grep -v "${MYSQL_CUR}"`; do
			if [ -h /usr/local/${i}/data ]; then
				rm -rf /usr/local/$i
				if [ "${CLEAN_OPT}" = "no" ]; then
					echo "Removing /usr/local/$i..."
				fi
			fi
		done
	fi

	if [ "${CLEAN_OLD_TARBALLS_OPT}" = "yes" ]; then
		doclean_old_tarballs
	fi

	if [ "${CLEAN_OLD_WEBAPPS_OPT}" = "yes" ]; then
		doclean_old_webapps
	fi

	if [ "${CLEAN_OPT}" = "no" ]; then
		echo "All clean!"
	fi
}

HELP_SECTIONS="BUILD_COMP BUILD_PHP_EXT BUILD_COMP_CONF BUILD_COMP_WEBAPPS BUILD_CB BUILD_OLD BUILD_ALL BUILD_PHP_EXTENSIONS BUILD_EXPERIENCED"

BUILD_PHP_EXT_SET="php_gmp php_igbinary php_ioncube php_imagick php_imap php_ldap php_opcache php_phalcon php_psr php_redis php_readline php_snuffleupagus php_suhosin php_xmlrpc php_zend"
BUILD_PHP_EXT_DESC="Install/update PHP extensions"
BUILD_PHP_EXT_REQADD=""

BUILD_COMP_SET="apache awstats csf clamav composer dovecot exim imagemagick imapsync jailshell lego libmodsecurity litespeed mod_lsapi mod_proctitle mod_aclr2 mod_htscanner2 mod_fcgid modsecurity modsecurity_rules mysql netdata nginx nginx_apache openlitespeed pigeonhole php proftpd pureftpd redis rspamd spamassassin unit webalizer wp"
BUILD_COMP_DESC="Install/update server components"
BUILD_COMP_REQADD=""

BUILD_COMP_CONF_SET="exim_conf dovecot_conf blockcracking easy_spam_fighter php_ini rewrite_confs secure_php spamassassin_cron litespeed_license litespeed_license_migrate"
BUILD_COMP_CONF_DESC="Components configuration options"
BUILD_COMP_CONF_REQADD=""

BUILD_COMP_WEBAPPS_SET="phpmyadmin roundcube squirrelmail"
BUILD_COMP_WEBAPPS_DESC="Install/update web applications"
BUILD_COMP_WEBAPPS_REQADD=""

BUILD_CB_SET="create_options cron opt_help options_nobold list_removals remove_items set update_da update_versions update_webapps used_configs versions"
BUILD_CB_DESC="CustomBuild related options/functions"
BUILD_CB_SET_REQADD="opt_help set"
SET_ADDIT="option_name value"
OPT_HELP_ADDIT="(full)"

BUILD_OLD_SET="clean clean_old_webapps"
BUILD_OLD_DESC="Remove old build data"
BUILD_OLD_REQUADD=""

BUILD_ALL_SET="all"
BUILD_ALL_DESC="Build everything what is set in the options.conf file"
BUILD_ALL_REQADD=""

BUILD_PHP_EXTENSIONS_SET="php_extensions"
BUILD_PHP_EXTENSIONS_DESC="Build all PHP extensions set set in the php_extensions.conf file"
BUILD_PHP_EXTENSIONS_REQADD=""

BUILD_EXPERIENCED_SET="php_expert php_htscanner2 set_service"
BUILD_EXPERIENCED_DESC="Recommended for experienced users only (!)"
BUILD_EXPERIENCED_REQADD="php_expert php_htscanner2 set_service"
PHP_EXPERT_ADDIT="php_release php_mode"
PHP_HTSCANNER2_ADDIT="php_release"
SET_SERVICE_ADDIT="service ON|OFF|delete"

###################################################

generateHelp() {
	for section in ${HELP_SECTIONS}; do
		DESC=${section}_DESC
		echo " +-----------------------------------------------------------+"
		printf " | %-55s %-2s|\n" "${!DESC}:"

		BUILDSET="${section}_SET"
		BUILD_ADD_TO_OUT="${section}_REQADD"
		for setting in ${!BUILDSET}; do
			ADDIT=""
			for i in ${!BUILD_ADD_TO_OUT}; do
				ADDIT_VAR=`echo "${i}_ADDIT" | tr "[a-z]" "[A-Z]"`
				if [ "$i" = "${setting}" ]; then
					ADDIT="${!ADDIT_VAR}"
				fi
			done
			printf " | %-55s %-2s|\n" "   $0 ${setting} ${ADDIT}"
		done
	done
}

command_dump_build_software() {
	local mysql_ver_str
	if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
		mysql_ver_str="${MYSQL_VER}"
	else
		mysql_ver_str="${MARIADB_VER}"
	fi

	local php_ver_str
	if [ "${PHP2_RELEASE_OPT}" = "no" ] && [ "${PHP3_RELEASE_OPT}" = "no" ] && [ "${PHP4_RELEASE_OPT}" = "no" ]; then
		php_ver_str="${PHP1_RELEASE_OPT} (${PHP1_MODE_OPT})"
	elif [ "${PHP3_RELEASE_OPT}" = "no" ] && [ "${PHP4_RELEASE_OPT}" = "no" ]; then
		php_ver_str="${PHP1_RELEASE_OPT} (${PHP1_MODE_OPT}) and ${PHP2_RELEASE_OPT} (${PHP2_MODE_OPT})"
	elif [ "${PHP4_RELEASE_OPT}" = "no" ]; then
		php_ver_str="${PHP1_RELEASE_OPT} (${PHP1_MODE_OPT}), ${PHP2_RELEASE_OPT} (${PHP2_MODE_OPT}) and ${PHP3_RELEASE_OPT} (${PHP3_MODE_OPT})"
	else
		php_ver_str="${PHP1_RELEASE_OPT} (${PHP1_MODE_OPT}), ${PHP2_RELEASE_OPT} (${PHP2_MODE_OPT}), ${PHP3_RELEASE_OPT} (${PHP3_MODE_OPT}) and ${PHP4_RELEASE_OPT} (${PHP4_MODE_OPT})"
	fi

	declare -A main_actions=(
		           [apache]="Apache           |Install/update Apache WEB server                        |${APACHE2_VER}"
		          [awstats]="awstats          |Install/update AWstats                                  |${AWSTATS_VER}"
		              [csf]="CSF              |Install/update ConfigServer Security & Firewall (csf)   |"
		           [clamav]="ClamAV           |Install/update ClamAV antivirus engine                  |"
		         [composer]="composer         |Install/update composer                                 |${COMPOSER_VER}"
		          [dovecot]="Dovecot          |Install/update Dovecot IMAP/POP3 server                 |${DOVECOT_VER}"
		             [exim]="Exim             |Install/update Exim Mail Transfer Agent                 |${EXIM_VER}"
		      [imagemagick]="ImageMagick      |Install/update ImageMagick                              |${IMAGEMAGICK_VER}"
		         [imapsync]="imapsync         |Install/update imapsync tool for mailbox synchronization|${IMAPSYNC_VER}"
		        [jailshell]="jailshell        |Install/update jailshell                                |"
		             [lego]="lego             |Install/update lego Let's Encrypt client                |${LEGO_VER}"
		        [litespeed]="litespeed        |Install/update LiteSpeed WEB server                     |${LITESPEED_VER}"
		        [mod_lsapi]="mod_lsapi        |Install/update mod_lsapi                                |${MOD_LSAPI_VER}"
		[mod_hostinglimits]="mod_hostinglimits|Install/update mod_hostinglimits                        |${MOD_HOSTINGLIMITS_VER}"
		    [mod_proctitle]="mod_proctitle    |Install/update mod_proctitle                            |${MOD_PROCTITLE_VER}"
		        [mod_aclr2]="mod_aclr2        |Install/update mod_aclr2                                |${MOD_ACLR2_VER}"
		   [mod_htscanner2]="mod_htscanner2   |Install/update mod_htscanner2                           |${HTSCANNER_VER}"
		        [mod_fcgid]="mod_fcgid        |Install/update mod_fcgid                                |${MOD_FCGID_VER}"
		      [modsecurity]="ModSecurity      |Install/update ModSecurity                              |${MODSECURITY_VER}"
		   [libmodsecurity]="LibModSecurity   |Install/update LibModSecurity (ModSecurity 3.0)         |${LIBMODSECURITY_VER}"
		[modsecurity_rules]="ModSecurity Rules|Install/update ModSecurity rule set                     |"
		            [mysql]="${MYSQLNAME}     |Install/update ${MYSQLNAME}                             |${mysql_ver_str}"
		          [netdata]="netdata          |Install/update netdata metrics for your server          |"
		            [nginx]="nginx            |Install/update nginx WEB server                         |${NGINX_VER}"
		     [nginx_apache]="nginx+Apache     |Install/update nginx and Apache (nginx as a reverse proxy for Apache)|${NGINX_VER}/${APACHE2_VER}"
		    [openlitespeed]="openlitespeed    |Install/update OpenLiteSpeed WEB server                 |${OPENLITESPEED_VER}"
		       [pigeonhole]="Pigeonhole       |Install/update Pigeonhole used in Dovecot to provide Sieve email filtering and ManageSieve protocol|${PIGEONHOLE_VER}"
		              [php]="PHP              |Install/update PHP                                      |${php_ver_str}"
		          [proftpd]="ProFTPd          |Install/update ProFTPD FTP server                       |${PROFTPD_VER}"
		         [pureftpd]="Pure-FTPd        |Install/update Pure-FTPd FTP server                     |${PUREFTPD_VER}"
		            [redis]="redis            |Install/update redis                                    |${REDIS_VER}"
		           [rspamd]="Rspamd           |Install/update Rspamd                                   |"
		     [spamassassin]="SpamAssassin     |Install/update SpamAssassin                             |${SPAMASSASSIN_VER}"
		             [unit]="Nginx Unit       |Install/update Nginx Unit dynamic application server    |${UNIT_VER}"
		        [webalizer]="Webalizer        |Install/update Webalizer                                |${WEBALIZER_VER}"
		               [wp]="wp-cli           |Install/update command-line interface for WordPress     |${WP_VER}"
	)
	declare -A main_skip=()
	[ "${WEBSERVER_OPT}" = "apache" ] && main_skip[nginx]=yes
	[ "${WEBSERVER_OPT}" = "apache" ] && main_skip[litespeed]=yes
	[ "${WEBSERVER_OPT}" = "apache" ] && main_skip[nginx_apache]=yes
	[ "${WEBSERVER_OPT}" = "apache" ] && main_skip[mod_aclr2]=yes
	[ "${WEBSERVER_OPT}" = "apache" ] && main_skip[openlitespeed]=yes
	[ "${WEBSERVER_OPT}" = "nginx" ] && main_skip[apache]=yes
	[ "${WEBSERVER_OPT}" = "nginx" ] && main_skip[litespeed]=yes
	[ "${WEBSERVER_OPT}" = "nginx" ] && main_skip[nginx_apache]=yes
	[ "${WEBSERVER_OPT}" = "nginx" ] && main_skip[mod_aclr2]=yes
	[ "${WEBSERVER_OPT}" = "nginx" ] && main_skip[openlitespeed]=yes
	[ "${WEBSERVER_OPT}" = "litespeed" ] && main_skip[apache]=yes
	[ "${WEBSERVER_OPT}" = "litespeed" ] && main_skip[nginx]=yes
	[ "${WEBSERVER_OPT}" = "litespeed" ] && main_skip[nginx_apache]=yes
	[ "${WEBSERVER_OPT}" = "litespeed" ] && main_skip[mod_aclr2]=yes
	[ "${WEBSERVER_OPT}" = "litespeed" ] && main_skip[openlitespeed]=yes
	[ "${WEBSERVER_OPT}" = "openlitespeed" ] && main_skip[apache]=yes
	[ "${WEBSERVER_OPT}" = "openlitespeed" ] && main_skip[litespeed]=yes
	[ "${WEBSERVER_OPT}" = "openlitespeed" ] && main_skip[nginx]=yes
	[ "${WEBSERVER_OPT}" = "openlitespeed" ] && main_skip[nginx_apache]=yes
	[ "${WEBSERVER_OPT}" = "openlitespeed" ] && main_skip[mod_aclr2]=yes
	[ "${CLAMAV_OPT}" = "no" ] && main_skip[clamav]=yes
	[ "${AWSTATS_OPT}" = "no" ] && main_skip[awstats]=yes
	[ "${WEBALIZER_OPT}" = "no" ] && main_skip[webalizer]=yes
	[ "${CSF_OPT}" = "no" ] && main_skip[csf]=yes
	[ "${FTPD_OPT}" = "no" ] && main_skip[proftpd]=yes
	[ "${FTPD_OPT}" = "no" ] && main_skip[pureftpd]=yes
	[ "${FTPD_OPT}" = "pureftpd" ] && main_skip[proftpd]=yes
	[ "${FTPD_OPT}" = "proftpd" ] && main_skip[pureftpd]=yes
	[ "${MODSECURITY_OPT}" = "no" ] && main_skip[libmodsecurity]=yes
	[ "${MODSECURITY_OPT}" = "no" ] && main_skip[modsecurity]=yes
	[ "${MODSECURITY_OPT}" = "no" ] && main_skip[modsecurity_rules]=yes
	if [ "${CLOUDLINUX_OPT}" = "no" ] || [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		main_skip[mod_hostinglimits]=yes
		main_skip[mod_lsapi]=yes
		main_skip[mod_proctitle]=yes
	fi
	[ "${HTSCANNER_OPT}" = "no" ] && main_skip[mod_htscanner2]=yes
	[ "${HAVE_FCGID}" = "no" ] && main_skip[mod_fcgid]=yes
	[ "${PIGEONHOLE_OPT}" = "no" ] && main_skip[pigeonhole]=yes
	[ "${DOVECOT_OPT}" = "no" ] && main_skip[dovecot]=yes
	[ "${MYSQL_INST_OPT}" = "no" ] && main_skip[mysql]=yes
	[ "${SPAMD_OPT}" = "no" ] && main_skip[spamassassin]=yes
	[ "${SPAMD_OPT}" = "no" ] && main_skip[rspamd]=yes
	[ "${SPAMD_OPT}" = "rspamd" ] && main_skip[spamassassin]=yes
	[ "${SPAMD_OPT}" = "spamsassasin" ] && main_skip[rspamd]=yes
	[ "${EXIM_OPT}" = "no" ] && main_skip[exim]=yes

	declare -A php_ext_actions=(
		          [gmp]="gmp              |Install/update GNU Multiple Precision extension for PHP|"
		          [bz2]="bz2              |Install/update Bzip2 extension for PHP                 |"
		     [igbinary]="igbinary         |Install/update igbinary extension for PHP              |${IGBINARY_VER}"
		      [ioncube]="ionCube          |Install/update ionCube                                 |${IONCUBE_VER}"
		      [imagick]="imagick          |Install/update ImageMagick extension for PHP           |${IMAGICK_VER}"
		         [imap]="imap             |Install/update imap extension for PHP                  |${IMAP_VER}"
		         [ldap]="ldap             |Install/update ldap extension for PHP                  |"
		      [opcache]="opcache          |Install/update opcache                                 |"
		      [phalcon]="phalcon          |Install/update Phalcon extension for PHP               |${versions_txt[phalcon]}/${versions_txt[phalcon5]}"
		          [psr]="psr              |Install/update psr extension for PHP                   |${PSR_VER}"
		        [redis]="redis            |Install/update redis extension for PHP                 |${PHPREDIS_VER}"
		     [readline]="readline         |Install/update readline extension for PHP              |"
		[snuffleupagus]="snuffleupagus    |Install/update snuffleupagus extension for PHP         |${SNUFFLEUPAGUS_VER}"
		      [suhosin]="suhosin          |Install/update suhosin                                 |${SUHOSIN_VER}"
		       [xmlrpc]="xmlrpc           |Install/update xmlrpc extension for PHP                |"
		         [zend]="Zend Guard loader|Install/update Zend Guard loader                       |"
	)
	declare -A php_ext_skip=()
	[ "${PHP_IGBINARY_OPT}" = "no" ] && php_ext_skip[igbinary]=yes
	[ "${IMAGICK_OPT}" = "no" ] && php_ext_skip[imagick]=yes
	[ "${ZEND_OPT}" = "no" ] && php_ext_skip[zend]=yes
	[ "${IONCUBE_OPT}" = "no" ] && php_ext_skip[ioncube]=yes
	[ "${SUHOSIN_OPT}" = "no" ] && php_ext_skip[suhosin]=yes
	[ "${PHP_SNUFFLEUPAGUS_OPT}" = "no" ] && php_ext_skip[snuffleupagus]=yes
	[ "${PHP_PHALCON_OPT}" = "no" ] && php_ext_skip[phalcon]=yes
	[ "${PHP_PHALCON_OPT}" = "no" ] && php_ext_skip[psr]=yes
	[ "${PHP_IMAP_OPT}" = "no" ] && php_ext_skip[imap]=yes

	declare -A webapp_actions=(
		  [phpmyadmin]="phpMyAdmin  |Install/update phpMyAdmin WEB MySQL administration tool|${PHPMYADMIN_VER}"
		   [roundcube]="RoundCube   |Install/update RoundCube webmail                       |${ROUNDCUBE_VER}"
		[squirrelmail]="SquirrelMail|Install/update SquirrelMail webmail                    |${SQUIRRELMAIL_VER}"
	)
	declare -A webapp_skip=()
	[ "${PHPMYADMIN_OPT}" = "no" ] && webapp_skip[phpmyadmin]=yes
	[ "${ROUNDCUBE_OPT}" = "no" ] && webapp_skip[roundcube]=yes
	[ "${SQUIRRELMAIL_OPT}" = "no" ] && webapp_skip[squirrelmail]=yes

	local cmd available name desc ver
	for cmd in "${!main_actions[@]}"; do
		IFS='|' read -r name desc ver _ <<< "${main_actions[$cmd]}"
		name=${name%"${name##*[! ]}"}
		desc=${desc%"${desc##*[! ]}"}
		available=Y
		[ -n "${main_skip[${cmd}]}" ] && available=N
		printf "main|%s|%s|%s|%s|%s\n" "${available}" "${cmd}" "${name}" "${desc}" "${ver}"
	done
	for cmd in "${!php_ext_actions[@]}"; do
		IFS='|' read -r name desc ver _ <<< "${php_ext_actions[$cmd]}"
		name=${name%"${name##*[! ]}"}
		desc=${desc%"${desc##*[! ]}"}
		available=Y
		[ -n "${php_ext_skip[${cmd}]}" ] && available=N
		printf "php_extension|%s|%s|%s|%s|%s\n" "${available}" "php_${cmd}" "${name}" "${desc}" "${ver}"
	done
	for cmd in "${!webapp_actions[@]}"; do
		IFS='|' read -r name desc ver _ <<< "${webapp_actions[$cmd]}"
		name=${name%"${name##*[! ]}"}
		desc=${desc%"${desc##*[! ]}"}
		available=Y
		[ -n "${webapp_skip[$cmd]}" ] && available=N
		printf "webapp|%s|%s|%s|%s|%s\n" "${available}" "${cmd}" "${name}" "${desc}" "${ver}"
	done
}

command_dump_actions() {
	declare -A actions=(
		           [update_webapps]="Update WEB applications               |Updates WEB applications if updates are available (only phpMyAdmin, RoundCube and SquirrelMail)."
		                [exim_conf]="Update Exim configuration files       |Updates Exim configuration files (exim.conf and exim.pl). WARNING: Any customizations done will be lost."
		             [dovecot_conf]="Update Dovecot configuration files    |Updates Dovecot configuration files."
		            [blockcracking]="Enable BlockCracking                  |Enables BlockCracking for outgoing SPAM mitigation in Exim configuration file (exim.conf). Requires Exim configuration version 4.3 or higher. More information: https://forum.directadmin.com/showthread.php?t=50059."
		        [easy_spam_fighter]="Enable Easy Spam Fighter              |Enables Easy Spam Fighter for incoming SPAM mitigation in Exim configuration file (exim.conf). Requires Exim configuration version 4.3 or higher. More information: https://forum.directadmin.com/showthread.php?t=50059."
		                  [php_ini]="Update PHP configuration files        |Updates php.ini configuration files used by PHP. WARNING: Any customizations done will be lost."
		            [rewrite_confs]="Rewrite WEB server configuration files|Rewrites Apache/Nginx WEB server configuration files (useful when configuration got corrupted or needs to be updated). WARNING: customizations must be present in 'custom/' folder, otherwise they will be lost."
		               [secure_php]="Secure PHP                            |Disables dangerous PHP functions in php.ini file."
		        [spamassassin_cron]="Build SpamAssassin cron               |Install SpamAssassin cronjob for periodic rule updates."
		        [litespeed_license]="Update LiceSpeed License              |Updates LiteSpeed license using the serial number provided."
		[litespeed_license_migrate]="Migrate LiteSpeed License             |Releases LiteSpeed license (equivalent of 'lshttpd -m')."
	)

	[ "${PHP_INI_OPT}" = "no" ] && unset 'actions[php_ini]'
	[ "${EXIMCONF_OPT}" = "no" ] && unset 'actions[eximconf]'
	[ "${WEBSERVER_OPT}" != "litespeed" ] && unset 'actions[litespeed_license]'
	[ "${WEBSERVER_OPT}" != "litespeed" ] && unset 'actions[litespeed_license_migrate]'
	[ "${LITESPEED_SERIALNO_OPT}" = "trial" ] && unset 'actions[litespeed_license_migrate]'
	[ "${DOVECOT_CONF_OPT}" = "no" ] && unset 'actions[dovecot_conf]'
	[ "${BLOCKCRACKING_OPT}" = "no" ] && unset 'actions[blockcracking]'
	[ "${EXIMCONF_OPT}" = "no" ] && unset 'actions[easy_spam_fighter]'

	local cmd name desc
	for cmd in "${!actions[@]}"; do
		IFS='|' read -r name desc _ <<< "${actions[$cmd]}"
		name=${name%"${name##*[! ]}"}
		printf "%s|%s|%s\n" "${cmd}" "${name}" "${desc}"
	done
}

###################################################

showHelp() {
	printf " +%-55s+\n" "-----------------------------------------------------------"
	printf " | %-55s %-2s|\n" "DirectAdmin WebServices Installer"
	printf " | %-55s %-2s|\n" "Written by Martynas Bendorius and DirectAdmin"
	printf " | %-55s %-2s|\n" "Version: $(showVersion)"
	printf " +%-55s+\n" "-----------------------------------------------------------"
	printf " | %-55s %-2s|\n" "To build everything run:"
	printf " | %-55s %-2s|\n" "   $0 all"
	printf " | %-55s %-2s|\n" ""
	printf " | %-55s %-2s|\n" " ${boldon}NOTE${boldoff}: Command all will compile everything as it is set"
	printf " | %-55s %-2s|\n" "   in the options.conf file, please take a look at"
	printf " | %-55s %-2s|\n" "   \"$0 options\"!"
	generateHelp
	printf " +%-55s+\n" "-----------------------------------------------------------"
	printf " | %-55s %-2s|\n" "You can pass a 2nd argument to automate the input:"
	printf " | %-55s %-2s|\n" "   $0 <option> d : do the default action"
	printf " | %-55s %-2s|\n" "   $0 <option> y : answer yes to all questions"
	printf " | %-55s %-2s|\n" "   $0 <option> n : answer no to all questions"
	printf " +%-55s+\n" "-----------------------------------------------------------"
}

checkFile() {
	if [ ! -s $1 ]; then
		echo "*** Cannot find $1. Aborting ***"
		do_exit 0
	else
		echo "Found $1"
	fi
}

####################################################

get_webmail_link() {
	WL=roundcube
	if [ "$ROUNDCUBE_OPT" = "no" ]; then
		WL=squirrelmail
	fi
	if [ -s ${DACONF_FILE} ] && [ -s /usr/local/directadmin/directadmin ]; then
		WL=`/usr/local/directadmin/directadmin c | grep -m1 '^webmail_link' | cut -d= -f2`
	fi

	echo "${WL}"
}

doPasswdServerStatus() {
	if [ -e /var/www/html/passwd-server-status ]; then
		rm -f /var/www/html/passwd-server-status
	fi
	touch /var/www/passwd-server-status
	chown apache:apache /var/www/passwd-server-status
	chmod 640 /var/www/passwd-server-status
	if command -v htpasswd > /dev/null; then
		if grep -q da_admin /var/www/passwd-server-status; then
			sed -i '/da_admin/d' /var/www/passwd-server-status
		fi
		RANDOM_HTPASSWD_USER=`random_pass`
		RANDOM_HTPASSWD_PASS=`random_pass`
		htpasswd -b -c /var/www/passwd-server-status "${RANDOM_HTPASSWD_USER}" "${RANDOM_HTPASSWD_PASS}" >/dev/null 2>&1
		echo "#Authenticate using:" >> /etc/httpd/conf/extra/httpd-info.conf
		echo "#Username: ${RANDOM_HTPASSWD_USER}" >> /etc/httpd/conf/extra/httpd-info.conf
		echo "#Password: ${RANDOM_HTPASSWD_PASS}" >> /etc/httpd/conf/extra/httpd-info.conf
		chmod 640 /etc/httpd/conf/extra/httpd-info.conf
	fi
}

####################################################

doApacheHostConf() {
	HOSTCONF=${HTTPDCONF}/extra/httpd-hostname.conf
	if [ -e ${WORKDIR}/custom/ap2/conf/extra/httpd-hostname.conf ]; then
		cp -pf ${WORKDIR}/custom/ap2/conf/extra/httpd-hostname.conf ${HOSTCONF}
	else
		echo -n '' > ${HOSTCONF}

		if [ "${HAVE_FPM_CGI}" = "yes" ]; then
			echo 'SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1' >> ${HOSTCONF}
		fi

		echo '<Directory /var/www/html>' >> ${HOSTCONF}

		if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
			echo '<FilesMatch "\.(inc|php[0-9]*|phtml|phps)$">' >> ${HOSTCONF}
			echo "AddHandler \"proxy:unix:/usr/local/php${PHP1_SHORTRELEASE}/sockets/webapps.sock|fcgi://localhost\" .inc .php .php5 .php${PHP1_SHORTRELEASE} .phtml" >> ${HOSTCONF}
			echo '</FilesMatch>' >> ${HOSTCONF}
		fi

		echo '	Options +SymLinksIfOwnerMatch +IncludesNoExec -Indexes' >> ${HOSTCONF}
		echo '	AllowOverride AuthConfig FileInfo Indexes Limit Options=Includes,IncludesNOEXEC,Indexes,ExecCGI,MultiViews,SymLinksIfOwnerMatch,None' >> ${HOSTCONF}
		echo '	AllowMethods reset' >> ${HOSTCONF}
		echo '' >> ${HOSTCONF}
		echo '	Require all granted' >> ${HOSTCONF}
		echo '	<IfModule !mod_ruid2.c>' >> ${HOSTCONF}
		echo '		SuexecUserGroup webapps webapps' >> ${HOSTCONF}
		echo '	</IfModule>' >> ${HOSTCONF}
		echo '	<IfModule mod_lsapi.c>' >> ${HOSTCONF}
		echo '		lsapi_user_group webapps webapps' >> ${HOSTCONF}
		echo "		php_admin_value session.save_path ${APP_TMP}" >> ${HOSTCONF}
		echo "		php_admin_value upload_tmp_dir ${APP_TMP}" >> ${HOSTCONF}
		echo '	</IfModule>' >> ${HOSTCONF}

		ensure_webapps_tmp

		WEBAPPS_FCGID_DIR=/var/www/fcgid
		SUEXEC_PER_DIR="0"
		if [ -s /usr/sbin/suexec ]; then
			SUEXEC_PER_DIR="`/usr/sbin/suexec -V 2>&1 | grep -c 'AP_PER_DIR'`"
		fi
		if [ "${PHP1_MODE_OPT}" = "fastcgi" ]; then
			echo '	<IfModule mod_fcgid.c>' >> ${HOSTCONF}
			echo "		FcgidWrapper /usr/local/safe-bin/fcgid${PHP1_SHORTRELEASE}.sh .php" >> ${HOSTCONF}
			if [ "${SUEXEC_PER_DIR}" -gt 0 ]; then
				echo '	  SuexecUserGroup webapps webapps' >> ${HOSTCONF}
			fi
			echo '		<FilesMatch "\.(inc|php[0-9]*|phtml|phps)$">' >> ${HOSTCONF}
			echo '			Options +ExecCGI' >> ${HOSTCONF}
			echo '			AddHandler fcgid-script .php' >> ${HOSTCONF}
			echo '		</FilesMatch>' >> ${HOSTCONF}
			echo '	</IfModule>' >> ${HOSTCONF}
		fi

		echo '</Directory>' >> ${HOSTCONF}
		
		# Do not show authentication logs for public
		echo '<Directory /var/www/html/phpMyAdmin/log>' >> ${HOSTCONF}
		echo '	Require all denied' >> ${HOSTCONF}
		echo '</Directory>' >> ${HOSTCONF}
	fi
}

options() {
	if [ "${UNIT_OPT}" = "yes" ]; then
		echo "Nginx Unit: ${boldon}${UNIT_VER}${boldoff}"
	else
		echo "Nginx Unit: ${boldon}no${boldoff}"
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "Apache: ${boldon}${APACHE2_VER}${boldoff}"
	elif [ "${WEBSERVER_OPT}" = "nginx" ]; then
		echo "Nginx: ${boldon}${NGINX_VER}${boldoff}"
	fi
	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "Nginx (reverse proxy): ${boldon}${NGINX_VER}${boldoff}"
	fi

	if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		echo "Litespeed: ${boldon}${LITESPEED_VER}${boldoff}"
	fi

	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		echo "OpenLitespeed: ${boldon}${OPENLITESPEED_VER}${boldoff}"
	fi

	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			echo "mod_lsapi: ${boldon}${MOD_LSAPI_VER}${boldoff}"
			echo "mod_hostinglimits: ${boldon}${MOD_HOSTINGLIMITS_VER}${boldoff}"
			echo "mod_proctitle: ${boldon}${MOD_PROCTITLE_VER}${boldoff}"
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ]; then
		if [ "${MODSECURITY_OPT}" = "yes" ]; then
			echo "ModSecurity: ${boldon}${MODSECURITY_VER}${boldoff}"
			echo "ModSecurity Rule Set: ${boldon}${MODSECURITY_RULESET_OPT}${boldoff}"
		else
			echo "ModSecurity: ${boldon}no${boldoff}"
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "nginx_apache" ] || [ "${WEBSERVER_OPT}" = "nginx" ]; then
		if [ "${MODSECURITY_OPT}" = "yes" ]; then
			echo "LibModSecurity: ${boldon}${LIBMODSECURITY_VER}${boldoff}"
			echo "LibModSecurity Rule Set: ${boldon}${MODSECURITY_RULESET_OPT}${boldoff}"
		else
			echo "LibModSecurity: ${boldon}no${boldoff}"
		fi
	fi

	if [ "${PHP1_MODE_OPT}" != "lsphp" ] && [ "${HTSCANNER_OPT}" = "yes" ]; then
		echo "htscanner: ${boldon}${HTSCANNER_VER}${boldoff}"
	else
		echo "htscanner: ${boldon}no${boldoff}"
	fi

	if [ "${DOVECOT_OPT}" = "yes" ]; then
		echo "Dovecot: ${boldon}${DOVECOT_VER}${boldoff}"
	else
		echo "Dovecot: ${boldon}no${boldoff}"
	fi

	echo "Dovecot configuration: ${boldon}${DOVECOT_CONF_OPT}${boldoff}"

	if [ "${AWSTATS_OPT}" = "yes" ]; then
		echo "AWstats: ${boldon}${AWSTATS_VER}${boldoff}"
	else
		echo "AWstats: ${boldon}no${boldoff}"
	fi

	if [ "${EXIM_OPT}" = "yes" ]; then
		echo "Exim: ${boldon}${EXIM_VER}${boldoff}"
	else
		echo "Exim: ${boldon}no${boldoff}"
	fi

	echo "exim.conf update: ${boldon}${EXIMCONF_OPT}${boldoff}"

	echo "BlockCracking: ${boldon}${BLOCKCRACKING_OPT}${boldoff}"

	echo "Easy Spam Fighter: ${boldon}${EASY_SPAM_FIGHTER_OPT}${boldoff}"

	if [ "${SPAMD_OPT}" = "spamassassin" ]; then
		echo "SpamAssassin: ${boldon}${SPAMASSASSIN_VER}${boldoff}"
		echo "SpamAssassin rule updates: ${boldon}${SA_UPDATE_OPT}${boldoff}"
	elif [ "${SPAMD_OPT}" = "rspamd" ]; then
		echo "Rspamd: ${boldon}yes${boldoff}"
	else
		echo "SpamAssassin: ${boldon}no${boldoff}"
	fi

	if [ "${CLAMAV_OPT}" = "yes" ]; then
		echo "ClamAV: ${boldon}yes${boldoff}"
	else
		echo "ClamAV: ${boldon}no${boldoff}"
	fi

	if [ "${MYSQL_INST_OPT}" != "no" ]; then
		if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
			echo "${MYSQLNAME}: ${boldon}${MYSQL_VER}${boldoff}"
		else
			echo "${MYSQLNAME}: ${boldon}${MARIADB_VER}${boldoff}"
		fi
	else
		echo "${MYSQLNAME}: ${boldon}no${boldoff}"
	fi

	echo "MySQL backup: ${boldon}${MYSQL_BACKUP_OPT}${boldoff}"

	if [ "${MYSQL_BACKUP_OPT}" = "yes" ]; then
		echo "MySQL backup directory: ${boldon}${MYSQL_BACKUP_DIR_OPT}${boldoff}"

		echo "MySQL compress backups: ${boldon}${MYSQL_BACKUP_GZIP_OPT}${boldoff}"
	fi

	echo "PHP (default): ${boldon}${PHP1_RELEASE_OPT}${boldoff} as ${boldon}${PHP1_MODE_OPT}${boldoff}"
	if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		echo "PHP (additional): ${boldon}${PHP2_RELEASE_OPT}${boldoff} as ${boldon}${PHP2_MODE_OPT}${boldoff}"
	fi
	if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		echo "PHP (additional, 3rd): ${boldon}${PHP3_RELEASE_OPT}${boldoff} as ${boldon}${PHP3_MODE_OPT}${boldoff}"
	fi
	if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		echo "PHP (additional, 4th): ${boldon}${PHP4_RELEASE_OPT}${boldoff} as ${boldon}${PHP4_MODE_OPT}${boldoff}"
	fi

	if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
		echo "phpMyAdmin: ${boldon}${PHPMYADMIN_VER}${boldoff}"
	else
		echo "phpMyAdmin: ${boldon}no${boldoff}"
	fi

	if [ "${FTPD_OPT}" = "proftpd" ]; then
		echo "ProFTPD: ${boldon}${PROFTPD_VER}${boldoff}"
	else
		echo "ProFTPD: ${boldon}no${boldoff}"
	fi

	if [ "${FTPD_OPT}" = "pureftpd" ]; then
		echo "Pure-FTPd: ${boldon}${PUREFTPD_VER}${boldoff}"
	else
		echo "Pure-FTPd: ${boldon}no${boldoff}"
	fi

	if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
		echo "RoundCube webmail: ${boldon}${ROUNDCUBE_VER}${boldoff}"
	else
		echo "RoundCube webmail: ${boldon}no${boldoff}"
	fi

	if [ "${WEBAPPS_INBBOX_PREFIX_OPT}" = "yes" ]; then
		echo "Webapps using .INBOX prefix for IMAP folders: ${boldon}${WEBAPPS_INBBOX_PREFIX_OPT}${boldoff}"
	fi

	echo "Replace \"php.ini\" with '$0 all' and '$0 php_ini': ${boldon}${PHP_INI_OPT}${boldoff}"

	if [ "${PHP_INI_OPT}" = "yes" ]; then
		echo "Replace \"php.ini\" using type: ${boldon}${PHP_INI_TYPE_OPT}${boldoff}"
	fi

	if [ "${CRON_OPT}" = "yes" ]; then
		echo "Cron for notifications and (or) updates: ${boldon}yes${boldoff}"
		echo "Cron frequency: ${boldon}${CRON_FREQUENCY_OPT}${boldoff}"
		if [ "${NOTIFICATIONS_OPT}" = "yes" ]; then
			echo "Auto notifications: ${boldon}yes${boldoff}"
			echo "Auto notifications email address: ${boldon}${EMAIL_OPT}${boldoff}"
		fi
		if [ "${UPDATES_OPT}" = "yes" ]; then
			echo "Auto updates: ${boldon}yes${boldoff}"
		fi
	else
		echo "Auto updates/notifications: ${boldon}no${boldoff}"
	fi

	echo "Run \"clean\" every time: ${boldon}${CLEAN_OPT}${boldoff}"
	echo "Run \"clean_old_webapps\" every time: ${boldon}${CLEAN_OLD_WEBAPPS_OPT}${boldoff}"
	echo "Run \"clean_old_tarballs\" every time: ${boldon}${CLEAN_OLD_TARBALLS_OPT}${boldoff}"

	echo "Show texts in bold: ${boldon}${BOLD_OPT}${boldoff}"

	if [ "${SQUIRRELMAIL_OPT}" = "yes" ]; then
		echo "SquirrelMail: ${boldon}${SQUIRRELMAIL_VER}${boldoff}"
	else
		echo "SquirrelMail: ${boldon}no${boldoff}"
	fi

	echo "Zend Guard Loader: ${boldon}${ZEND_OPT}${boldoff}"

	if [ "${IONCUBE_OPT}" = "yes" ]; then
		echo "ionCube loader: ${boldon}${IONCUBE_VER}${boldoff}"
	else
		echo "ionCube loader: ${boldon}no${boldoff}"
	fi

	if [ "${SUHOSIN_OPT}" = "yes" ] && [ "${SUHOSIN_PHP_UPLOADSCAN_OPT}" = "yes" ]; then
		echo "Suhosin (with PHP upload scan script): ${boldon}${SUHOSIN_VER}${boldoff}"
	elif [ "${SUHOSIN_OPT}" = "yes" ] && [ "${SUHOSIN_PHP_UPLOADSCAN_OPT}" = "no" ]; then
		echo "Suhosin: ${boldon}${SUHOSIN_VER}${boldoff}"
	else
		echo "Suhosin: ${boldon}no${boldoff}"
	fi
}

####################################################

option_set_valid_php() {
	#Used in create_options()
	if [ -z $2 ]; then
		if [ ! -z "$3" ]; then
			OPTION_VALUE="${3}"
		else
			echo "Two arguments must be given for the function"
			return
		fi
	else
		OPTION_VALUE="${2}"
	fi
	VAR=`echo $1 | tr "[a-z]" "[A-Z]"`
	TMPVAR=PHP_${VAR}_SET

	if [ -z "${!TMPVAR}" ]; then
		echo "${1} is not a valid option."
		return
	fi

	VALID="no"
	for i in ${!TMPVAR}; do
		if [ "${i}" = "${OPTION_VALUE}" ] || [ "${i}" = "userinput" ]; then
			VALID="yes"
			break
		fi
	done
	if [ "${VALID}" = "yes" ]; then
		command_set_php $1 ${OPTION_VALUE}
	else
		echo "${boldon}Invalid selection, please enter the selection again.${boldoff}"
	fi
	echo ""
}

option_set_valid() {
	#Used in create_options()
	if [ -z "$2" ]; then
		if [ ! -z "$3" ]; then
			OPTION_VALUE="${3}"
		else
			echo "Two arguments must be given for the function"
			return
		fi
	else
		OPTION_VALUE="${2}"
	fi
	VAR=`echo $1 | tr "[a-z]" "[A-Z]"`
	TMPVAR=${VAR}_SET

	if [ -z "${!TMPVAR}" ]; then
		echo "${1} is not a valid option."
		return
	fi

	VALID="no"
	for i in ${!TMPVAR}; do
		if [ "${i}" = "${OPTION_VALUE}" ] || [ "${i}" = "userinput" ]; then
			VALID="yes"
			break
		fi
	done
	if [ "${VALID}" = "yes" ]; then
		command_set $1 ${OPTION_VALUE}
	else
		echo "${boldon}Invalid selection, please enter the selection again.${boldoff}"
	fi
	echo ""
}

create_options() {
	HIDE_CHANGES=1

	if [ -s ${OPTIONS_CONF} ] && [ -f ${OPTIONS_CONF} ]; then
		echo -n "Would you like to backup the current options.conf? (yes/no, default: yes): "
		read do_opt_backup
		until [ "${do_opt_backup}" = "yes" ] || [ "${do_opt_backup}" = "no" ] || [ -z "${do_opt_backup}" ]; do
			echo -n "Please enter 'yes', 'no' or click 'enter' for default: "
			read do_opt_backup
		done
		if [ -z "${do_opt_backup}" ]; then
			do_opt_backup="yes"
		fi

		if [ "${do_opt_backup}" = "yes" ]; then
			cp -f ${OPTIONS_CONF} ${OPTIONS_CONF}.`date +%Y%m%d%I%M%S`.backup
			echo "Backup created: ${OPTIONS_CONF}.`date +%Y%m%d%I%M%S`.backup"
		fi
		echo ""
	fi

	echo -n "Would you like the default settings of ${WEBSERVER_OPT} and php ${PHP1_RELEASE_OPT} as ${PHP1_MODE_OPT}? (yes/no, default: yes):"
	read cb_defaults
	until [ "${cb_defaults}" = "yes" ] || [ "${cb_defaults}" = "no" ] || [ -z "${cb_defaults}" ]; do
		echo -n "Please enter 'yes' or 'no': "
		read cb_defaults
	done
	if [ -z "${cb_defaults}" ]; then
		cb_defaults="yes"
	fi

	if [ "${cb_defaults}" != "yes" ]; then
		QUESTION_SET="`echo ${WEBSERVER_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select webserver you would like to use (${QUESTION_SET}, default: ${WEBSERVER_DEF}):"
			read option_answer
			option_set_valid webserver "${option_answer}" "${WEBSERVER_DEF}"
		done

		if [ -e /etc/redhat-release ]; then
			if grep -q CloudLinux /etc/redhat-release; then
				echo -n "Would you like to enable CloudLinux in CustomBuild? (yes/no, default: yes): "
				read clopt
				until [ "${clopt}" = "yes" ] || [ "${clopt}" = "no" ] || [ -z "${do_opt_backup}" ]; do
					echo -n "Please enter 'yes' or 'no': "
					read clopt
				done
				if [ -z "${clopt}" ]; then
					clopt="yes"
				fi
				command_set cloudlinux "${clopt}"
				echo ""
			fi
		fi

		QUESTION_SET="`echo ${MYSQL_INST_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select MySQL database server you would like to use (${QUESTION_SET}, default: ${MYSQL_INST_DEF}):"
			read option_answer
			option_set_valid mysql_inst "${option_answer}" "${MYSQL_INST_DEF}"
		done

		MYSQL_INST_ANSWER=${option_answer}
		if [ -z "${MYSQL_INST_ANSWER}" ]; then
			MYSQL_INST_ANSWER=${MYSQL_INST_DEF}
		fi

		if [ "${MYSQL_INST_ANSWER}" != "no" ]; then
			if [ "${MYSQL_INST_ANSWER}" = "mysql" ]; then
				QUESTION_SET="`echo ${MYSQL_SET} | tr ' ' '/'`"
				QUESTION_DEF="${MYSQL_DEF}"
			else
				QUESTION_SET="`echo ${MARIADB_SET} | tr ' ' '/'`"
				QUESTION_DEF="${MARIADB_DEF}"
			fi
			VALID="no"
			until [ "${VALID}" = "yes" ]; do
				echo -n "Please select ${MYSQL_INST_ANSWER} version you would like to use (${QUESTION_SET}, default: ${QUESTION_DEF}):"
				read option_answer
				option_set_valid ${MYSQL_INST_ANSWER} "${option_answer}" "${QUESTION_DEF}"
			done
		fi

		QUESTION_SET="`echo ${FTPD_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select FTP server you would like to use (${QUESTION_SET}, ${FTPD_DEF}):"
			read option_answer
			option_set_valid ftpd "${option_answer}" "${FTPD_DEF}"
		done

		QUESTION_SET="`echo ${PHP1_RELEASE_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select default PHP version you would like to use (${QUESTION_SET}, default: ${PHP1_RELEASE_DEF}):"
			read option_answer
			option_set_valid php1_release "${option_answer}" "${PHP1_RELEASE_DEF}"
		done

		DEFPHP_ANSWER="no"
		QUESTION_SET="`echo ${PHP1_MODE_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select default PHP mode you would like to use (${QUESTION_SET}, default: ${PHP1_MODE_DEF}):"
			read option_answer
			option_set_valid php1_mode "${option_answer}" "${PHP1_MODE_DEF}"
		done
		DEFPHP_ANSWER=${option_answer}

		if [ -z "${DEFPHP_ANSWER}" ]; then
			DEFPHP_ANSWER="${PHP1_MODE_DEF}"
		fi

		echo -n "Would you like to have a second instance of PHP installed? (yes/no, default: no): "
		read wantsec
		until [ "${wantsec}" = "yes" ] || [ "${wantsec}" = "no" ] || [ -z "${wantsec}" ]; do
			echo -n "Please enter 'yes' or 'no': "
			read wantsec
			if [ -z "${wantsec}" ]; then
				wantsec="no"
			fi
		done
		echo ""

		if [ "${wantsec}" = "yes" ]; then
			#PHP1_RELEASE_SET is not a bug here :) It's set not to display "no" as an option, because the previous question already asks if anyone would like to have a 2nd version of PHP
			QUESTION_SET="`echo ${PHP1_RELEASE_SET} | tr ' ' '/'`"
			VALID="no"
			until [ "${VALID}" = "yes" ]; do
				echo -n "Please select additional PHP version you would like to use (${QUESTION_SET}):"
				read option_answer
				option_set_valid php2_release ${option_answer}
			done

			QUESTION_SET="`echo ${PHP2_MODE_SET} | tr ' ' '/'`"
			VALID="no"
			until [ "${VALID}" = "yes" ]; do
				echo -n "Please select additional PHP mode you would like to use (${QUESTION_SET}, default: ${PHP1_MODE_DEF}):"
				read option_answer
				option_set_valid php2_mode "${option_answer}" "${PHP1_MODE_DEF}"
			done

			echo -n "Would you like to have a third instance of PHP installed? (yes/no, default: no): "
			read wantthird
			until [ "${wantthird}" = "yes" ] || [ "${wantthird}" = "no" ] || [ -z "${wantthird}" ]; do
				echo -n "Please enter 'yes' or 'no': "
				read wantthird
				if [ -z "${wantthird}" ]; then
					wantthird="no"
				fi
			done
			echo ""
		
			if [ "${wantthird}" = "yes" ]; then
				#PHP1_RELEASE_SET is not a bug here :) It's set not to display "no" as an option, because the previous question already asks if anyone would like to have a 2nd version of PHP
				QUESTION_SET="`echo ${PHP1_RELEASE_SET} | tr ' ' '/'`"
				VALID="no"
				until [ "${VALID}" = "yes" ]; do
					echo -n "Please select additional PHP version you would like to use (${QUESTION_SET}):"
					read option_answer
					option_set_valid php3_release ${option_answer}
				done

				QUESTION_SET="`echo ${PHP3_MODE_SET} | tr ' ' '/'`"
				VALID="no"
				until [ "${VALID}" = "yes" ]; do
					echo -n "Please select additional PHP mode you would like to use (${QUESTION_SET}, default: ${PHP1_MODE_DEF}):"
					read option_answer
					option_set_valid php3_mode "${option_answer}" "${PHP1_MODE_DEF}"
				done
		
				echo -n "Would you like to have a fourth instance of PHP installed? (yes/no, default: no): "
				read wantfourth
				until [ "${wantfourth}" = "yes" ] || [ "${wantfourth}" = "no" ] || [ -z "${wantfourth}" ]; do
					echo -n "Please enter 'yes' or 'no': "
					read wantfourth
					if [ -z "${wantfourth}" ]; then
						wantfourth="no"
					fi
				done
				echo ""

				if [ "${wantfourth}" = "yes" ]; then
					#PHP1_RELEASE_SET is not a bug here :) It's set not to display "no" as an option, because the previous question already asks if anyone would like to have a 2nd version of PHP
					QUESTION_SET="`echo ${PHP1_RELEASE_SET} | tr ' ' '/'`"
					VALID="no"
					until [ "${VALID}" = "yes" ]; do
						echo -n "Please select additional PHP version you would like to use (${QUESTION_SET}):"
						read option_answer
						option_set_valid php4_release ${option_answer}
					done

					QUESTION_SET="`echo ${PHP4_MODE_SET} | tr ' ' '/'`"
					VALID="no"
					until [ "${VALID}" = "yes" ]; do
						echo -n "Please select additional PHP mode you would like to use (${QUESTION_SET}, default: ${PHP1_MODE_DEF}):"
						read option_answer
						option_set_valid php4_mode "${option_answer}" "${PHP1_MODE_DEF}"
					done
				fi
			fi
		fi

		QUESTION_SET="`echo ${PHP_IONCUBE_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select if you would like to use ionCube (${QUESTION_SET}, default: ${PHP_IONCUBE_DEF}):"
			read option_answer
			option_set_valid_php ioncube "${option_answer}" "${PHP_IONCUBE_DEF}"
		done

		QUESTION_SET="`echo ${PHP_OPCACHE_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select if you would like to use opCache (${QUESTION_SET}, default: ${PHP_OPCACHE_DEF}):"
			read option_answer
			option_set_valid_php opcache "${option_answer}" "${PHP_OPCACHE_DEF}"
		done

		QUESTION_SET="`echo ${PHP_ZEND_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select if you would like to use Zend Guard Loader (${QUESTION_SET}, default: ${PHP_ZEND_DEF}):"
			read option_answer
			option_set_valid_php zend "${option_answer}" "${PHP_ZEND_DEF}"
		done

		QUESTION_SET="`echo ${EXIM_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select if you would like CustomBuild to manage Exim installation (${QUESTION_SET}, default: ${EXIM_DEF}):"
			read option_answer
			option_set_valid exim "${option_answer}" "${EXIM_DEF}"
		done

		QUESTION_SET="`echo ${DOVECOT_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select if you would like CustomBuild to manage Dovecot installation (${QUESTION_SET}, default: ${DOVECOT_DEF}):"
			read option_answer
			option_set_valid dovecot "${option_answer}" "${DOVECOT_DEF}"
		done

		QUESTION_SET="`echo ${PHPMYADMIN_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select if you would like CustomBuild to manage phpMyAdmin installation (${QUESTION_SET}, default: ${PHPMYADMIN_DEF}):"
			read option_answer
			option_set_valid phpmyadmin "${option_answer}" "${PHPMYADMIN_DEF}"
		done

		QUESTION_SET="`echo ${SQUIRRELMAIL_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select if you would like CustomBuild to manage SquirrelMail installation (${QUESTION_SET}, default: ${SQUIRRELMAIL_DEF}):"
			read option_answer
			option_set_valid squirrelmail "${option_answer}" "${SQUIRRELMAIL_DEF}"
		done

		QUESTION_SET="`echo ${ROUNDCUBE_SET} | tr ' ' '/'`"
		VALID="no"
		until [ "${VALID}" = "yes" ]; do
			echo -n "Please select if you would like CustomBuild to manage RoundCube installation (${QUESTION_SET}, default: ${ROUNDCUBE_DEF}):"
			read option_answer
			option_set_valid roundcube "${option_answer}" "${ROUNDCUBE_DEF}"
		done
	fi
}

####################################################

used_configs() {
	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "Apache configuration file: ${configure_scripts_active[apache]}"
	fi
	if [ "${WEBSERVER_OPT}" = "nginx" ]; then
		echo "Nginx configuration file: ${configure_scripts_active[nginx]}"
	fi
	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "Nginx (reverse proxy) configuration file: ${configure_scripts_active[nginx_reverse]}"
	fi

	PHP_INI_VAR=PHP_INI_FPM${PHP1_SHORTRELEASE}
	echo "PHP (default) php.ini file: ${!PHP_INI_VAR}"

	if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		PHP_INI_VAR=PHP_INI_FPM${PHP2_SHORTRELEASE}
		echo "PHP (additional) php.ini file: ${!PHP_INI_VAR}"
	fi

	if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		PHP_INI_VAR=PHP_INI_FPM${PHP3_SHORTRELEASE}
		echo "PHP (additional, 3rd) php.ini file: ${!PHP_INI_VAR}"
	fi

	if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		PHP_INI_VAR=PHP_INI_FPM${PHP4_SHORTRELEASE}
		echo "PHP (additional, 4th) php.ini file: ${!PHP_INI_VAR}"
	fi

	echo "PHP (default) configuration file: ${configure_scripts_active[php${PHP1_SHORTRELEASE}_${PHP1_MODE_OPT}]}"

	if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		echo "PHP (additional) configuration file: ${configure_scripts_active[php${PHP2_SHORTRELEASE}_${PHP2_MODE_OPT}]}"
	fi

	if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		echo "PHP (additional, 3rd) configuration file: ${configure_scripts_active[php${PHP3_SHORTRELEASE}_${PHP3_MODE_OPT}]}"
	fi

	if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		echo "PHP (additional, 4th) configuration file: ${configure_scripts_active[php${PHP4_SHORTRELEASE}_${PHP4_MODE_OPT}]}"
	fi

	if [ "${FTPD_OPT}" = "proftpd" ]; then
		echo "ProFTPD configuration file: ${configure_scripts_active[proftpd]}"
	fi

	if [ "${FTPD_OPT}" = "pureftpd" ]; then
		echo "PureFTPD configuration file: ${configure_scripts_active[pureftpd]}"
	fi

	if [ "${IMAGICK_OPT}" = "yes" ]; then
		echo "ImageMagick configuration file: ${configure_scripts_active[imagemagick]}"
	fi

	if [ "${EXIM_OPT}" = "yes" ]; then
		echo -n "Exim Makefile: "
		if [ "${EXIM_MAKEFILE}" != "" ]; then
			echo "${EXIM_MAKEFILE}"
		else
			echo "${WEBPATH}/Makefile"
		fi
	fi

	if [ "${DOVECOT_OPT}" = "yes" ]; then
		echo "Dovecot configuration file: ${configure_scripts_active[dovecot]}"
	fi

	if [ -d ${PMA_THEMES} ]; then
		if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
			echo "phpMyAdmin themes directory: ${PMA_THEMES}"
		fi
	fi

	if [ -e ${PMA_MAIN_CONFIG} ]; then
		if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
			echo "phpMyAdmin configuration file: ${PMA_MAIN_CONFIG}"
		fi
	fi
	
	if [ -e ${PMA_HTACCESS} ]; then
		if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
			echo "phpMyAdmin .htaccess file: ${PMA_HTACCESS}"
		fi
	fi
	
	if [ -e ${PMA_USER_INI} ]; then
		if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
			echo "phpMyAdmin .user.ini file: ${PMA_USER_INI}"
		fi
	fi

	if [ -e ${SQUIRREL_CONFIG} ]; then
		if [ "${SQUIRRELMAIL_OPT}" = "yes" ]; then
			echo "SquirrelMail configuration file: ${SQUIRREL_CONFIG}"
		fi
	fi

	if [ -e ${ROUNDCUBE_CONFIG} ]; then
		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			echo "RoundCube webmail configuration file: ${ROUNDCUBE_CONFIG}"
		fi
	fi

	if [ -e ${ROUNDCUBE_CONFIG_DB} ]; then
		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			echo "RoundCube webmail database configuration file: ${ROUNDCUBE_CONFIG_DB}"
		fi
	fi

	if [ -e ${ROUNDCUBE_HTACCESS} ]; then
		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			echo "RoundCube .htaccess file: ${ROUNDCUBE_HTACCESS}"
		fi
	fi
	
	if [ -e ${ROUNDCUBE_COMPOSER} ]; then
		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			echo "RoundCube composer.json file: ${ROUNDCUBE_COMPOSER}"
		fi
	fi

	if [ -d ${ROUNDCUBE_PLUGINS} ]; then
		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			echo "RoundCube webmail plugins overwrite directory: ${ROUNDCUBE_PLUGINS}"
		fi
	fi

	if [ -d ${ROUNDCUBE_SKINS} ]; then
		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			echo "RoundCube webmail skins overwrite directory: ${ROUNDCUBE_SKINS}"
		fi
	fi
	
	if [ -d ${ROUNDCUBE_VENDOR} ]; then
		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			echo "RoundCube webmail vendor overwrite directory: ${ROUNDCUBE_VENDOR}"
		fi
	fi

	if [ -d ${ROUNDCUBE_PROGRAM} ]; then
		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			echo "RoundCube webmail program overwrite directory: ${ROUNDCUBE_PROGRAM}"
		fi
	fi

}

####################################################

listConfigsJSON() {
	# Array for descriptions and for picking which sections to show
	declare -A avail=()
	[ "${WEBSERVER_OPT}" = "apache" ]        && avail[apache]="Apache configuration file"
	[ "${WEBSERVER_OPT}" = "nginx_apache" ]  && avail[apache]="Apache configuration file"
	[ "${WEBSERVER_OPT}" = "nginx" ]         && avail[nginx]="Nginx configuration file"
	[ "${WEBSERVER_OPT}" = "nginx_reverse" ] && avail[nginx_reverse]="Nginx (reverse proxy) configuration file"
	[ "${DOVECOT_OPT}" = "yes" ]             && avail[dovecot]="Dovecot configuration file"
	[ "${FTPD_OPT}" = "proftpd" ]            && avail[proftpd]="ProFTPd configuration file"
	[ "${FTPD_OPT}" = "pureftpd" ]           && avail[pureftpd]="Pure-FTPd configuration file"
	[ "${IMAGICK_OPT}" = "yes" ]             && avail[imagemagick]="ImageMagick configuration file"
	[ "${UNIT_OPT}" = "yes" ]                && avail[unit]="Nginx Unit configuration file"
	local php_release php_mode
	for php_release in "${!options_conf_php[@]}"; do
		php_mode=${options_conf_php[${php_release}]}
		avail[php${php_release//./}_${php_mode}]="PHP ${php_release} as ${php_mode} configuration file"
	done

	echo "{"
	local n=0
	for section in "${!avail[@]}"; do
		printf '\t"%s": {\n' "${section}"
		printf '\t\t"description": "%s",\n' "${avail[$section]}"
		printf '\t\t"main": "%s",\n' "${configure_scripts_main[$section]}"
		printf '\t\t"read": "%s",\n' "${configure_scripts_active[$section]}"
		printf '\t\t"custom": "%s"\n' "${configure_scripts_custom[$section]}"
		printf '\t}'
		((n++))
		if [ "${n}" -ne "${#avail[@]}" ]; then
			printf ','
		fi
		printf '\n'
	done
	echo "}"
}

####################################################

addToAccess() {
	if [ -z $1 ]; then
		return
	fi
	# Check for nginx user in access group
	if grep -m1 -q "^access" /etc/group; then
		if ! grep -m1 "^access" /etc/group | grep -q $1; then
			usermod -G access $1
		fi
	fi
}

####################################################
fpmCheck() {
	ARG=$1
	CHANGED=0
	COUNT=`grep -m1 -c nginx /usr/local/php${ARG}/etc/php-fpm.conf`
	CHOWN_USER=${WEBSERVER_OPT}
	if [ "${CHOWN_USER}" = "nginx_apache" ]; then
		CHOWN_USER=apache
	fi
	chown ${CHOWN_USER}:${CHOWN_USER} /usr/local/php${ARG}/sockets
	FPM_SOCK_CHMOD=710
	chmod ${FPM_SOCK_CHMOD} /usr/local/php${ARG}/sockets

	if [ "${WEBSERVER_OPT}" = "nginx" ] && [ "${COUNT}" -eq 0 ]; then
		perl -pi -e 's/apache/nginx/' /usr/local/php${ARG}/etc/php-fpm.conf
		CHANGED=1
	elif [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ "${COUNT}" -gt 0 ]; then
			perl -pi -e 's/nginx/apache/' /usr/local/php${ARG}/etc/php-fpm.conf
			CHANGED=1
		fi
	fi

	if [ -d /usr/local/php${ARG}/sockets ]; then
		if [ "${WEBSERVER_OPT}" = "nginx" ]; then
			chgrp -R nginx /usr/local/php${ARG}/sockets
		elif [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			chgrp -R apache /usr/local/php${ARG}/sockets
		fi
	fi

	if [ ${CHANGED} -eq 1 ]; then
		control_service php-fpm${ARG} restart
	fi
}

fpmChecks() {
	for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
		EVAL_CHECK_VAR=HAVE_FPM${php_shortrelease}_CGI
		EVAL_COPY_VAR=PHP${php_shortrelease}_FPM_CONF
		if [ "${!EVAL_CHECK_VAR}" = "yes" ] && [ -d /usr/local/php${php_shortrelease}/sockets ]; then
			cp -f ${!EVAL_COPY_VAR} /usr/local/php${php_shortrelease}/etc/php-fpm.conf
			fpmCheck ${php_shortrelease}
		fi
	done

	if [ "${HAVE_FPM_CGI}" = "yes" ]; then
		if [ "${WEBSERVER_OPT}" = "nginx" ]; then
			perl -pi -e 's/apache/nginx/' /usr/local/directadmin/data/templates/php-fpm.conf
		elif [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			perl -pi -e 's/nginx/apache/' /usr/local/directadmin/data/templates/php-fpm.conf
		fi

		#update the webapps_settings.conf
		#swap "fastcgi_pass unix:/usr/local/php54/sockets/webapps.sock;" if needed
		#might be a better way to do this, other checks. Close enough for now.
		if [ -e /etc/nginx/webapps_settings.conf ]; then
			PHP_REPLACE_STRING="`grep -m1 '^fastcgi_pass unix:/usr/local/php../sockets/webapps.sock;' /etc/nginx/webapps_settings.conf | cut -d/ -f4`"
			if [ "${PHP_REPLACE_STRING}" = "" ]; then
				PHP_REPLACE_STRING=php54
			fi
			if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
				perl -pi -e "s#${PHP_REPLACE_STRING}#php${PHP1_SHORTRELEASE}#" /etc/nginx/webapps_settings.conf
			fi
		fi

		if [ -e /etc/nginx/nginx-vhosts.conf ]; then
			PHP_REPLACE_STRING="`grep -m1 '^fastcgi_pass unix:/usr/local/php../sockets/webapps.sock;' /etc/nginx/nginx-vhosts.conf | cut -d/ -f4`"
			if [ "${PHP_REPLACE_STRING}" = "" ]; then
				PHP_REPLACE_STRING=php54
			fi
			if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
				perl -pi -e "s#${PHP_REPLACE_STRING}#php${PHP1_SHORTRELEASE}#" /etc/nginx/nginx-vhosts.conf
			fi
		fi
		
		if [ -e /etc/nginx/nginx-userdir.conf ]; then
			PHP_REPLACE_STRING="`grep -m1 '^fastcgi_pass unix:/usr/local/php../sockets/webapps.sock;' /etc/nginx/nginx-userdir.conf | cut -d/ -f4`"
			if [ "${PHP_REPLACE_STRING}" = "" ]; then
				PHP_REPLACE_STRING=php54
			fi
			if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
				perl -pi -e "s#${PHP_REPLACE_STRING}#php${PHP1_SHORTRELEASE}#" /etc/nginx/nginx-userdir.conf
			fi
		fi
	fi
}

dovecotChecks() {
	if [ -e ${DOVECOT_CONFIG} ]; then
		if [ "${WEBSERVER_OPT}" = "nginx" ]; then
			if grep -m1 -q '/etc/httpd/conf/' ${DOVECOT_CONFIG}; then
				perl -pi -e 's#/etc/httpd/conf/#/etc/nginx/#' ${DOVECOT_CONFIG}
				control_service dovecot restart
			elif grep -m1 -q '/usr/local/lsws/conf/' ${DOVECOT_CONFIG}; then
				perl -pi -e 's#/usr/local/lsws/conf/#/etc/nginx/#' ${DOVECOT_CONFIG}
				control_service dovecot restart
			fi
		elif [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
			if grep -m1 -q '/etc/httpd/conf/' ${DOVECOT_CONFIG}; then
				perl -pi -e 's#/etc/httpd/conf/#/usr/local/lsws/conf/#' ${DOVECOT_CONFIG}
				control_service dovecot restart
			elif grep -m1 -q '/etc/nginx/' ${DOVECOT_CONFIG}; then
				perl -pi -e 's#/etc/nginx/#/usr/local/lsws/conf/#' ${DOVECOT_CONFIG}
				control_service dovecot restart
			fi
		elif [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			if grep -m1 -q '/etc/nginx/' ${DOVECOT_CONFIG}; then
				perl -pi -e 's#/etc/nginx/#/etc/httpd/conf/#' ${DOVECOT_CONFIG}
				control_service dovecot restart
			elif grep -m1 -q '/usr/local/lsws/conf/' ${DOVECOT_CONFIG}; then
				perl -pi -e 's#/usr/local/lsws/conf/#/etc/httpd/conf/#' ${DOVECOT_CONFIG}
				control_service dovecot restart
			fi
		fi
	fi
}

####################################################

addWebappsUser() {
	# Check for webapps user
	if [ `grep -c -m1 -e "^${APPUSER}:" /etc/passwd` = "0" ]; then
		if distro_is_debian; then
			/usr/sbin/adduser --system --group --firstuid 100 --home ${WWWDIR} --no-create-home --disabled-login --force-badname ${APPUSER}
		elif distro_is_rhel; then
			/usr/sbin/useradd -d ${WWWDIR} -s /bin/false ${APPUSER} 2> /dev/null
		fi
	fi

	####################################################
	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		# Do we have httpd-phpmodules.conf line?
		NEWCONFIGS=1
		if [ -e ${HTTPD_CONF} ]; then
			if [ "`grep -m1 -c -e '/etc/httpd/conf/extra/httpd-phpmodules.conf' ${HTTPD_CONF}`" = "0" ]; then
				NEWCONFIGS=0
			fi
		fi
	fi
}

####################################################

setupLogrotate() {
	if [ ! -d /etc/logrotate.d ] || [ ! -s "${CB_LOGROTATE}/${1}" ]; then
		return
	fi
	if [ -e "${CB_CUST_LOGROTATE}/${1}" ]; then
		cp -f "${CB_CUST_LOGROTATE}/${1}" "/etc/logrotate.d/${1}"
	else
		cp -f "${CB_LOGROTATE}/${1}" "/etc/logrotate.d/${1}"
	fi
	chmod 644 "/etc/logrotate.d/${1}"
}

ensure_webapps_logrotate() {
	cd ${WORKDIR}

	setupLogrotate webapps

	WL=/etc/logrotate.d/webapps
	if grep -q 'su apache webapps' ${WL}; then
		perl -pi -e 's/su apache webapps/su webapps webapps/' ${WL}
	fi

	#backup in case mod_php was used before
	if grep -q 'su apache apache' ${WL}; then
		perl -pi -e 's/su apache apache/su webapps webapps/' ${WL}
	fi
}

####################################################

ensure_webapps_php_ini() {
	WEBAPPS_INI=/usr/local/php${PHP1_SHORTRELEASE}/lib/php.conf.d/50-webapps.ini
	mkdir -p /usr/local/php${PHP1_SHORTRELEASE}/lib/php.conf.d

	if [ -e ${PHP_CUSTOM_PHP_CONF_D_INI_PATH}/50-webapps.ini ]; then
		echo "Using custom ${PHP_CUSTOM_PHP_CONF_D_INI_PATH}/50-webapps.ini for ${WEBAPPS_INI}"
		cp -f ${PHP_CUSTOM_PHP_CONF_D_INI_PATH}/50-webapps.ini ${WEBAPPS_INI}
	else
		echo "[PATH=${WWWDIR}]" > ${WEBAPPS_INI}
		echo "session.save_path=${APP_TMP}" >> ${WEBAPPS_INI}
		echo "upload_tmp_dir=${APP_TMP}" >> ${WEBAPPS_INI}
		echo "disable_functions=exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname" >> ${WEBAPPS_INI}
	fi
}

ensure_webapps_tmp() {
	if [ ! -d ${APP_TMP} ]; then
		mkdir -p ${APP_TMP}
	fi

	chmod 770 ${APP_TMP}
	chown ${APPUSER}:${APPGROUP} ${APP_TMP}

	ensure_webapps_php_ini
}

####################################################

dophpMyAdmin() {
	if [ "${PHPMYADMIN_OPT}" != "yes" ]; then
		do_exit 1 "You cannot install phpMyAdmin, because you do not have it set in options.conf file."
	fi

	addWebappsUser
	ensure_webapps_logrotate

	cd ${WORKDIR}
	if [ ! -d ${WWWDIR} ]; then
		echo "${WWWDIR} does not exist."
		do_exit 0
	fi

	initMySQL

	if [ ! -s "$MYSQL_BIN" ]; then
		echo "${boldon}phpMyAdmin requires mysqld.  Cannot find $MYSQL_BIN${boldoff}"
		return
	fi
	
	if [ "`version_cmp ${PHPMYADMIN_VER} 4.5.0 'pma4.5 ver check'`" -ge 0 ]; then
		if [ "`version_cmp ${PHP1_RELEASE_OPT} 5.5 'pma4.5 php check'`" -lt 0 ]; then
			echo "${boldon}phpMyAdmin ${PHPMYADMIN_VER} requires PHP 5.5+, but ${PHP1_RELEASE_OPT} is installed${boldoff}"
			return
		fi
	fi
	if [ "`version_cmp ${PHPMYADMIN_VER} 5.2.0 'pma5.2 ver check'`" -ge 0 ]; then
		if [ "`version_cmp ${PHP1_RELEASE_OPT} 7.2 'pma5.2 php check'`" -lt 0 ]; then
			echo "${boldon}phpMyAdmin ${PHPMYADMIN_VER} requires PHP 7.2+, but ${PHP1_RELEASE_OPT} is installed${boldoff}"
			return
		fi
	fi
	if [ "`version_cmp ${PHPMYADMIN_VER} 5.0.0 'pma5.0 ver check'`" -ge 0 ]; then
		if [ "`version_cmp ${PHP1_RELEASE_OPT} 7.1 'pma5.0 php check'`" -lt 0 ]; then
			echo "${boldon}phpMyAdmin ${PHPMYADMIN_VER} requires PHP 7.1+, but ${PHP1_RELEASE_OPT} is installed${boldoff}"
			return
		fi	
	fi

	TARFILE=${WORKDIR}/phpMyAdmin-${PHPMYADMIN_VER}.tar.gz
	REALPATH=${WWWDIR}/phpMyAdmin-${PHPMYADMIN_VER}
	ALIASPATH=${WWWDIR}/phpMyAdmin
	CONFIG=${REALPATH}/config.inc.php

	safeDownloadWithMove "${WORKDIR}/phpMyAdmin-${PHPMYADMIN_VER}.tar.gz" "${PHPMYADMIN_DOWNLOADURL}"

	if [ ! -s ${TARFILE} ]; then
		echo "The phpMyAdmin package cannot be found. Please ensure that the paths are correct"
		do_exit 0
	fi

	tar xzf ${TARFILE} --no-same-owner -C ${WWWDIR}

	PHPMYADMIN_AUTOLOGIN=0

	#SSO plugin
	if [ -x ${DA_BIN} ] && [ -s ${DACONF_FILE} ]; then
		if ${DA_BIN} c | grep -m1 -q '^one_click_pma_login=1$'; then
			PMA_DIRECT_LOGIN_VER=${versions_txt["pma_direct_login"]}
			PMA_DIRECT_LOGIN="phpMyAdmin_direct_login-${PMA_DIRECT_LOGIN_VER}.tar.gz"
			cd ${REALPATH}
			safeDownloadWithMove "${REALPATH}/${PMA_DIRECT_LOGIN}" "${WEBPATH_SERVICES}/all/auto_login/phpMyAdmin/${PMA_DIRECT_LOGIN}"
			tar xzf ${PMA_DIRECT_LOGIN}
			chown -R webapps:webapps direct_login
			chmod 711 direct_login
			chmod 700 direct_login/tokens

			if [ "${MYSQLHOST}" != "localhost" ]; then
				perl -pi -e "s#host = 'localhost'#host = '${MYSQLHOST}'#" direct_login/index.php
			fi			

			cd ${WORKDIR}
			PHPMYADMIN_AUTOLOGIN=1

		elif [ -d ${REALPATH}/direct_login ]; then
			rm -rf ${REALPATH}/direct_login
		fi
	fi

	if [ -s ${PMA_MAIN_CONFIG} ]; then
		PMA_CONF_MD5=`md5sum ${PMA_MAIN_CONFIG} | cut -d\  -f1`
		
		if [ "${PMA_CONF_MD5}" = "1289b44793c91dfa7f6b6512ec94d600" ]; then
			echo "Deleting ${PMA_MAIN_CONFIG}";
			rm -f ${PMA_MAIN_CONFIG}
		fi
	fi

	if [ "${PMA_CUSTOM_CONFIG}" != "" ] && [ -e ${PMA_CUSTOM_CONFIG} ]; then
		echo "Installing custom PhpMyAdmin Config: ${PMA_CUSTOM_CONFIG}"
		cp -f ${PMA_CUSTOM_CONFIG} ${REALPATH}/config.inc.php
	else
		cp -f ${PMA_MAIN_CONFIG} ${REALPATH}/config.inc.php
		BLOWFISH_SECRET="`tr -cd 'a-zA-Z0-9' < /dev/urandom 2>/dev/null | head -c32`"
		perl -pi -e "s|^\\\$cfg\['blowfish_secret'\] \= ''|\\\$cfg['blowfish_secret'] = '${BLOWFISH_SECRET}'|g" ${REALPATH}/config.inc.php
		if [ "${PHPMYADMIN_AUTOLOGIN}" = "0" ]; then
			perl -pi -e "s#\['auth_type'\] = 'cookie'#\['auth_type'\] = 'http'#" ${REALPATH}/config.inc.php
		else
			if [ "${PHPMYADMIN_PUBLIC_OPT}" = "no" ]; then
				if [ "${PHP1_RELEASE_OPT}" = "5.3" ]; then
					APPEND=""
				else
					APPEND="http_response_code\(403\)\;\n\t"
				fi
				perl -pi -e "s#\\\$cfg\['Servers'\]\[\\\$i\]\['auth_type'\] = 'cookie'#${APPEND}die(\"Access to phpMyAdmin is only allowed from control panel.\"\)#" ${REALPATH}/config.inc.php
			fi
		fi
		perl -pi -e "s#\['extension'\] = 'mysql'#\['extension'\] = 'mysqli'#" ${REALPATH}/config.inc.php
	fi
	
	perl -pi -e "s#\['host'\] = 'localhost'#\['host'\] = '${MYSQLHOST}'#" ${REALPATH}/config.inc.php
	perl -pi -e "s#\['host'\] = ''#\['host'\] = '${MYSQLHOST}'#" ${REALPATH}/config.inc.php
	
	if [ "`version_cmp ${PHPMYADMIN_VER} 4.8.0 'pma4.8 ver check'`" -ge 0 ]; then
		C=`grep -c AuthLog ${REALPATH}/config.inc.php`
		if [ "${C}" = "0" ]; then
			#add AuthLog to the config.
			echo "Adding AuthLog to ${REALPATH}/config.inc.php"
			echo "\$cfg['AuthLog'] = '/var/www/html/phpMyAdmin/log/auth.log';" >> ${REALPATH}/config.inc.php
		fi
		
		#and check the brute_filter.list for phpmyadmin3. pma4 comes with DA 1.53.1, so no need to add it.
		BFL=/usr/local/directadmin/data/templates/brute_filter.list
		C=`grep -c ^phpmyadmin3= ${BFL}`
		if [ "${C}" = "0" ]; then
			echo "Adding phpmyadmin3 to ${BFL}"
			echo "phpmyadmin3=ip_after=%20from%20'&ip_until='&text=phpmyadmin:%20user%20denied:%20&user_after=user%20denied:%20'&user_until='%20(mysql-denied)" >> ${BFL}
		fi

		if ! grep -m1 -q 'PmaNoRelation_DisableWarning' ${REALPATH}/config.inc.php; then
			#add PmaNoRelation_DisableWarning to the config.
			echo "Adding PmaNoRelation_DisableWarning to ${REALPATH}/config.inc.php"
			echo "\$cfg['PmaNoRelation_DisableWarning'] = true;" >> ${REALPATH}/config.inc.php
		fi
	fi

	if [ -e ${PMA_HTACCESS} ]; then
		echo "Installing custom PhpMyAdmin .htaccess: ${PMA_HTACCESS}"
		cp -f ${PMA_HTACCESS} ${REALPATH}/.htaccess
	fi

	if [ -e ${PMA_USER_INI} ]; then
		echo "Installing custom PhpMyAdmin .user.ini: ${PMA_USER_INI}"
		cp -f ${PMA_USER_INI} ${REALPATH}/.user.ini
	fi

	if [ -d ${PMA_THEMES} ]; then
		echo "Installing custom PhpMyAdmin themes: ${PMA_THEMES}"
		cp -Rf ${PMA_THEMES} ${REALPATH}
	fi

	rm -f ${ALIASPATH} >/dev/null 2>&1
	ln -s ${REALPATH} ${ALIASPATH}

	if [ ! -d ${REALPATH}/log ]; then
		mkdir -p ${REALPATH}/log
	fi

	chown -f -R ${APPUSER}:${APPUSER} ${REALPATH}
	chown -h ${APPUSER}:${APPUSER} ${ALIASPATH}
	chmod -f 755 ${REALPATH}

	if [ -d ${REALPATH}/log ]; then
		chmod 710 ${REALPATH}/log
	fi

	if [ -d ${REALPATH}/scripts ]; then
		chmod 000 ${REALPATH}/scripts
	fi

	if [ -d ${REALPATH}/setup ]; then
		chmod 000 ${REALPATH}/setup
	fi

	#secure configuration file
	if [ -s ${REALPATH}/config.inc.php ]; then
		chmod 440 ${REALPATH}/config.inc.php
		chown ${APPUSER}:${APPGROUP} ${REALPATH}/config.inc.php
	fi

	if [ "`version_cmp ${PHPMYADMIN_VER} 4.9.3 'pma9.3 ver check'`" -lt 0 ]; then
		echo "Patching phpMyAdmin to log failed authentications for BFM..."
		cd ${REALPATH}
		patch -p0 < ${WORKDIR}/patches/pma_auth_logging.patch
	fi

	PMAHTA=${REALPATH}/log/.htaccess
	if [ ! -s ${PMAHTA} ]; then
		echo '<ifModule mod_authz_core.c>'	>  ${PMAHTA}
		echo '    Require all denied'		>> ${PMAHTA}
		echo '</ifModule>'			>> ${PMAHTA}
		echo '<ifModule !mod_authz_core.c>'	>> ${PMAHTA}
		echo '    Deny from all'		>> ${PMAHTA}
		echo '</ifModule>'			>> ${PMAHTA}
	fi

	ensure_webapps_tmp

	echo "phpMyAdmin ${PHPMYADMIN_VER} installation is done."
	writeLog "dophpMyAdmin: installed version ${PHPMYADMIN_VER}"

	cd ${WORKDIR}
}

####################################################

doRemovephpMyAdmin() {
	if [ "${PHPMYADMIN_OPT}" != "no" ]; then
		do_exit 1 "Cannot remove phpMyAdmin, because it is enabled in options.conf file."
	fi

	remove_file /var/www/html/phpmyadmin
	remove_file /var/www/html/phpMyAdmin

	echo "Removing all phpMyAdmin directories from /var/www/html..."
	find /var/www/html -maxdepth 1 -name 'phpMyAdmin-*' -print -exec rm -rf {} \;

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "phpMyAdmin has been successfully removed."
	writeLog "doRemovephpMyAdmin: phpMyAdmin removed"
}

####################################################

doSquirrelmail() {
	if [ "${SQUIRRELMAIL_OPT}" != "yes" ]; then
		do_exit 1 "You cannot install Squirrelmail, because you do not have it set in options.conf file."
	fi

	ensure_webapps_logrotate

	cd ${WORKDIR}
	if [ ! -d ${WWWDIR} ]; then
		echo "${WWWDIR} does not exist."
		do_exit 0
	fi

	TARFILE=${WORKDIR}/squirrelmail-${SQUIRRELMAIL_VER}.tar.gz
	LOCALEFILE=${WORKDIR}/all_locales-${SQUIRRELMAIL_LOCALE_VER}.tar.gz
	LOGGERFILE=${WORKDIR}/squirrel_logger-${SQUIRRELMAIL_LOGGER_VER}.tar.gz
	REALPATH=${WWWDIR}/squirrelmail-${SQUIRRELMAIL_VER}
	ALIASPATH=${WWWDIR}/squirrelmail
	CONFIG=${REALPATH}/config/config.php

	if [ ! -s ${TARFILE} ]; then
		safeDownloadWithMove "${TARFILE}" "${SQUIRRELMAIL_DOWNLOADURL}"
	fi

	if [ ! -s ${TARFILE} ]; then
		echo "The squirrelmail package cannot be found. Please ensure that the paths are correct"
		do_exit 0
	fi

	if [ ! -s ${LOCALEFILE} ]; then
		safeDownloadWithMove "${LOCALEFILE}" "${SQUIRRELMAIL_LOCALE_DOWNLOADURL}"
	fi

	if [ ! -s ${LOGGERFILE} ]; then
		safeDownloadWithMove "${LOGGERFILE}" "${SQUIRRELMAIL_LOGGER_DOWNLOADURL}"
	fi

	#Extract the file
	tar xzf ${TARFILE} --no-same-owner -C ${WWWDIR}

	#install locales
	tar xzf ${LOCALEFILE} --no-same-owner -C ${REALPATH}

	#install logger
	tar xzf ${LOGGERFILE} --no-same-owner -C ${REALPATH}/plugins

	#this bit is to copy all of the preious setup to the new setup
	if [ -e ${ALIASPATH} ]; then
		cp -fR ${ALIASPATH}/data ${REALPATH}
	fi

	#link it from a fake path:
	/bin/rm -f ${ALIASPATH}
	/bin/ln -sf squirrelmail-${SQUIRRELMAIL_VER} ${ALIASPATH}
	chown -h ${APPUSER}:${APPUSER} ${ALIASPATH}

	if [ -d ${REALPATH}/plugins/squirrel_logger ]; then
		if [ ! -e ${REALPATH}/plugins/squirrel_logger/config.php ] && [ -e ${REALPATH}/plugins/squirrel_logger/config_example.php ]; then
			echo "Setting up SquirrelMail logger configuration file"
			cp -fp ${REALPATH}/plugins/squirrel_logger/config_example.php ${REALPATH}/plugins/squirrel_logger/config.php
		fi
	fi

	#install the proper config:
	if [ -e ${SQUIRREL_CONFIG} ]; then
		echo "Installing custom SquirrelMail Config: ${SQUIRREL_CONFIG}"
		/bin/cp -f ${SQUIRREL_CONFIG} ${CONFIG}
	else
		echo "Setting up SquirrelMail Config"
		/bin/cp -f ${REALPATH}/config/config_default.php ${CONFIG}

		#IMAP folders
		if [ "${WEBAPPS_INBOX_PREFIX_OPT}" = "no" ]; then
			/usr/bin/perl -pi -e "s/\$trash_folder = 'INBOX.Trash'/\$trash_folder = 'Trash'/" ${CONFIG}
			/usr/bin/perl -pi -e "s/\$sent_folder  = 'INBOX.Sent'/\$sent_folder  = 'Sent'/" ${CONFIG}
			/usr/bin/perl -pi -e "s/\$draft_folder = 'INBOX.Drafts'/\$draft_folder = 'Drafts'/" ${CONFIG}
		fi

		/usr/bin/perl -pi -e 's/\$force_username_lowercase = false/\$force_username_lowercase = true/' ${CONFIG}
		/usr/bin/perl -pi -e "s/\'example.com\';/\\$\_SERVER\[\'HTTP_HOST\'\];\nwhile \(sizeof\(explode\(\'\.\', \\$\domain\)\) \> 2) {\n\t\\$\domain = substr(\\$\domain, strpos\(\\$\domain, \'\.\'\) \+ 1\);\n\}/" ${CONFIG}
		/usr/bin/perl -pi -e 's/\$show_contain_subfolders_option = false/\$show_contain_subfolders_option = true/' ${CONFIG}

		/usr/bin/perl -pi -e 's/\$allow_thread_sort = false/\$allow_thread_sort = true/' ${CONFIG}
		/usr/bin/perl -pi -e 's/\$allow_server_sort = false/\$allow_server_sort = true/' ${CONFIG}

		/usr/bin/perl -pi -e 's#/var/local/squirrelmail/data/#/var/www/html/squirrelmail/data/#' ${CONFIG}
		/usr/bin/perl -pi -e 's#/var/local/squirrelmail/attach/#/var/www/html/squirrelmail/data/#' ${CONFIG}

		#we want it to use port 587 and use smtp auth.
		/usr/bin/perl -pi -e 's/\$smtpPort = 25/\$smtpPort = 587/' ${CONFIG}
		/usr/bin/perl -pi -e "s#\$smtp_auth_mech = \'none\'#\$smtp_auth_mech = \'login\'#" ${CONFIG}

		#enable the plugins
		/usr/bin/perl -pi -e "s/Add list of enabled plugins here/Add list of enabled plugins here\n\\$\plugins\[0\] = \'spamcop\';\n\\$\plugins\[1\] = \'filters\';\n\\$\plugins\[2\] = \'squirrel_logger\';\n\\$\plugins\[3\] = \'squirrelspell\';/" ${CONFIG}
	fi

	/usr/bin/perl -pi -e 's/\$allow_charset_search = true;/\$allow_charset_search = false;/' ${CONFIG}

	#set the permissions:
	/bin/chmod -R 755 ${REALPATH}
	chown -R ${APPUSER}:${APPUSER} ${REALPATH}
	/bin/chmod -R 770 ${REALPATH}/data

	ensure_webapps_tmp

	echo "SquirrelMail ${SQUIRRELMAIL_VER} installation is done."
	writeLog "squirrelmail ${SQUIRRELMAIL_VER} installed"
}

####################################################

doRemoveSquirrelmail() {
	if [ "${SQUIRRELMAIL_OPT}" != "no" ]; then
		do_exit 1 "Cannot remove SquirrelMail webmail, because it is enabled in options.conf file."
	fi

	remove_file /var/www/html/squirrelmail

	echo "Removing all squirrelmail directories from /var/www/html..."
	find /var/www/html -maxdepth 1 -name 'squirrelmail-*' -print -exec rm -rf {} \;

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "SquirrelMail has been successfully removed."
	writeLog "squirrelmail removed"
}

####################################################

have_sql_user() {
	SQL_USER=$1
	SQL_HOST=$2
	
	mysql --defaults-extra-file=${DA_MY_CNF} -sse "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$SQL_USER' AND host = '$SQL_HOST');" --host=${MYSQLHOST} 2>&1
}

ensure_sql_user() {
	SQL_USER=$1
	SQL_HOST=$2
	SQL_PASS=$3
	SQL_DB=$4
	
	HAVE_SQL_USER=`have_sql_user "$SQL_USER" "$SQL_HOST"`

	MYSQLV=`mysql_main`
	
	echo "Found MySQL version $MYSQLV"
	
	USE_NEW_SET_PASSWORD=1
	INDENTIFIED_WITH_STRING="IDENTIFIED"
	#for MySQL 8.0, SET PASSWORD doesn't specify PASSWORD()
	if [ "${MYSQLV}" = "5.5" ] || [ "${MYSQLV}" = "5.6" ]; then
		USE_NEW_SET_PASSWORD=0
		INDENTIFIED_WITH_STRING="IDENTIFIED"
	elif [ "${MYSQLV}" = "5.7" ]; then
		INDENTIFIED_WITH_STRING="IDENTIFIED"
	elif has_mariadb; then
		if [ "${MYSQLV}" != "10.3" ] && [ "${MYSQLV}" != "10.4" ] && [ "${MYSQLV}" != "10.5" ] && [ "${MYSQLV}" != "10.6" ]; then
			USE_NEW_SET_PASSWORD=0
		fi
		INDENTIFIED_WITH_STRING="IDENTIFIED"
	else
		INDENTIFIED_WITH_STRING="IDENTIFIED WITH mysql_native_password"
	fi

	if [ "${HAVE_SQL_USER}" != "1" ]; then
		echo "Creating User: CREATE USER '${SQL_USER}'@'${SQL_HOST}' ${INDENTIFIED_WITH_STRING} BY '${SQL_PASS}';"
		mysql --defaults-extra-file=${DA_MY_CNF} -e "CREATE USER '${SQL_USER}'@'${SQL_HOST}' ${INDENTIFIED_WITH_STRING} BY '${SQL_PASS}';" --host=${MYSQLHOST} 2>&1
	fi
	
	echo "Granting access: GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER,LOCK TABLES,INDEX,REFERENCES ON ${SQL_DB}.* TO '${SQL_USER}'@'${SQL_HOST}';"
	mysql --defaults-extra-file=${DA_MY_CNF} -e "GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER,LOCK TABLES,INDEX,REFERENCES ON ${SQL_DB}.* TO '${SQL_USER}'@'${SQL_HOST}';" --host=${MYSQLHOST} 2>&1
	
	if [ "${USE_NEW_SET_PASSWORD}" = "1" ]; then
		echo "Setting password: ALTER USER '${SQL_USER}'@'${SQL_HOST}' ${INDENTIFIED_WITH_STRING} BY '${SQL_PASS}';"
		mysql --defaults-extra-file=${DA_MY_CNF} -e "ALTER USER '${SQL_USER}'@'${SQL_HOST}' ${INDENTIFIED_WITH_STRING} BY '${SQL_PASS}';" --host=${MYSQLHOST} 2>&1
	else
		echo "Setting password: SET PASSWORD FOR '${SQL_USER}'@'${SQL_HOST}' = PASSWORD('${SQL_PASS}');"
		mysql --defaults-extra-file=${DA_MY_CNF} -e "SET PASSWORD FOR '${SQL_USER}'@'${SQL_HOST}' = PASSWORD('${SQL_PASS}');" --host=${MYSQLHOST} 2>&1
	fi
	
}

doroundcube() {
	if [ "${ROUNDCUBE_OPT}" != "yes" ]; then
		do_exit 1 "You cannot install RoundCube webmail, because you do not have it set in options.conf file."
	fi

	addWebappsUser

	MYSQLV="`mysql_main`"
	OLD_MYSQL=false

	if [ "`version_cmp ${ROUNDCUBE_VER} 1.5.0 'RC 1.5.0 MySQL cersion check'`" -ge 0 ]; then
		if has_mariadb; then
			if [ "${MYSQLV}" = "5.5" ] || [ "${MYSQLV}" = "10.0" ] || [ "${MYSQLV}" = "10.1" ]; then
				OLD_MYSQL=true
			fi
		elif [ "${MYSQLV}" = "5.5" ] || [ "${MYSQLV}" = "5.6" ]; then
			OLD_MYSQL=true
		fi
	fi
	if ${OLD_MYSQL}; then
		if ! grep -m1 -q 'innodb_file_format=Barracuda' /etc/my.cnf 2>/dev/null; then
			echo "${boldon}RoundCube ${ROUNDCUBE_VER} requires newer version of ${MYSQLNAME} than ${MYSQLV}, alternatively, the following my.cnf configuration can be set:${boldoff}"
			echo "innodb_large_prefix=1"
			echo "innodb_file_per_table=1"
			echo "innodb_file_format=Barracuda"
			exit 1
		fi
	fi
	ensure_webapps_logrotate

	initMySQL

	if [ "`version_cmp ${ROUNDCUBE_VER} 1.3.0 'RC 1.3.0 php 5.3 check'`" -ge 0 ]; then
		#RC 1.3.0+ will not run on php 5.3 or older.
		if [ "${PHP1_RELEASE_OPT}" = "5.3" ]; then
			echo "${boldon}RoundCube ${ROUNDCUBE_VER} cannot run on php 5.3 or older. Not installing it.${boldoff}"
			return
		fi
	fi
	if [ "`version_cmp ${ROUNDCUBE_VER} 1.5.3 'RC 1.5.3 php 5.6 check'`" -ge 0 ]; then
		#RC 1.5.3+ will not run on php 5.5 or older.
		if [ "${PHP1_RELEASE_OPT}" = "5.4" ] || [ "${PHP1_RELEASE_OPT}" = "5.5" ]; then
			echo "${boldon}RoundCube ${ROUNDCUBE_VER} cannot run on php 5.5 or older. Not installing it.${boldoff}"
			return
		fi
	fi
	if [ "`version_cmp ${ROUNDCUBE_VER} 1.6.0 'RC 1.6.0 php 7.3 check'`" -ge 0 ]; then
		#RC 1.6.0+ will not run on php 7.3 or older.
		if [ "${PHP1_RELEASE_OPT}" = "5.6" ] || [ "${PHP1_RELEASE_OPT}" = "7.0" ] || [ "${PHP1_RELEASE_OPT}" = "7.1" ] || [ "${PHP1_RELEASE_OPT}" = "7.2" ]; then
			echo "${boldon}RoundCube ${ROUNDCUBE_VER} cannot run on php 7.3 or older. Not installing it.${boldoff}"
			return
		fi
	fi

	cd ${WORKDIR}
	TARFILE=${WORKDIR}/roundcubemail-${ROUNDCUBE_VER}.tar.gz
	REALPATH=${WWWDIR}/roundcubemail-${ROUNDCUBE_VER}
	ALIASPATH=${WWWDIR}/roundcube

	if [ "${ROUNDCUBE_MAJOR_VER}" != "0" ]; then
		if [ -s ${ROUNDCUBE_CONFIG_OLD} ] || [ -s ${ROUNDCUBE_CONFIG_DB_OLD} ]; then
			echo "Please remove RoundCube 0.x custom configuration files if you would like to upgrade it. The following files should not be used anymore: ${ROUNDCUBE_CONFIG_OLD}, ${ROUNDCUBE_CONFIG_DB_OLD}. Please use config.inc.php as a new custom RoundCube configuration file."
			return
		fi
	fi
	
	# variables for the database:
	ROUNDCUBE_DB=da_roundcube
	ROUNDCUBE_DB_USER=da_roundcube
	ROUNDCUBE_DB_PASS=`random_pass`
	ROUNDCUBE_DES_KEY=`random_pass 24`
	ROUNDCUBE_MY_CNF=${REALPATH}/config/my.cnf
	safeDownloadWithMove "${WORKDIR}/roundcubemail-${ROUNDCUBE_VER}.tar.gz" "${ROUNDCUBE_DOWNLOADURL}"

	if [ ! -s ${TARFILE} ]; then
		echo "Cannot download roundcubemail-${ROUNDCUBE_VER}"
		do_exit 0
	fi

	#Extract the file
	tar xzf ${TARFILE} --no-same-owner -C ${WWWDIR}

	if [ ! -e ${REALPATH} ]; then
		do_exit 1 "Directory ${REALPATH} does not exist"
	fi

	if [ -e ${ALIASPATH} ]; then
		if [ -d ${ALIASPATH}/logs ]; then
			cp -fR ${ALIASPATH}/logs ${REALPATH} >/dev/null 2>&1
		fi
		if [ -d ${ALIASPATH}/temp ]; then
			cp -fR ${ALIASPATH}/temp ${REALPATH} >/dev/null 2>&1
		fi
	fi	

	#link it from a fake path:
	/bin/rm -f ${ALIASPATH}
	/bin/ln -sf roundcubemail-${ROUNDCUBE_VER} ${ALIASPATH}
	chown -h ${APPUSER}:${APPUSER} ${ALIASPATH}
	cd ${REALPATH}

	if [ -d logs ]; then
		chmod 710 logs
	fi

	if [ ${ROUNDCUBE_MAJOR_VER} -eq 0 ]; then
		EDIT_CONFIG=main.inc.php
		CONFIG_DIST=main.inc.php.dist
		EDIT_DB=db.inc.php
		DB_DIST=db.inc.php.dist
	else
		EDIT_CONFIG=config.inc.php
		CONFIG_DIST=config.inc.php.sample
		EDIT_DB=${EDIT_CONFIG}
		DB_DIST=${CONFIG_DIST}
	fi

	MYSQLSHOW=/usr/bin/mysqlshow
	if [ ! -e ${MYSQLSHOW} ]; then
            MYSQLSHOW=/usr/local/mysql/bin/mysqlshow
	fi
	
	#insert data to mysql and create database/user for roundcube:
	if ! ${MYSQLSHOW} --defaults-extra-file=${DA_MY_CNF} --host=${MYSQLHOST} | grep -m1 -q ' da_roundcube '; then
		if [ -d SQL ]; then
			echo "Inserting data to mysql and creating database/user for roundcube..."
			mysql --defaults-extra-file=${DA_MY_CNF} -e "CREATE DATABASE ${ROUNDCUBE_DB};" --host=${MYSQLHOST} 2>&1

			ensure_sql_user "${ROUNDCUBE_DB_USER}" "${MYSQL_ACCESS_HOST}" "${ROUNDCUBE_DB_PASS}" "${ROUNDCUBE_DB}"

			if [ "${MYSQLHOST}" != "localhost" ]; then
				for access_host_ip in `grep '^access_host.*=' ${DA_MYSQL} | cut -d= -f2`; do {
					ensure_sql_user "${ROUNDCUBE_DB_USER}" "${access_host_ip}" "${ROUNDCUBE_DB_PASS}" "${ROUNDCUBE_DB}"
				}; done
			fi

			rm -f ${ROUNDCUBE_MY_CNF}
			ensure_my_cnf ${ROUNDCUBE_MY_CNF} "${ROUNDCUBE_DB_USER}" "${ROUNDCUBE_DB_PASS}"
			mysql --defaults-extra-file=${ROUNDCUBE_MY_CNF} -e "use ${ROUNDCUBE_DB}; source SQL/mysql.initial.sql;" --host=${MYSQLHOST} 2>&1

			echo "Database created, ${ROUNDCUBE_DB_USER} password is ${ROUNDCUBE_DB_PASS}"
		else
			echo "Cannot find SQL directory in roundcubemail-${ROUNDCUBE_VER}"
			do_exit 0
		fi
	else
		if [ -e ${ROUNDCUBE_CONFIG_DB} ]; then
			COUNT_MYSQL=`grep -m1 -c 'mysql://' ${ROUNDCUBE_CONFIG_DB}`
			if [ ${COUNT_MYSQL} -gt 0 ]; then
				PART1="`grep -m1 "\$config\['db_dsnw'\]" ${ROUNDCUBE_CONFIG_DB} | awk '{print $3}' | cut -d\@ -f1 | cut -d'/' -f3`"
				ROUNDCUBE_DB_USER="`echo ${PART1} | cut -d\: -f1`"
				ROUNDCUBE_DB_PASS="`echo ${PART1} | cut -d\: -f2`"
				PART2="`grep -m1 "\$config\['db_dsnw'\]" ${ROUNDCUBE_CONFIG_DB} | awk '{print $3}' | cut -d\@ -f2 | cut -d\' -f1`"
				MYSQL_ACCESS_HOST="`echo ${PART2} | cut -d'/' -f1`"
				ROUNDCUBE_DB="`echo ${PART2} | cut -d'/' -f2`"
			fi
		fi

		ensure_sql_user "${ROUNDCUBE_DB_USER}" "${MYSQL_ACCESS_HOST}" "${ROUNDCUBE_DB_PASS}" "${ROUNDCUBE_DB}"
		
		if [ "${MYSQLHOST}" != "localhost" ]; then
			for access_host_ip in `grep '^access_host.*=' ${DA_MYSQL} | cut -d= -f2`; do {
				ensure_sql_user "${ROUNDCUBE_DB_USER}" "${access_host_ip}" "${ROUNDCUBE_DB_PASS}" "${ROUNDCUBE_DB}"
			}; done
		fi

		#in case anyone uses it for backups
		rm -f ${ROUNDCUBE_MY_CNF}
		ensure_my_cnf ${ROUNDCUBE_MY_CNF} "${ROUNDCUBE_DB_USER}" "${ROUNDCUBE_DB_PASS}"
	fi

	#password plugin pre-configuration
	if [ -e ${REALPATH}/plugins/password ]; then
		cd ${REALPATH}/plugins/password
		if [ ! -e config.inc.php ]; then
			cp config.inc.php.dist config.inc.php
		fi

		/usr/bin/perl -pi -e "s|\['password_driver'] = 'sql'|\['password_driver'] = 'directadmin'|" config.inc.php > /dev/null

		if [ -e /usr/local/directadmin/directadmin ]; then
			DAPORT=`/usr/local/directadmin/directadmin c | grep -m1 -e '^port=' | cut -d= -f2`
			if [ "${DAPORT}" != "" ]; then
				/usr/bin/perl -pi -e "s|\['password_directadmin_port'] = .*$|\['password_directadmin_port'] = ${DAPORT};|" config.inc.php > /dev/null
			fi

			DASSL=`/usr/local/directadmin/directadmin c | grep -m1 -e '^ssl=' | cut -d= -f2`
			DAHOST=`/usr/local/directadmin/directadmin c | grep -m1 -e '^force_hostname=' | cut -d= -f2`
			if [ -z "${DAHOST}" ]; then
				DAHOST="localhost"
			fi

			if [ "$DASSL" -eq 1 ]; then
				/usr/bin/perl -pi -e "s|\['password_directadmin_host'] = 'tcp://localhost'|\['password_directadmin_host'] = 'ssl://${DAHOST}'|" config.inc.php > /dev/null
			elif [ "${DAHOST}" != "localhost" ]; then
				/usr/bin/perl -pi -e "s|\['password_directadmin_host'] = 'tcp://localhost'|\['password_directadmin_host'] = 'tcp://${DAHOST}'|" config.inc.php > /dev/null
			fi
		fi
		cd ${REALPATH}
	fi

	#pigeonhole plugin pre-configuration
	if [ "${PIGEONHOLE_OPT}" = "yes" ]; then
		if [ -d ${REALPATH}/plugins/managesieve ]; then
			cd ${REALPATH}/plugins/managesieve
			if [ ! -e config.inc.php ]; then
				cp config.inc.php.dist config.inc.php
			fi
			/usr/bin/perl -pi -e "s|\['managesieve_port'] = null|\['managesieve_port'] = 4190|" config.inc.php > /dev/null
			/usr/bin/perl -pi -e "s|\['managesieve_vacation'\] = 0|\['managesieve_vacation'\] = 1|g" config.inc.php > /dev/null
			cd ${REALPATH}
		fi
	fi

	#Cleanup config
	rm -f ${REALPATH}/config/${EDIT_CONFIG}

	#install the proper config:
	if [ -d ../roundcube ]; then

		echo "Editing roundcube configuration..."
		cd ${REALPATH}/config

		if [ -e ${ROUNDCUBE_CONFIG} ]; then
			echo "Installing custom RoundCube Config: ${ROUNDCUBE_CONFIG}"
			cp -f ${ROUNDCUBE_CONFIG} ${EDIT_CONFIG}
		fi

		if [ -e ${ROUNDCUBE_CONFIG_DB} ]; then
			if [ ! -e ${EDIT_DB} ]; then
				/bin/cp -f ${ROUNDCUBE_CONFIG_DB} ${EDIT_DB}
			fi
			COUNT_MYSQL=`grep -m1 -c 'mysql://' ${ROUNDCUBE_CONFIG_DB}`
			if [ ${COUNT_MYSQL} -eq 0 ]; then
				echo "\$config['db_dsnw'] = 'mysql://${ROUNDCUBE_DB_USER}:${ROUNDCUBE_DB_PASS}@${MYSQLHOST}/${ROUNDCUBE_DB}';" >> ${EDIT_DB}
			fi
		else
			if [ ! -e ${EDIT_DB} ]; then
				/bin/cp -f ${DB_DIST} ${EDIT_DB}
				/usr/bin/perl -pi -e "s|mysql://roundcube:pass\@localhost/roundcubemail|mysql://${ROUNDCUBE_DB_USER}:\\Q${ROUNDCUBE_DB_PASS}\\E\@${MYSQLHOST}/${ROUNDCUBE_DB}|" ${EDIT_DB} > /dev/null
				/usr/bin/perl -pi -e "s/\'mdb2\'/\'db\'/" ${EDIT_DB} > /dev/null
			fi
		fi

		SPAM_INBOX_PREFIX_OPT=$(${DA_BIN} config-get spam_inbox_prefix)
		SPAM_FOLDER="INBOX.spam"
		if [ "${SPAM_INBOX_PREFIX_OPT}" = "0" ]; then
			SPAM_FOLDER="Junk"
		fi

		/usr/bin/perl -pi -e "s|rcmail-\!24ByteDESkey\*Str|\\Q${ROUNDCUBE_DES_KEY}\\E|" ${EDIT_CONFIG}
		if [ ! -e ${ROUNDCUBE_CONFIG} ]; then
			if [ ${ROUNDCUBE_MAJOR_VER} -eq 0 ]; then
				/usr/bin/perl -pi -e "s|\['default_host'] = ''|\['default_host'] = 'localhost'|" ${EDIT_CONFIG} > /dev/null

				#IMAP folders
				if [ "${WEBAPPS_INBOX_PREFIX_OPT}" = "yes" ]; then
					/usr/bin/perl -pi -e "s|\['drafts_mbox'] = 'Drafts'|\['drafts_mbox'] = 'INBOX.Drafts'|" ${EDIT_CONFIG} > /dev/null
					/usr/bin/perl -pi -e "s|\['sent_mbox'] = 'Sent'|\['sent_mbox'] = 'INBOX.Sent'|" ${EDIT_CONFIG} > /dev/null
					/usr/bin/perl -pi -e "s|\['trash_mbox'] = 'Trash'|\['trash_mbox'] = 'INBOX.Trash'|" ${EDIT_CONFIG} > /dev/null
					/usr/bin/perl -pi -e "s|\['default_imap_folders'] = array\('INBOX', 'Drafts', 'Sent', 'Junk', 'Trash'\)|\['default_imap_folders'] = array\('INBOX', 'INBOX.Drafts', 'INBOX.Sent', '${SPAM_FOLDER}', 'INBOX.Trash'\)|" ${EDIT_CONFIG} > /dev/null
					/usr/bin/perl -pi -e "s|\['default_folders'] = array\('INBOX', 'Drafts', 'Sent', 'Junk', 'Trash'\)|\['default_folders'] = array\('INBOX', 'INBOX.Drafts', 'INBOX.Sent', '${SPAM_FOLDER}', 'INBOX.Trash'\)|" ${EDIT_CONFIG} > /dev/null
				else
					/usr/bin/perl -pi -e "s|\['default_imap_folders'] = array\('INBOX', 'Drafts', 'Sent', 'Junk', 'Trash'\)|\['default_imap_folders'] = array\('INBOX', 'Drafts', 'Sent', '${SPAM_FOLDER}', 'Trash'\)|" ${EDIT_CONFIG} > /dev/null
					/usr/bin/perl -pi -e "s|\['default_folders'] = array\('INBOX', 'Drafts', 'Sent', 'Junk', 'Trash'\)|\['default_folders'] = array\('INBOX', 'Drafts', 'Sent', '${SPAM_FOLDER}', 'Trash'\)|" ${EDIT_CONFIG} > /dev/null
				fi

				if [ "${SPAM_INBOX_PREFIX_OPT}" = "1" ]; then
					/usr/bin/perl -pi -e "s|\['junk_mbox'] = 'Junk'|\['junk_mbox'] = 'INBOX.spam'|" ${EDIT_CONFIG} > /dev/null
				fi

				#smtp stuff
				/usr/bin/perl -pi -e "s|\['smtp_port'] = 25|\['smtp_port'] = 587|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['smtp_server'] = ''|\['smtp_server'] = 'localhost'|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['smtp_user'] = ''|\['smtp_user'] = '%u'|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['smtp_pass'] = ''|\['smtp_pass'] = '%p'|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['smtp_auth_type'] = ''|\['smtp_auth_type'] = 'LOGIN'|" ${EDIT_CONFIG} > /dev/null

				/usr/bin/perl -pi -e "s|\['create_default_folders'] = .*;|\['create_default_folders'] = true;|" ${EDIT_CONFIG} > /dev/null

				/usr/bin/perl -pi -e "s|\['login_lc'] = 0;|\['login_lc'] = 2;|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['login_autocomplete'] = 0;|\['login_autocomplete'] = 2;|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['quota_zero_as_unlimited'] = false;|\['quota_zero_as_unlimited'] = true;|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['enable_spellcheck'] = true;|\['enable_spellcheck'] = false;|" ${EDIT_CONFIG} > /dev/null
			else
				#default_host is set to localhost by default in RC 1.0.0, so we don't echo it to the file

				#These ones are already in config.inc.php.sample file, so we just use perl-regex to change them
				/usr/bin/perl -pi -e "s|\['smtp_port'] = 25|\['smtp_port'] = 587|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['smtp_server'] = ''|\['smtp_server'] = 'localhost'|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['smtp_user'] = ''|\['smtp_user'] = '%u'|" ${EDIT_CONFIG} > /dev/null
				/usr/bin/perl -pi -e "s|\['smtp_pass'] = ''|\['smtp_pass'] = '%p'|" ${EDIT_CONFIG} > /dev/null

				#Changing default options, that are set in defaults.inc.php
				#IMAP folders

				if [ "${WEBAPPS_INBOX_PREFIX_OPT}" = "yes" ]; then
					echo "\$config['drafts_mbox'] = 'INBOX.Drafts';" >> ${EDIT_CONFIG}
					echo "\$config['junk_mbox'] = '${SPAM_FOLDER}';" >> ${EDIT_CONFIG}
					echo "\$config['sent_mbox'] = 'INBOX.Sent';" >> ${EDIT_CONFIG}
					echo "\$config['trash_mbox'] = 'INBOX.Trash';" >> ${EDIT_CONFIG}
					echo "\$config['default_folders'] = array('INBOX', 'INBOX.Drafts', 'INBOX.Sent', '${SPAM_FOLDER}', 'INBOX.Trash');" >> ${EDIT_CONFIG}
				else
					echo "\$config['junk_mbox'] = '${SPAM_FOLDER}';" >> ${EDIT_CONFIG}
					echo "\$config['default_folders'] = array('INBOX', 'Drafts', 'Sent', '${SPAM_FOLDER}', 'Trash');" >> ${EDIT_CONFIG}
				fi

				HN_T=${HOSTNAME}
				echo "\$config['smtp_helo_host'] = '${HN_T}';" >> ${EDIT_CONFIG}

				echo "\$config['smtp_auth_type'] = 'LOGIN';" >> ${EDIT_CONFIG}
				echo "\$config['create_default_folders'] = true;" >> ${EDIT_CONFIG}
				echo "\$config['protect_default_folders'] = true;" >> ${EDIT_CONFIG}
				echo "\$config['login_autocomplete'] = 2;" >> ${EDIT_CONFIG}
				echo "\$config['quota_zero_as_unlimited'] = true;" >> ${EDIT_CONFIG}
				echo "\$config['enable_spellcheck'] = false;" >> ${EDIT_CONFIG}
				echo "\$config['email_dns_check'] = true;" >> ${EDIT_CONFIG}
				if grep -q '^recipients_max' /etc/exim.conf; then
					RECIPIENTS_MAX="`grep -m1 '^recipients_max' /etc/exim.conf | cut -d= -f2 | tr -d ' '`"
					echo "\$config['max_recipients'] = ${RECIPIENTS_MAX};" >> ${EDIT_CONFIG}
					echo "\$config['max_group_members'] = ${RECIPIENTS_MAX};" >> ${EDIT_CONFIG}
				fi

				if [ ! -s mime.types ]; then
					if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
						if [ -s /etc/httpd/conf/mime.types ]; then
							if grep -m1 -q 'application/java-archive' /etc/httpd/conf/mime.types; then
								cp -f /etc/httpd/conf/mime.types ./mime.types
							fi
						fi
					fi
				fi
				if [ ! -s mime.types ]; then
					safeDownloadWithMove "${ALIASPATH}/config/mime.types" "https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types"
				fi
				echo "\$config['mime_types'] = '${ALIASPATH}/config/mime.types';" >> ${EDIT_CONFIG}
			fi
			
			#password plugin
			if [ -e ${REALPATH}/plugins/password ]; then
				if [ ${ROUNDCUBE_MAJOR_VER} -eq 0 ]; then
					/usr/bin/perl -pi -e "s|\['plugins'] = array\(\);|\['plugins'] = array\('password'\);|" ${EDIT_CONFIG} > /dev/null
				else
					/usr/bin/perl -pi -e "s|\['plugins'] = array\(\n|\['plugins'] = array\(\n    'password',\n|" ${EDIT_CONFIG} > /dev/null
					/usr/bin/perl -pi -e "s|\['plugins'] = \[\n|\['plugins'] = \[\n    'password',\n|" ${EDIT_CONFIG} > /dev/null
				fi
				cd ${REALPATH}/config
			fi

			#pigeonhole plugin
			if [ "${PIGEONHOLE_OPT}" = "yes" ]; then
				if [ -d ${REALPATH}/plugins/managesieve ]; then
					if [ ${ROUNDCUBE_MAJOR_VER} -eq 0 ]; then
						/usr/bin/perl -pi -e "s|\['plugins'] = array\('password'\);|\['plugins'] = array\('password','managesieve'\);|" ${EDIT_CONFIG} > /dev/null
					else
						if [ `grep -m1 -c "'managesieve'" ${EDIT_CONFIG}` -eq 0 ]; then
							/usr/bin/perl -pi -e "s|\['plugins'] = array\(\n|\['plugins'] = array\(\n    'managesieve',\n|" ${EDIT_CONFIG} > /dev/null
							/usr/bin/perl -pi -e "s|\['plugins'] = \[\n|\['plugins'] = \[\n    'managesieve',\n|" ${EDIT_CONFIG} > /dev/null
						fi
					fi
					cd ${REALPATH}/config
				fi
			fi
		fi

		#SSO plugin
		if [ -x ${DA_BIN} ] && [ -s ${DACONF_FILE} ]; then
			if ${DA_BIN} c | grep -m1 -q '^one_click_webmail_login=1$'; then
				ROUNDCUBE_DIRECT_LOGIN_VER=${versions_txt["rc_direct_login"]}
				ROUNDCUBE_DIRECT_LOGIN="roundcube_direct_login-${ROUNDCUBE_DIRECT_LOGIN_VER}.tar.gz"
				cd ${REALPATH}
				safeDownloadWithMove "${REALPATH}/${ROUNDCUBE_DIRECT_LOGIN}" "${WEBPATH_SERVICES}/all/auto_login/roundcube/${ROUNDCUBE_DIRECT_LOGIN}"
				tar xzf ${ROUNDCUBE_DIRECT_LOGIN}
				chown -R webapps:webapps direct_login
				chmod 711 direct_login
				chmod 700 direct_login/tokens
				chmod 644 direct_login/index.php
				cd ${REALPATH}/config
			elif [ -d ${REALPATH}/direct_login ]; then
				rm -rf ${REALPATH}/direct_login
			fi
		fi

		if [ -d ${ROUNDCUBE_PLUGINS} ]; then
			echo "Copying files from ${ROUNDCUBE_PLUGINS} to ${REALPATH}/plugins"
			cp -Rpf ${ROUNDCUBE_PLUGINS}/* ${REALPATH}/plugins
		fi

		if [ -d ${ROUNDCUBE_SKINS} ]; then
			echo "Copying files from ${ROUNDCUBE_SKINS} to ${REALPATH}/skins"
			cp -Rpf ${ROUNDCUBE_SKINS}/* ${REALPATH}/skins
		fi
		
		if [ -d ${ROUNDCUBE_VENDOR} ]; then
			echo "Copying files from ${ROUNDCUBE_VENDOR} to ${REALPATH}/vendor"
			cp -Rpf ${ROUNDCUBE_VENDOR}/* ${REALPATH}/vendor
		fi

		if [ -d ${ROUNDCUBE_PROGRAM} ]; then
			echo "Copying files from ${ROUNDCUBE_PROGRAM} to ${REALPATH}/program"
			cp -Rpf ${ROUNDCUBE_PROGRAM}/* ${REALPATH}/program
		fi

		if [ -e ${ROUNDCUBE_COMPOSER} ]; then
			echo "Copying composer.json file from ${ROUNDCUBE_COMPOSER} to ${REALPATH}/composer.json"
			cp -Rpf ${ROUNDCUBE_COMPOSER} ${REALPATH}/composer.json
		fi
		
		if [ -e ${ROUNDCUBE_HTACCESS} ]; then
			echo "Copying .htaccess file from ${ROUNDCUBE_HTACCESS} to ${REALPATH}/.htaccess"
			cp -pf ${ROUNDCUBE_HTACCESS} ${REALPATH}/.htaccess
		fi

		echo "Roundcube ${ROUNDCUBE_VER} has been installed successfully."
		writeLog "RoundCube ${ROUNDCUBE_VER} installed"
	fi

	#systems with "system()" in disable_functions need to use no php.ini:
	if [ "`have_php_system`" = "0" ]; then
		perl -pi -e 's#^\#\!/usr/bin/env php#\#\!/usr/local/bin/php \-n#' ${REALPATH}/bin/update.sh
	fi

	#systems with suhosin cannot have PHP memory_limit set to -1, we need not to load suhosin for RoundCube .sh scripts
	if [ "${SUHOSIN_OPT}" = "yes" ]; then
		perl -pi -e 's#^\#\!/usr/bin/env php#\#\!/usr/local/bin/php \-n#' ${REALPATH}/bin/msgimport.sh
		perl -pi -e 's#^\#\!/usr/bin/env php#\#\!/usr/local/bin/php \-n#' ${REALPATH}/bin/indexcontacts.sh
		perl -pi -e 's#^\#\!/usr/bin/env php#\#\!/usr/local/bin/php \-n#' ${REALPATH}/bin/msgexport.sh
	fi

	#set the permissions:
	chown -R ${APPUSER}:${APPUSER} ${REALPATH}

	#update if needed
	${REALPATH}/bin/update.sh '--version=?'

	#drop alias column if it's still there
	if mysql --defaults-extra-file=${DA_MY_CNF} da_roundcube -e "SHOW COLUMNS FROM da_roundcube.users LIKE 'alias';" --host=${MYSQLHOST} -sss 2>&1 | grep -m1 -q '^alias'; then
		mysql --defaults-extra-file=${DA_MY_CNF} da_roundcube -e "ALTER TABLE da_roundcube.users DROP COLUMN da_roundcube.users.alias;"--host=${MYSQLHOST} -sss 2>&1
	fi

	#cleanup
	rm -rf ${ALIASPATH}/installer

	#secure configuration file
	if [ -s ${EDIT_DB} ]; then
		chmod 440 ${EDIT_DB}
		chown ${APPUSER}:${APPGROUP} ${EDIT_DB}
	fi

	RC_HTACCESS=${REALPATH}/.htaccess
	if [ -s "${RC_HTACCESS}" ]; then
		if grep -m1 -q upload_max_filesize ${RC_HTACCESS}; then
			perl -pi -e 's/^php_value   upload_max_filesize/#php_value   upload_max_filesize/' ${RC_HTACCESS}
			perl -pi -e 's/^php_value   post_max_size/#php_value   post_max_size/' ${RC_HTACCESS}
            perl -pi -e 's/^php_value   memory_limit/#php_value   memory_limit/' ${RC_HTACCESS}
		fi

		perl -pi -e 's/FollowSymLinks/SymLinksIfOwnerMatch/' ${RC_HTACCESS}
	fi

	ensure_webapps_tmp
	
	if [ "${OPCACHE_OPT}" = "yes" ]; then
		if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
			echo "Reloading php-fpm${PHP1_SHORTRELEASE}."
			control_service php-fpm${PHP1_SHORTRELEASE} reload
		elif [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			echo "Reloading apache."
			control_service httpd reload
		elif [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
			echo "Reloading litespeed."
			control_service litespeed reload
		fi
	fi

	cd ${WORKDIR}
}

####################################################

doRemoveRoundcube() {
	if [ "${ROUNDCUBE_OPT}" != "no" ]; then
		do_exit 1 "Cannot remove RoundCube webmail, because it is enabled in options.conf file."
	fi

	initMySQL

	# variables for the database:
	ROUNDCUBE_DB=da_roundcube
	ROUNDCUBE_DB_USER=da_roundcube

	#Removing RoundCube database and database user
	if [ -d $MYSQL_DATA/${ROUNDCUBE_DB} ]; then
		echo "Dropping database ${ROUNDCUBE_DB} and database user ${ROUNDCUBE_DB_USER}..."
		mysql --defaults-extra-file=${DA_MY_CNF} -e "DROP DATABASE ${ROUNDCUBE_DB};" --host=${MYSQLHOST} 2>/dev/null
		mysql --defaults-extra-file=${DA_MY_CNF} -e "DROP USER '${ROUNDCUBE_DB_USER}'@'${MYSQL_ACCESS_HOST}';" --host=${MYSQLHOST} 2>/dev/null
		if [ "${MYSQLHOST}" != "localhost" ]; then
			for access_host_ip in `grep '^access_host.*=' ${DA_MYSQL} | cut -d= -f2`; do { 
				mysql --defaults-extra-file=${DA_MY_CNF} -e "DROP USER '${ROUNDCUBE_DB_USER}'@'${ROUNDCUBE_DB_USER}'@'${access_host_ip}';" --host=${MYSQLHOST} 2>&1
			}; done
		fi
	fi

	remove_file /var/www/html/roundcube

	echo "Removing all roundcubemail directories from /var/www/html..."
	find /var/www/html -maxdepth 1 -name 'roundcubemail-*' -print -exec rm -rf {} \;

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "RoundCube webmail has been successfully removed."
	writeLog "RoundCube removed"
}

ensurepopb4smtp(){
	#pop before smtp
	if [ ! -s /etc/systemd/system/da-popb4smtp.service ]; then
		cp -f ${WORKDIR}/configure/systemd/da-popb4smtp.service /etc/systemd/system/da-popb4smtp.service
		systemctl daemon-reload
		systemctl enable da-popb4smtp.service
		systemctl start da-popb4smtp.service
	fi
	set_service da-popb4smtp ON
}

createEtcVirtual(){
	addUserGroup mail mail 12 12
	addToAccess mail
	VIRTUAL="/etc/virtual"
	if [ ! -d ${VIRTUAL} ]; then
		mkdir -p ${VIRTUAL}
	fi
	chown -f mail ${VIRTUAL}
	chgrp -f mail ${VIRTUAL}
	chmod 711 ${VIRTUAL}

	if ! grep -q "^${HOSTNAME}$" ${VIRTUAL}/domains 2>/dev/null; then
		echo "${HOSTNAME}" >> ${VIRTUAL}/domains
	fi

	if [ ! -s ${VIRTUAL}/limit ]; then
		echo "1000" > ${VIRTUAL}/limit
		chmod 644 ${VIRTUAL}/limit
		chown -f mail:mail ${VIRTUAL}/limit
	fi
	if [ ! -s ${VIRTUAL}/limit_unknown ]; then
		echo "0" > ${VIRTUAL}/limit_unknown
		chmod 644 ${VIRTUAL}/limit_unknown
		chown -f mail:mail ${VIRTUAL}/limit_unknown
	fi
	if [ ! -s ${VIRTUAL}/user_limit ]; then
		echo "200" > ${VIRTUAL}/user_limit
		chmod 644 ${VIRTUAL}/user_limit
		chown -f mail:mail ${VIRTUAL}/user_limit
	fi
	if [ ! -d ${VIRTUAL}/usage ]; then
		mkdir -p ${VIRTUAL}/usage
	fi
	chmod 750 ${VIRTUAL}/usage
	chown -f mail:mail ${VIRTUAL}/usage

	for i in domains domainowners blacklist_domains whitelist_from use_rbl_domains bad_sender_hosts bad_sender_hosts_ip blacklist_senders whitelist_domains whitelist_hosts whitelist_hosts_ip whitelist_senders skip_av_domains skip_rbl_domains; do
        	if [ ! -e ${VIRTUAL}/$i ]; then
				touch ${VIRTUAL}/$i
			fi
			chmod 640 ${VIRTUAL}/$i
			chown -f mail:mail ${VIRTUAL}/$i
	done
}

ensureBuildPackages() {
	install_debs g++ make
	install_rpms gcc-c++ make
}

doExim() {
	if [ "${EXIM_OPT}" != "yes" ]; then
		do_exit 1 "You cannot update Exim, because you do not have it set in options.conf file."
	fi
	ensureBuildPackages
	install_debs libssl-dev libpcre2-dev libperl-dev libdb-dev
	install_rpms openssl-devel pcre2-devel perl-ExtUtils-Embed libdb-devel

	createEtcVirtual

	V_U_RBL_D=${VIRTUAL}/use_rbl_domains
	if [ -f ${V_U_RBL_D} ] && [ ! -s ${V_U_RBL_D} ]; then
		rm -f ${V_U_RBL_D}
		ln -s domains ${V_U_RBL_D}
		chown -h mail:mail ${V_U_RBL_D}
	fi

	safeDownloadWithMove "${WORKDIR}/exim-${EXIM_VER}.tar.gz" "${EXIM_DOWNLOADURL}"

	ensurepopb4smtp

	pkill -x sendmail 2> /dev/null

	if [ -s /etc/inetd.conf ]; then
		if grep -m1 -q '^pop' /etc/inetd.conf; then
			perl -pi -e 's/^pop/\#pop/' /etc/inetd.conf
			pkill -x inetd
		fi
	fi
	if distro_is_debian; then
		if ! has_debs_installed da_exim && ! has_debs_installed da-exim; then
			install_debs equivs
			if [ -x /usr/bin/equivs-build ]; then
				echo 'Package: da-exim' > da-exim.equivs
				echo 'Maintainer: JBMC Software <no-reply@directadmin.com>' >> da-exim.equivs
				echo 'Architecture: any' >> da-exim.equivs
				echo 'Provides: mail-transport-agent' >> da-exim.equivs
				echo 'Replaces: mail-transport-agent, exim4-base' >> da-exim.equivs
				echo 'Description: Dummy package to replace dependencies' >> da-exim.equivs
				/usr/bin/equivs-build da-exim.equivs >/dev/null 2>&1
			fi
		fi
		if [ -s da-exim_1.0_amd64.deb ]; then
			dpkg -r --force-all exim exim4 exim4-base exim4-config exim4-daemon-light exim4-config-2 exim4-daemon-heavy rmail sendmail-bin sendmail mail-transport-agent postfix ssmtp courier-authdaemon courier-authlib courier-authlib-userdb courier-base courier-imap courier-imap-ssl courier-maildrop courier-pop courier-pop-ssl courier-ssl dovecot-core dovecot-imapd 2> /dev/null
			dpkg -P exim exim4 exim4-base exim4-config exim4-daemon-light exim4-config-2 exim4-daemon-heavy rmail sendmail-bin sendmail mail-transport-agent postfix ssmtp courier-authdaemon courier-authlib courier-authlib-userdb courier-base courier-imap courier-imap-ssl courier-maildrop courier-pop courier-pop-ssl courier-ssl dovecot-core dovecot-imapd 2> /dev/null
			dpkg -i da-exim_1.0_amd64.deb 2>/dev/null
			if [ -s da-exim.equivs ]; then
				rm -f da-exim.equivs
			fi
			rm -f da-exim_1.0_amd64.deb 2> /dev/null
		fi
	else
		rpm -e --nodeps sendmail 2> /dev/null
		rpm -e --nodeps postfix 2> /dev/null
		rpm -e --nodeps dovecot 2> /dev/null
		rpm -e --nodeps courier-imap 2> /dev/null
	fi

	install_rpms libspf2-devel
	install_debs libspf2-dev

	if [ ! -d /var/log/exim ]; then
		mkdir /var/log/exim
		chmod 700 /var/log/exim
	fi
	chown mail:mail /var/log/exim
	if [ -d /var/spool/exim ] && [ ! -e /usr/sbin/exim ]; then
		chown -R mail:mail /var/spool/exim
	fi

	cd ${WORKDIR}
	FILE=${WORKDIR}/exim-${EXIM_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ..."
	tar xzf ${FILE} --no-same-owner
	echo "Done."

	cd exim-${EXIM_VER}

	if [ -x /usr/sbin/opendmarc ] && [ -s ./src/dmarc.c ]; then
		if /usr/sbin/opendmarc -V | head -n1 | grep -q 'v1\.4'; then
			perl -pi -e 's|  dkim_result, US""\);|  sig->selector, dkim_result, US"");|g' ./src/dmarc.c
		fi
	fi
	# libnsl is only used for NIS and NIS+ lookups, compilation fails on CentOS8 due to no libnsl in glibc anymore
	perl -pi -e 's/-lnsl//g' ./OS/Makefile-Linux

	cp -f ${EXIM_MAKEFILE} Local/Makefile
	
	# Solve on CentOS8/9: /usr/bin/ld: acl.o: relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a PIE object; recompile with -fPIC
	if rhel_version_is 8 || rhel_version_is 9; then
		if ! grep -m1 -q CFLAGS.*fPIC Local/Makefile; then
			perl -pi -e 's|CFLAGS\=|CFLAGS\=-fPIC |g' Local/Makefile
		fi
	fi

	if [ -e /usr/include/spf2/spf.h ] || [ -e /usr/local/include/spf2/spf.h ]; then
		echo "SUPPORT_SPF=yes" >> Local/Makefile
		if [ -e /usr/local/include/spf2/spf.h ]; then
			echo "CFLAGS  += -DSPF -I/usr/local/include" >> Local/Makefile
		else
			echo "CFLAGS  += -DSPF"  >> Local/Makefile
		fi
		echo "LDFLAGS += -lspf2" >> Local/Makefile
	fi
	
	#Reported issue in https://forum.directadmin.com/showthread.php?t=55603&page=2&p=285310#post285310
	echo "CFLAGS  += `getGccOptions`" >> Local/Makefile

	if ! grep -q ^SUPPORT_SRS Local/Makefile; then
		echo "SUPPORT_SRS=yes " >> Local/Makefile
	fi
	
	echo "Trying to make exim..."
	if ! C_INCLUDE_PATH=/usr/kerberos/include make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing exim..."
	make install

	echo "Moving exim binary."
	EXIM_BINARY=`ls -t /usr/sbin/exim-${EXIM_VER}-* | head -n1`
	if [ "${EXIM_BINARY}" = "" ]; then
		#4.86.2 shows up as /usr/sbin/exim-4.86_2-2
		#assume newest binary is the winner.
		echo "Cannot find the ${EXIM_VER} formatted binary.  Trying a wildcard instead..."

		EXIM_BINARY=`ls -t /usr/sbin/exim-*-* | head -n1`

		echo "Found: '$EXIM_BINARY'"
	fi
	
	mv -f ${EXIM_BINARY} /usr/sbin/exim
	chmod 4755 /usr/sbin/exim

	if [ ! -e /etc/exim.cert ] || [ ! -e /etc/exim.key ]; then
		create_da_conf_certs || return 1
		install_file /usr/local/directadmin/conf/cacert.pem.combined /etc/exim.cert 600 mail:mail || return 1
		install_file /usr/local/directadmin/conf/cakey.pem           /etc/exim.key  600 mail:mail || return 1
	fi

	if [ "${EXIMCONF_OPT}" = "yes" ]; then
		doEximConf || exit 1
	fi

	echo "Enabling exim in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/exim.service ]; then
		cp -f ${CB_CUST_SYSTEMD}/exim.service ${SYSTEMDDIR}/exim.service
	else
		cp -f ${CB_SYSTEMD}/exim.service ${SYSTEMDDIR}/exim.service
	fi
	chmod 644 ${SYSTEMDDIR}/exim.service
	systemctl daemon-reload
	systemctl enable exim.service

	setupLogrotate exim

	echo "Exim ${EXIM_VER} Installed."
	writeLog "Exim ${EXIM_VER} installed"

	if [ "${SPAMD_OPT}" = "no" ]; then
		if [ -e ${SYSTEMDDIR}/spamassassin.service ]; then
			echo "Disabling spamassassin in systemd..."
			systemctl stop spamassassin.service
			systemctl disable spamassassin.service
			systemctl daemon-reload
			rm -f ${SYSTEMDDIR}/spamassassin.service
		fi
		if [ -e ${SYSTEMDDIR}/rspamd.service ]; then
			echo "Disabling rspamd in systemd..."
			systemctl stop rspamd.service
			systemctl disable rspamd.service
			systemctl daemon-reload
			rm -f ${SYSTEMDDIR}/rspamd.service
		fi
	fi

	cd ${WORKDIR}

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "Restarting exim."
	control_service exim restart
	set_service exim ON

	if [ -x /usr/sbin/alternatives ]; then
		if ! /usr/sbin/alternatives  --list | grep -m1 -q '^mta.*/usr/sbin/exim$'; then
			/usr/sbin/alternatives --install /usr/sbin/sendmail mta /usr/sbin/exim 100
		fi
		if [ "`readlink /etc/alternatives/mta`" = "/usr/sbin/exim" ]; then
			/usr/sbin/alternatives --set mta /usr/sbin/exim
		fi
	fi

	#Replace compiled s-nail with an OS version
	if [ -x /usr/local/bin/s-nail ] && [ -e /usr/local/bin/s-nail-uninstall.sh ]; then
		bash /usr/local/bin/s-nail-uninstall.sh
		hash -r
	fi

	if ! command -v s-nail > /dev/null && ! command -v mail > /dev/null; then
		install_rpms s-nail
		install_debs s-nail
	fi

	if [ -x /usr/sbin/exim ] && [ -d /usr/bin ]; then
		if [ ! -e /usr/bin/newaliases ]; then
			ln -s /usr/sbin/exim /usr/bin/newaliases
		fi
	fi
}

####################################################

doBlockCracking() {
	if [ "${BLOCKCRACKING_OPT}" != "yes" ] || [ "${EXIMCONF_OPT}" != "yes" ]; then
		do_exit 1 "You cannot enable BlockCracking, because you do not have it set in options.conf file (blockcracking/eximconf options)."
	fi

	if [ ! -d ${WORKDIR}/blockcracking ]; then
		mkdir -p ${WORKDIR}/blockcracking
		chmod 700 ${WORKDIR}/blockcracking
	fi

	cd ${WORKDIR}
	echo "Enabling BlockCracking..."

	safeDownloadWithMove "${WORKDIR}/exim.blockcracking-${BLOCKCRACKING_VER}.tar.gz" "${BLOCKCRACKING_DOWNLOADURL}"

	mkdir -p /etc/exim.blockcracking
	tar xzf exim.blockcracking-${BLOCKCRACKING_VER}.tar.gz -C /etc/exim.blockcracking

	BC_DP_SRC=/etc/exim.blockcracking/script.denied_paths.default.txt
	if [ -e /etc/exim.blockcracking/script.denied_paths.custom.txt ]; then
		echo "Using custom BC script.denied_paths.custom.txt"
		BC_DP_SRC=/etc/exim.blockcracking/script.denied_paths.custom.txt
	fi
	cp -fp ${BC_DP_SRC} /etc/exim.blockcracking/script.denied_paths.txt
	
	if [ "$1" != "norestart" ]; then
		echo "Restarting exim."
		control_service exim restart
	fi

	echo "BlockCracking is now enabled."
	writeLog "BlockCracking ${BLOCKCRACKING_VER} installed"
}

####################################################

doRemoveBlockCracking() {
	if [ "${BLOCKCRACKING_OPT}" != "no" ]; then
		do_exit 1 "You cannot remove BlockCracking, because you have enabled in options.conf file."
	fi

	cd ${WORKDIR}
	echo "Removing BlockCracking..."

	rm -rf /etc/exim.blockcracking

	echo "Restarting exim."
	control_service exim restart

	echo "BlockCracking is now removed."
	writeLog "BlockCracking removed"
}

####################################################

doEasySpamFighter() {
	if [ "${EASY_SPAM_FIGHTER_OPT}" != "yes" ] || [ "${EXIMCONF_OPT}" != "yes" ]; then
		do_exit 1 "You cannot enable Easy Spam Fighter, because you do not have it set in options.conf file (easy_spam_fighter/eximconf options)."
	fi

	EXIM_SPF_SUPPORT="`/usr/sbin/exim --version | grep -m1 -c SPF`"
	EXIM_SRS_SUPPORT="`/usr/sbin/exim --version | grep -m1 -c SRS`"
	if [ "${EXIM_SPF_SUPPORT}" = "0" ]; then
		do_exit 1 "Your version of Exim does not support SPF, which is needed for Easy Spam Fighter. Please update exim using the CustomBuild script: ./build exim."
	fi

	if [ "${EXIM_SRS_SUPPORT}" = "0" ]; then
		do_exit 1 "Your version of Exim does not support SRS, which is needed for Easy Spam Fighter. Please update exim using the CustomBuild script: ./build exim."
	fi

	if [ ! -d ${WORKDIR}/easy_spam_fighter ]; then
		mkdir -p ${WORKDIR}/easy_spam_fighter
		chmod 700 ${WORKDIR}/easy_spam_fighter
	fi

	cd ${WORKDIR}
	echo "Enabling Easy Spam Fighter..."

	safeDownloadWithMove "${WORKDIR}/exim.easy_spam_fighter-${EASY_SPAM_FIGHTER_VER}.tar.gz" "${EASY_SPAM_FIGHTER_DOWNLOADURL}"

	mkdir -p /etc/exim.easy_spam_fighter
	tar xzf exim.easy_spam_fighter-${EASY_SPAM_FIGHTER_VER}.tar.gz -C /etc/exim.easy_spam_fighter

	if [ -s /etc/virtual/esf_skip_ip ] && [ ! -s /etc/virtual/esf_skip_ips ]; then
		mv -f /etc/virtual/esf_skip_ip /etc/virtual/esf_skip_ips
	fi

	if [ "$1" != "norestart" ]; then
		echo "Restarting exim."
		control_service exim restart
	fi

	echo "Easy Spam Fighter is now enabled."
	writeLog "EasySpamFighter ${EASY_SPAM_FIGHTER_VER} installed"
}

####################################################

doRemoveEasySpamFighter() {
	if [ "${EASY_SPAM_FIGHTER_OPT}" != "no" ]; then
		do_exit 1 "You cannot remove Easy Spam Fighter, because you have enabled in options.conf file."
	fi

	cd ${WORKDIR}
	echo "Removing Easy Spam Fighter..."

	rm -rf /etc/exim.easy_spam_fighter

	echo "Restarting exim."
	control_service exim restart

	echo "Easy Spam Fighter is now removed."
	writeLog "EasySpamFigther removed"
}

####################################################

do_rspamd_conf() {
	if [ "${SPAMD_OPT}" != "rspamd" ]; then
		do_exit 1 "spamd=rspamd is not set in options.conf."
	fi

	echo "Enabling Rspamd Config..."

	mkdir -p /etc/exim/rspamd
	install_custom_file rspamd/check_message.conf /etc/exim/rspamd/check_message.conf 644 root:root || return 1
	install_custom_file rspamd/connect.conf       /etc/exim/rspamd/connect.conf       644 root:root || return 1
	install_custom_file rspamd/variables.conf     /etc/exim/rspamd/variables.conf     644 root:root || return 1
	
	if [ "$1" != "norestart" ]; then
		echo "Restarting exim."
		control_service exim restart
	fi

	echo "Rspamd config is now enabled."
	writeLog "rspamd config installed"
}

do_remove_rspamd_conf() {
	if [ "${SPAMD_OPT}" = "rspamd" ]; then
		do_exit 1 "You cannot remove rspamd_config, because you have enabled in options.conf file."
	fi

	cd ${WORKDIR}
	echo "Removing Rspamd Config..."

	remove_directory /etc/exim/rspamd

	echo "Restarting exim."
	control_service exim restart

	echo "Rspamd Config is now removed."
	writeLog "rspamd_config removed"
}

doGrubConf() {
	GRUB_CONF_MODIFIED=false
	HAS_XFS_ROOT=false
	if mount | grep ' / ' | grep -m1 -q ' xfs '; then
		HAS_XFS_ROOT=true
	fi
	if [ -x /usr/sbin/grub2-mkconfig ]; then
		GRUB_MKCONFIG=/usr/sbin/grub2-mkconfig
	elif [ -x /usr/sbin/grub-mkconfig ]; then
		GRUB_MKCONFIG=/usr/sbin/grub-mkconfig
	fi
	if [ ! -d /sys/fs/cgroup/user.slice ] && [ -s /etc/default/grub ] && ! rhel_version_is 7 && [ "${CLOUDLINUX_OPT}" = "no" ]; then
		if [ ! -z "${GRUB_MKCONFIG}" ]; then
				if [ -d /etc/default/grub.d ]; then
					if ! grep -m1 -q 'systemd.unified_cgroup_hierarchy' /etc/default/grub; then
						if ! grep -m1 -q 'systemd.unified_cgroup_hierarchy' /etc/default/grub.d/99-directadmin.cfg 2>/dev/null; then
							if ! ${HAS_XFS_ROOT}; then
								echo 'GRUB_CMDLINE_LINUX_DEFAULT="${GRUB_CMDLINE_LINUX_DEFAULT} systemd.unified_cgroup_hierarchy=1 psi=1"' > /etc/default/grub.d/99-directadmin.cfg
							elif ! grep -m1 -q 'rootflags' /etc/default/grub; then
								echo 'GRUB_CMDLINE_LINUX_DEFAULT="${GRUB_CMDLINE_LINUX_DEFAULT} rootflags=uquota,pquota systemd.unified_cgroup_hierarchy=1 psi=1"' > /etc/default/grub.d/99-directadmin.cfg
							else
								echo 'GRUB_CMDLINE_LINUX_DEFAULT="${GRUB_CMDLINE_LINUX_DEFAULT} systemd.unified_cgroup_hierarchy=1 psi=1"' > /etc/default/grub.d/99-directadmin.cfg
							fi
							GRUB_CONF_MODIFIED=true
						fi
					fi
					if ${GRUB_CONF_MODIFIED}; then
						find /boot -name 'grub.cfg' -exec ${GRUB_MKCONFIG} -o {} \;
					fi
				else
					if ! grep -m1 -q 'systemd.unified_cgroup_hierarchy' /etc/default/grub; then
						if ! ${HAS_XFS_ROOT}; then
							echo 'GRUB_CMDLINE_LINUX_DEFAULT="${GRUB_CMDLINE_LINUX_DEFAULT} systemd.unified_cgroup_hierarchy=1 psi=1"' >> /etc/default/grub
						elif ! grep -m1 -q 'rootflags' /etc/default/grub; then
							echo 'GRUB_CMDLINE_LINUX_DEFAULT="${GRUB_CMDLINE_LINUX_DEFAULT} rootflags=uquota,pquota systemd.unified_cgroup_hierarchy=1 psi=1"' >> /etc/default/grub
						else
							echo 'GRUB_CMDLINE_LINUX_DEFAULT="${GRUB_CMDLINE_LINUX_DEFAULT} systemd.unified_cgroup_hierarchy=1 psi=1"' >> /etc/default/grub
						fi
						GRUB_CONF_MODIFIED=true
					fi
					if ${GRUB_CONF_MODIFIED}; then
						find /boot -name 'grub.cfg' -exec ${GRUB_MKCONFIG} -o {} \;
					fi
				fi
		fi
	fi
	if [ -s /etc/default/grub ] && ${HAS_XFS_ROOT}; then
		if ! grep -m1 -q 'rootflags=uquota,pquota' /etc/default/grub; then
			if [ ! -z "${GRUB_MKCONFIG}" ]; then
				if ! grep -m1 -q 'rootflags' /etc/default/grub; then
					if ${HAS_XFS_ROOT}; then
						echo 'GRUB_CMDLINE_LINUX_DEFAULT="${GRUB_CMDLINE_LINUX_DEFAULT} rootflags=uquota,pquota"' >> /etc/default/grub
					fi
					GRUB_CONF_MODIFIED=true
					find /boot -name 'grub.cfg' -exec ${GRUB_MKCONFIG} -o {} \;
				fi
			fi
		fi
	fi
	if ${GRUB_CONF_MODIFIED}; then
		echo "Grub configuration re-generated. Please reboot the box."
	else
		echo "No grub changes needed."
	fi
}
####################################################

doEnsureEximFile() {
	if [ "$1" != "" ]; then
		if [ ! -e $1 ]; then
			echo "Creating file $1..."
			touch $1
			chown mail:mail $1
			chmod 600 $1
		fi
	fi
}

####################################################

doEximConf() {
	if [ "${EXIMCONF_OPT}" != "yes" ]; then
		do_exit 1 "You cannot update Exim configuration files, because you do not have it set in options.conf file."
	fi
	set_sendmail_link
	
	install_custom_file exim/exim.conf                   /etc/exim.conf                   600 root:root || return 1
	install_custom_file exim/system_filter.exim          /etc/system_filter.exim          644 root:root || return 1
	install_custom_file exim/exim.strings.conf           /etc/exim.strings.conf           644 root:root || return 1
	install_custom_file exim/exim.variables.conf.default /etc/exim.variables.conf.default 644 root:root || return 1
	install_custom_file exim/exim.pl                     /etc/exim.pl                     755 root:root || return 1

	#Make dovecot listen on port 10025 if dovecot_proxy is enabled
	DOVECOT_PROXY=$(${DA_BIN} config-get dovecot_proxy)
	if [ "${DOVECOT_PROXY}" -ne 0 ]; then
		if ! grep -m1 -q '^daemon_smtp_ports.*10025' /etc/exim.variables.conf.default; then
			perl -pi -e 's|^daemon_smtp_ports=25 : 587 : 465|daemon_smtp_ports=25 : 587 : 465 : 10025|g' /etc/exim.variables.conf.default
		fi
	fi

	if [ ${CPU_CORES} -gt 5 ]; then
		sed -i "s|^queue_run_max=.*|queue_run_max=${CPU_CORES}|" /etc/exim.variables.conf.default
	fi
	doCheckIPV6
	if [ "${IPV6}" = "0" ]; then
		sed -i 's|^disable_ipv6=.*|disable_ipv6=true|' /etc/exim.variables.conf.default
	fi

	doSslConfigurationEmail

	# Create /etc/exim.variables.conf
	{
		echo '#Do not edit this file directly'
		echo "#edit /etc/exim.variables.conf.custom"
		if [ -f /etc/exim.variables.conf.custom ]; then
			awk -F = 'function trim(s) { sub(/^[ \t\v]+/, "", s); sub(/[ \t\v]+$/, "", s); return s } !seen[trim($1)]++' /etc/exim.variables.conf.custom /etc/exim.variables.conf.default
		else
			cat /etc/exim.variables.conf.default
		fi
	} > /etc/exim.variables.conf.merged
	local rc=$?
	if [ "${rc}" -ne 0 ]; then
		rm -f /etc/exim.variables.conf.merged
		do_exit 1 "Failed to create /etc/exim.variables.conf.merged file"
	fi
	mv -f /etc/exim.variables.conf.merged /etc/exim.variables.conf

	MAIL_SNI_OPT=$(${DA_BIN} config-get mail_sni)
	if [ "${MAIL_SNI_OPT}" -ge 1 ]; then
		REPLACE_EXIM_TLS=false
		if grep -m1 -q '^tls_certificate *= */etc/exim.\cert' /etc/exim.variables.conf; then
			EXIM_TLS_FILE=/etc/exim.variables.conf
			REPLACE_EXIM_TLS=true
		elif grep -m1 -q '^tls_certificate *= */etc/exim.\cert' /etc/exim.conf; then
			EXIM_TLS_FILE=/etc/exim.conf
			REPLACE_EXIM_TLS=true
		fi
		if ${REPLACE_EXIM_TLS}; then
			perl -pi -e 's|^tls_certificate *\= */etc/exim\.cert|tls_certificate=\$\{if exists\{/etc/virtual/snidomains\}\{\$\{lookup\{\$tls_in_sni\}nwildlsearch\{/etc/virtual/snidomains\}\{\$\{if exists\{/usr/local/directadmin/data/users/\$\{extract\{1\}\{:\}\{\$value\}\}/domains/\$\{extract\{2\}\{:\}\{\$value\}\}.cert.combined\}\{/usr/local/directadmin/data/users/\$\{extract\{1\}\{:\}\{\$value\}\}/domains/\$\{extract\{2\}\{:\}\{\$value\}\}.cert.combined\}\{/etc/exim.cert\}\}\}\{/etc/exim.cert\}\}\}\{/etc/exim.cert\}\}|' ${EXIM_TLS_FILE}
			perl -pi -e 's|^tls_privatekey *\= */etc/exim\.key|tls_privatekey=\$\{if exists\{/etc/virtual/snidomains\}\{\$\{lookup\{\$tls_in_sni\}nwildlsearch\{/etc/virtual/snidomains\}\{\$\{if exists\{/usr/local/directadmin/data/users/\$\{extract\{1\}\{:\}\{\$value\}\}/domains/\$\{extract\{2\}\{:\}\{\$value\}\}.key\}\{/usr/local/directadmin/data/users/\$\{extract\{1\}\{:\}\{\$value\}\}/domains/\$\{extract\{2\}\{:\}\{\$value\}\}.key\}\{/etc/exim.key\}\}\}\{/etc/exim.key\}\}\}\{/etc/exim.key\}\}|' ${EXIM_TLS_FILE}
		fi
	fi
	if ! grep -m1 -q '^tls_dhparam' /etc/exim.variables.conf; then
		if [ ! -s /etc/exim_dh.pem ]; then
			ensure_dhparam /etc/exim_dh.pem
			chown mail:mail /etc/exim_dh.pem
			chmod 400 /etc/exim_dh.pem
		fi
		if [ -s /etc/exim_dh.pem ]; then
			echo 'tls_dhparam = /etc/exim_dh.pem' >> /etc/exim.variables.conf
			echo 'tls_dh_max_bits = 4096' >> /etc/exim.variables.conf
		fi
	fi
	EXIM_SRS_CONF=/etc/exim.srs.conf
	if ! grep -q '^SRS_SECRET' ${EXIM_SRS_CONF} 2>/dev/null; then
		echo -n "SRS_SECRET = " > ${EXIM_SRS_CONF}
		/usr/bin/openssl rand -base64 48 >> ${EXIM_SRS_CONF}
	fi
	

	if [ ! -e /etc/virtual/limit ]; then
		echo "/etc/virtual/limit not found. Creating with a value of 0..."
		echo "0" > /etc/virtual/limit
		chown mail:mail /etc/virtual/limit
	fi
	if [ ! -d /etc/virtual/usage ]; then
		echo "/etc/virtual/usage not found. Creating..."
		mkdir -p /etc/virtual/usage
		chown mail:mail /etc/virtual/usage
	fi
	doEnsureEximFile /etc/virtual/bad_sender_hosts
	doEnsureEximFile /etc/virtual/bad_sender_hosts_ip
	doEnsureEximFile /etc/virtual/blacklist_domains
	doEnsureEximFile /etc/virtual/blacklist_senders
	doEnsureEximFile /etc/virtual/whitelist_domains
	doEnsureEximFile /etc/virtual/whitelist_hosts
	doEnsureEximFile /etc/virtual/whitelist_hosts_ip
	doEnsureEximFile /etc/virtual/whitelist_senders
	doEnsureEximFile /etc/virtual/use_rbl_domains
	doEnsureEximFile /etc/virtual/skip_av_domains
	doEnsureEximFile /etc/virtual/skip_rbl_domains

	if [ "${PIGEONHOLE_OPT}" = "yes" ]; then
		perl -pi -e 's#transport = virtual_localdelivery#transport = dovecot_lmtp_udp#' /etc/exim.conf
	fi

	if [ "${BLOCKCRACKING_OPT}" = "yes" ]; then
		doBlockCracking norestart
	else
		rm -rf /etc/exim.blockcracking
	fi

	if [ "${EASY_SPAM_FIGHTER_OPT}" = "yes" ]; then
		doEasySpamFighter norestart
	else
		rm -rf /etc/exim.easy_spam_fighter
	fi

	if [ "${CAGEFS_OPT}" = "yes" ]; then
		echo "force_command" > /etc/exim.cagefs.pipe.conf
		echo 'command = /bin/cagefs_enter $address_pipe' >> /etc/exim.cagefs.pipe.conf
		chmod 644 /etc/exim.cagefs.pipe.conf
	else
		rm -f /etc/exim.cagefs.pipe.conf
	fi

	if [ "${SPAMD_OPT}" = "no" ]; then
		rm -f /etc/exim.spamassassin.conf
		rm -f /etc/exim.spamd.conf
		rm -f /etc/exim.spamd.load.conf
		if [ -d /etc/exim/rspamd ]; then
			if [ ! -d /etc/exim/rspamd_disabled ]; then
				echo "Renaming /etc/exim/rspamd to /etc/exim/rspamd_disabled..."
				mv /etc/exim/rspamd /etc/exim/rspamd_disabled
			else
				echo "Removing old /etc/exim/rspamd directory..."
				rm -rf /etc/exim/rspamd
			fi
		fi
	elif [ "${SPAMD_OPT}" = "rspamd" ]; then
#		we don't need the below as the spamd_address is in /etc/exim/rspamd/variables.conf.
#		echo "Enabling rspamd in /etc/exim.spamd.load.conf..."
#		echo 'spamd_address = 127.0.0.1 11333 retry=20s variant=rspamd' > /etc/exim.spamd.load.conf
#		cp -fv ${SPAMD_CONF} /etc/exim.spamd.conf

		do_rspamd_conf norestart
		
	elif [ "${SPAMD_OPT}" = "spamassassin" ]; then
		perl -pi -e 's|#.include_if_exists /etc/exim.spamassassin.conf|.include_if_exists /etc/exim.spamassassin.conf|' /etc/exim.conf
		install_custom_file exim/exim.spamassassin.conf /etc/exim.spamassassin.conf 644 root:root || exit 1
		rm -f /etc/exim.spamd.conf
		if [ -d /etc/exim/rspamd ]; then
			if [ ! -d /etc/exim/rspamd_disabled ]; then
				echo "Renaming /etc/exim/rspamd to /etc/exim/rspamd_disabled..."
				mv /etc/exim/rspamd /etc/exim/rspamd_disabled
			else
				echo "Removing old /etc/exim/rspamd directory..."
				rm -rf /etc/exim/rspamd
			fi
		fi
	fi

	if [ "$(${DA_BIN} config-get dkim)" != "0" ]; then
		DKIM_SELECTOR=$(${DA_BIN} config-get dkim_selector)
		install_custom_file exim/exim.dkim.conf /etc/exim.dkim.conf 644 root:root || exit 1
		perl -pi -e "s|dkim_selector \= .*|dkim_selector = ${DKIM_SELECTOR}|g" /etc/exim.dkim.conf 
	else
		rm -f /etc/exim.dkim.conf
	fi

	if [ "${CLAMAV_EXIM_OPT}" = "yes" ] && [ "${CLAMAV_OPT}" = "yes" ]; then
		perl -pi -e 's|#.include_if_exists /etc/exim.clamav.load.conf|.include_if_exists /etc/exim.clamav.load.conf|' /etc/exim.conf
		perl -pi -e 's|#.include_if_exists /etc/exim.clamav.conf|.include_if_exists /etc/exim.clamav.conf|' /etc/exim.conf
		install_custom_file exim/exim.clamav.load.conf /etc/exim.clamav.load.conf 644 root:root || exit 1
		install_custom_file exim/exim.clamav.conf      /etc/exim.clamav.conf      644 root:root || exit 1
	else
		rm -f /etc/exim.clamav.load.conf
		rm -f /etc/exim.clamav.conf
	fi

	#include magicspam
	if [ -x /usr/share/magicspam/bin/activate_module ]; then
		/usr/share/magicspam/bin/activate_module
	fi

	if [ "${SPAMD_OPT}" = "spamassassin" ]; then
		set_service spamd ON
	elif [ "${SPAMD_OPT}" != "spamassassin" ]; then
		set_service spamd delete
	fi

	if [ "${SPAMD_OPT}" = "rspamd" ]; then
		set_service rspamd ON
	else
		set_service rspamd delete
	fi

	echo "Restarting exim."
	control_service exim restart

	COUNT_LMTP=0
	if [ -e /etc/exim.conf ]; then
		COUNT_LMTP=`grep -c 'transport = dovecot_lmtp_udp' /etc/exim.conf`
	fi

	if [ ! -e /etc/dovecot/conf/lmtp.conf ] && [ "${COUNT_LMTP}" = "1" ] && [ -e /etc/dovecot/dovecot.conf ]; then
		if ! grep -q 'protocol lmtp' /etc/dovecot/dovecot.conf; then
			echo "${boldon}WARNING:${boldoff} make sure you have LMTP enabled in dovecot.conf, './build dovecot_conf' should fix it."
		fi
	fi
	
	writeLog "exim.conf installed"
}

####################################################

compile_mysql_binary() {
	ensureBuildPackages
	install_debs libaio1 libaio-dev cmake
	install_rpms libaio
	if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
		MYSQLURL=${WEBPATH_SERVICES}/all/mariadb/${MARIADB_OPT}/${MARIADB_VER}
		MYSQLSRC=mariadb-${MARIADB_VER}

		safeDownloadWithMove "${WORKDIR}/${MYSQLSRC}.tar.gz" "${WEBPATH_SERVICES}/all/mariadb/${MARIADB_OPT}/${MARIADB_VER}/${MYSQLSRC}.tar.gz"
	else
		MYSQLURL=${WEBPATH_SERVICES}/all/mysql/${MYSQL_OPT}/${MYSQL_VER}
		MYSQLSRC=mysql-${MYSQL_VER}

		safeDownloadWithMove "${WORKDIR}/${MYSQLSRC}.tar.gz" "${WEBPATH_SERVICES}/all/mysql/${MYSQL_OPT}/${MYSQL_VER}/${MYSQLSRC}.tar.gz"
	fi

	if [ -e ${MYSQLSRC} ]; then
		echo "Found old ${MYSQLSRC}, removing ..."
		rm -rf ${MYSQLSRC}
	fi

	echo "Extracting ${MYSQLSRC}.tar.gz ... "

	tar xzf ${MYSQLSRC}.tar.gz --no-same-owner
	if [ $? -ne 0 ]; then
		do_exit 1 "Failed to extract: ${MYSQLSRC}.tar.gz. Exiting..."
	fi
	cd ${MYSQLSRC}

	CFLAGS=-DHAVE_BROKEN_REALPATH
	
	if [ -e ${WORKDIR}/custom/mysql/cmake.mysql ]; then
		${WORKDIR}/custom/mysql/cmake.mysql
	else
		CMAKE_APPEND=""
		if [ "${MYSQL_OPT}" = "5.7" ] || [ "${MYSQL_OPT}" = "8.0" ]; then
			CMAKE_APPEND=" -DDOWNLOAD_BOOST=ON -DWITH_BOOST=/usr/local/boost_mysql -DFORCE_INSOURCE_BUILD=1"
		fi
		cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DWITH_INNOBASE_STORAGE_ENGINE=1 \
				-DWITH_FEDERATED_STORAGE_ENGINE=1 -DWITH_SYSTEMD=yes -DWITH_UNIT_TESTS=OFF -DPLUGIN_{ARCHIVE,TOKUDB,MROONGA,OQGRAPH,ROCKSDB,CONNECT,PERFSCHEMA,SPIDER,SPHINX}=NO -DWITH_SAFEMALLOC=OFF -DMYSQL_MAINTAINER_MODE=OFF \
				-DWITH_ZLIB=system -DWITH_EXTRA_CHARSETS=all${CMAKE_APPEND} -G Ninja
	fi

	echo "Done. Making ${MYSQLSRC}..."
	echo "Trying to make ${MYSQLSRC}..."
	if ! cmake --build . -- -j${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Packaging ${MYSQLSRC}..."
	./scripts/make_binary_distribution

	echo "Moving ${MYSQLSRC}-*.tar.gz to ${WORKDIR} ..."
	mv -f ${MYSQLSRC}-*.tar.gz ..
	cd ..
	echo "Done."
	
	writeLog "${MYSQLSRC}.tar.gz compiled"
}

all_databases() {
	if [ "$MYSQLUSER" = "" ] || [ "$MYSQLPASSWORD" = "" ]; then
		do_exit 1 "all_databases: user or password is blank"
	fi

	if [ -d ${MYSQL_DATA} ]; then
		initMySQL

		#Assumes that MYSQLUSER and MYSQLPASSWORD are already set.
		$MYSQL_BIN --defaults-extra-file=${DA_MY_CNF} -e 'SHOW DATABASES' -sss | grep -v '^information_schema$' | grep -v '^performance_schema$'
	fi
}

doMySQLback() {
	if [ "${MYSQL_BACKUP_OPT}" = "yes" ] && [ -d ${MYSQL_DATA} ]; then
		initMySQL
		MYSQLDUMP=/usr/local/mysql/bin/mysqldump
		if [ ! -e $MYSQLDUMP ]; then
			MYSQLDUMP=/usr/bin/mysqldump
		fi
		if [ ! -e $MYSQLDUMP ]; then
			if [ -d "${MYSQL_DATA}" ]; then
				echo "Cannot find $MYSQLDUMP"
			fi
			return
		fi

		if [ ! -d ${MYSQL_BACKUP_DIR_OPT} ]; then
			mkdir -p ${MYSQL_BACKUP_DIR_OPT}
		fi
		chmod 700 ${MYSQL_BACKUP_DIR_OPT}

		EXTRA_MYSQLDUMP_OPTIONS=""
		if /usr/local/directadmin/directadmin c | grep -m1 -q '^extra_mysqldump_options='; then
			EXTRA_MYSQLDUMP_OPTIONS="`/usr/local/directadmin/directadmin c | grep -m1 '^extra_mysqldump_options=' | cut -d'=' -f2-`"
		fi

		# sysbk code
		if [ -d ${MYSQL_DATA} ]; then
			cd ${MYSQL_DATA}
			for i in `all_databases`; do
				printf "\tDumping database $i \n"
				printf "\tDumping database $i \n" >> ${WORKDIR}/mysql_backups.log

				if [ "${MYSQL_BACKUP_GZIP_OPT}" = "yes" ]; then

					$MYSQLDUMP --defaults-extra-file=${DA_MY_CNF} --add-drop-database --databases --routines -f ${EXTRA_MYSQLDUMP_OPTIONS} -l $i | gzip > ${MYSQL_BACKUP_DIR_OPT}/$i.sql.gz
					if [ $? -ne 0 ]; then
						echo "BACKUP OF ${i} FAILED!"
					fi
					chmod 660 ${MYSQL_BACKUP_DIR_OPT}/$i.sql.gz
				else
					$MYSQLDUMP --defaults-extra-file=${DA_MY_CNF} --add-drop-database --databases --routines -f ${EXTRA_MYSQLDUMP_OPTIONS} -l $i > ${MYSQL_BACKUP_DIR_OPT}/$i.sql
					if [ $? -ne 0 ]; then
						echo "BACKUP OF ${i} FAILED!"
					fi
					chmod 660 ${MYSQL_BACKUP_DIR_OPT}/$i.sql
				fi
			done
		else
			echo "${MYSQL_DATA} directory does not exist, nothing to backup"
		fi
	fi
}

backup_libmysqlclient() {
	if ! distro_is_debian; then
		return
	fi

	LDD=/usr/bin/ldd
	LIB_PATH=/usr/local/mysql/lib
	if ${LDD} ${DA_BIN} 2>/dev/null | grep -m1 -q libmysqlclient.so; then
		LIB_NAME=`${LDD} ${DA_BIN} 2>/dev/null | grep -m1 'libmysqlclient.so' | awk '{ print $1; }'`
		CLIENT_LIB=`${LDD} ${DA_BIN} 2>/dev/null | grep -m1 'libmysqlclient.so' | awk '{ print $3; }'`
		if [ -s "${CLIENT_LIB}" ]; then
			echo "Backing up ${CLIENT_LIB} to ${WORKDIR}/${LIB_NAME}"
			cp -fp ${CLIENT_LIB} ${WORKDIR}/${LIB_NAME}
		fi
	fi
}

restore_libmysqlclient() {
	if ! distro_is_debian; then
		return
	fi

	LDD=/usr/bin/ldd
	LIB_PATH=/usr/local/mysql/lib
	if ${LDD} ${DA_BIN} 2>/dev/null | grep -m1 -q 'libmysqlclient.so'; then
		LIB_NAME=`${LDD} ${DA_BIN} 2>/dev/null | grep -m1 'libmysqlclient.so' | awk '{ print $1; }'`
		CLIENT_LIB=${LIB_PATH}/${LIB_NAME}
		if [ ! -s "${CLIENT_LIB}" ]; then
			if [ ! -s ${WORKDIR}/${LIB_NAME} ]; then
				echo "Cannot find ${WORKDIR}/${LIB_NAME} to restore."
				echo "DirectAdmin might crash. If needed, see this guide:"
				echo "https://help.directadmin.com/item.php?id=236"
				return
			fi

			cp -fp ${WORKDIR}/${LIB_NAME} ${CLIENT_LIB}
		fi
	fi
}

#To make sure local-infile is disabled
setup_my_cnf() {
	echo "Ensuring local-infile is disabled for security reasons in MySQL configuration file..."
	MY_CNF_FILE=/etc/my.cnf
	if [ -e ${MY_CNF_FILE} ]; then
		if grep -m1 -q -F 'includedir /etc/my.cnf.d' ${MY_CNF_FILE}; then
			if [ -e /etc/my.cnf.d/server.cnf ]; then
				MY_CNF_FILE=/etc/my.cnf.d/server.cnf
			fi
		fi
		if grep -m1 -q '[mysqld]' ${MY_CNF_FILE}; then
			if ! grep -m1 -q 'local-infile' ${MY_CNF_FILE}; then
				perl -pi -e 's#\[mysqld\]#[mysqld]\nlocal-infile = 0#' ${MY_CNF_FILE}
			fi
		else
			if ! grep -m1 -q 'local-infile' ${MY_CNF_FILE}; then
				echo '[mysqld]' >> ${MY_CNF_FILE}
				echo 'local-infile = 0' >> ${MY_CNF_FILE}
			fi
		fi
		if ! grep -m1 -q 'max_allowed_packet' ${MY_CNF_FILE}; then
			if ! grep -m1 -q 'max-allowed-packet' ${MY_CNF_FILE}; then
				perl -pi -e 's#\[mysqld\]#[mysqld]\nmax_allowed_packet=64M#' ${MY_CNF_FILE}
			fi
		fi
		if rhel_version_is 9; then
			if ! grep -q '\[client\]' ${MY_CNF_FILE}; then
				echo "" >> ${MY_CNF_FILE}
				echo "[client]" >> ${MY_CNF_FILE}
				echo "socket=/var/lib/mysql/mysql.sock" >> ${MY_CNF_FILE}
			elif grep -q '\[client\]' ${MY_CNF_FILE}; then
				if ! grep -q '^socket=' ${MY_CNF_FILE}; then
					perl -pi -e 's#\[client\]#[client]\nsocket=/var/lib/mysql/mysql.sock#' ${MY_CNF_FILE}
				fi
			fi
		fi
	fi
}

ensure_cmake() {
	CMAKE_NAME="cmake"
	if rhel_version_is 7; then
		CMAKE_NAME="cmake3"
	fi
	install_debs cmake ninja-build
	install_rpms ${CMAKE_NAME} ninja-build
}

ensure_libnuma() {
	install_rpms numactl-devel
	install_debs libnuma-dev libnuma1
}

ensure_libtirpc() {
	install_rpms libtirpc-devel
	install_debs libtirpc-dev
}

ensure_rpcgen() {
	install_rpms rpcgen
}

hotfix_rhel9_with_libxcrypt_compat() {
	# Mariadb provided precompiled binary for rhel 9 requires legacy libcrypt.so.1 to be present, which does not exist on alma 9 by default
	# Hoping this function is temporary and Mariadb ditches the legacy libcrypt module 
	if rhel_version_is 9 && ldd /usr/local/mysql/bin/mariadbd | grep -q 'libcrypt.so.1 => not found'; then
		install_rpms libxcrypt-compat
	fi
}

ensure_libpmem() {
	if [ ! -e /usr/lib/libpmem.so.1 ] && [ ! -e /usr/lib/i386-linux-gnu/libpmem.so.1 ] && [ ! -e /usr/lib64/libpmem.so.1 ] && [ ! -e /lib64/libpmem.so.1 ] && [ ! -e /lib/libpmem.so.1 ] && [ ! -e /lib/i386-linux-gnu/libpmem.so.1 ] && [ ! -e /usr/lib/x86_64-linux-gnu/libpmem.so.1 ]; then
		echo "Cannot find libpmem.so.1, installing..."
		install_debs libpmem-dev libpmem1
		install_rpms libpmem
	fi
}

setup_mysql_root_user() {
	cd ${WORKDIR}

	if [ "${MYSQLPASSWORD}" = "nothing" ]; then
		MYSQLPASSWORD="`random_pass`"
		if [ -s ${DA_MYSQL} ]; then
			perl -pi -e "s|\=nothing$|=${MYSQLPASSWORD}|g" ${DA_MYSQL}
			perl -pi -e "s|\=\"nothing\"$|=\"${MYSQLPASSWORD}\"|g" ${DA_MYSQL}
		else
			echo "user=da_admin" > ${DA_MYSQL}
			echo "passwd=${MYSQLPASSWORD}" >> ${DA_MYSQL}
			chown -f diradmin:diradmin ${DA_MYSQL}
			chmod -f 400 ${DA_MYSQL}
		fi
		if [ -s ${DA_MY_CNF} ]; then
			perl -pi -e "s|\=\"nothing\"$|=\"${MYSQLPASSWORD}\"|g" ${DA_MY_CNF}
		fi
		if [ -s /usr/local/directadmin/scripts/setup.txt ]; then
			if grep -q '^mysql\=' /usr/local/directadmin/scripts/setup.txt; then
				perl -pi -e "s|^mysql\=.*$|mysql=${MYSQLPASSWORD}|g" /usr/local/directadmin/scripts/setup.txt
			else
				echo "mysql=${MYSQLPASSWORD}" >> /usr/local/directadmin/scripts/setup.txt
			fi
		fi
	fi
	if [ -z "${SQL_PATH_IS_SETUP}" ]; then
		if ${SQL_PATH_IS_EMPTY}; then
			MYSQL_ROOT_PASS=""
			ROOT_PASS_SET=true
			if [ ! -d ${MYSQL_DATA}/mysql ]; then
				echo "${MYSQL_DATA}/mysql does not exist, running clean mysql data installation..."
				hotfix_rhel9_with_libxcrypt_compat
				# Clean /root/.mysql_secret up
				echo -n '' > /root/.mysql_secret
				mkdir -p ${MYSQL_DATA}
				chown mysql:mysql ${MYSQL_DATA}
				chmod 711 ${MYSQL_DATA}
				if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
					FORCE_APPEND="--force"
				elif [ "${MYSQL_INST_OPT}" = "mysql" ] && [ "${MYSQL_VER_OPT}" = "5.6" ]; then
					FORCE_APPEND="--random-password-file=/root/.mysql_secret"
				else
					FORCE_APPEND=""
				fi
				if distro_is_debian || rhel_version_is 9 || [ "${MYSQL_FORCE_COMPILE_OPT}" = "yes" ]; then
					MYSQL_BASEDIR_PATH="/usr/local/mysql"
				else
					MYSQL_BASEDIR_PATH="/usr"
				fi
				if [ "${MYSQL_INST_OPT}" = "mysql" ] && [ "${MYSQL_OPT}" != "5.5" ] && [ "${MYSQL_OPT}" != "5.6" ]; then
					if [ -x /usr/sbin/mysqld ]; then
						MYSQL_ROOT_PASS=`/usr/sbin/mysqld --initialize --user=mysql --basedir=${MYSQL_BASEDIR_PATH} --datadir=${MYSQL_DATA} 2>&1 | grep 'temporary password' | tail -n1 | grep -o 'root@localhost: .*' | awk '{print $2}'`
					else
						MYSQL_ROOT_PASS=`/usr/local/mysql/bin/mysqld --initialize --user=mysql --basedir=${MYSQL_BASEDIR_PATH} --datadir=${MYSQL_DATA} 2>&1 | grep 'temporary password' | tail -n1 | grep -o 'root@localhost: .*' | awk '{print $2}'`
					fi
				elif [ -x ${MYSQL_BIN}_install_db ]; then
					${MYSQL_BIN}_install_db --user=mysql --basedir=${MYSQL_BASEDIR_PATH} --datadir=${MYSQL_DATA} ${FORCE_APPEND}
				elif [ -x /usr/local/mysql/scripts/mysql_install_db ]; then
					/usr/local/mysql/scripts/mysql_install_db --user=mysql --basedir=${MYSQL_BASEDIR_PATH} --datadir=${MYSQL_DATA} ${FORCE_APPEND}
				fi
				if [ -s /root/.mysql_secret ]; then
					ROOT_PASS_SET=true
				elif [ "${MYSQL_INST_OPT}" = "mysql" ] && [ "${MYSQL_OPT}" = "8.0" ]; then
					ROOT_PASS_SET=true
				elif [ "${MYSQL_INST_OPT}" = "mysql" ] && [ "${MYSQL_OPT}" = "5.7" ]; then
					ROOT_PASS_SET=true
				else
					ROOT_PASS_SET=false
				fi
			fi
		
			control_service mysqld start
			sleep 5
			if [ -z "${MYSQL_ROOT_PASS}" ]; then
				if ${ROOT_PASS_SET} && [ -s /root/.mysql_secret ] && [ "${MYSQL_OPT}" != "8.0" ]; then
					if find /root/.mysql_secret -mmin -5 -type f 2>/dev/null | grep -m1 -q '/root/.mysql_secret'; then
						MYSQL_ROOT_PASS="`grep -o ': .*$' /root/.mysql_secret | cut -d ' ' -f2 | tail -n1`"
						if [ "${MYSQL_ROOT_PASS}" = "" ]; then
							MYSQL_ROOT_PASS="`tail -n1 /root/.mysql_secret`"
						fi
					fi
				fi

				if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
					if [ "${MYSQL_OPT}" = "5.7" ] || [ "${MYSQL_OPT}" = "8.0" ]; then
						if [ -x /bin/journalctl ]; then
							MYSQL_ROOT_PASS=`journalctl -xe -u mysqld |grep 'temporary password' | tail -n1 | grep -o 'root@localhost: .*' | awk '{print $2}'`
						fi
						if [ -s /var/log/mysqld.log ] && [ -z "${MYSQL_ROOT_PASS}" ]; then
							MYSQL_ROOT_PASS=`grep 'temporary password' /var/log/mysqld.log | tail -n1 | grep -o 'root@localhost: .*' | awk '{print $2}'`
						fi
					fi
				fi
			fi

			USE_NEW_SET_PASSWORD=1
			MYSQLV=`mysql_main`
			INDENTIFIED_WITH_STRING="IDENTIFIED"
			#for MySQL 8.0, SET PASSWORD doesn't specify PASSWORD()
			if [ "${MYSQLV}" = "5.5" ] || [ "${MYSQLV}" = "5.6" ]; then
				USE_NEW_SET_PASSWORD=0
				INDENTIFIED_WITH_STRING="IDENTIFIED"
			elif [ "${MYSQLV}" = "5.7" ]; then
				INDENTIFIED_WITH_STRING="IDENTIFIED"
			elif has_mariadb; then
				if [ "${MYSQLV}" != "10.3" ] && [ "${MYSQLV}" != "10.4" ] && [ "${MYSQLV}" != "10.5" ] && [ "${MYSQLV}" != "10.6" ]; then
					USE_NEW_SET_PASSWORD=0
				fi
				INDENTIFIED_WITH_STRING="IDENTIFIED"
			else
				INDENTIFIED_WITH_STRING="IDENTIFIED WITH mysql_native_password"
			fi
			${MYSQL_BIN}admin --user=root --password="${MYSQL_ROOT_PASS}" password "${MYSQLPASSWORD}" 2>&1 >/dev/null
			if [ "$?" != "0" ]; then
				echo "Error setting root pass using ${MYSQL_BIN}admin. Trying SET PASSWORD."
				if [ "${USE_NEW_SET_PASSWORD}" = "1" ]; then
					echo "Setting password: ALTER USER 'root'@'localhost' ${INDENTIFIED_WITH_STRING} BY '${MYSQLPASSWORD}';"
					${MYSQL_BIN} --user=root --password="${MYSQL_ROOT_PASS}" -e "ALTER USER 'root'@'localhost' ${INDENTIFIED_WITH_STRING} BY '${MYSQLPASSWORD}';" --host=${MYSQLHOST} >/dev/null 2>&1
				else
					echo "Setting password: SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${MYSQLPASSWORD}');"
					${MYSQL_BIN} --user=root --password="${MYSQL_ROOT_PASS}" -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${MYSQLPASSWORD}');" --host=${MYSQLHOST} >/dev/null 2>&1 
				fi
				if [ "$?" = "0" ]; then
						echo "That worked! Root password should be set."
				else
						echo "*********************************"
						echo ""
						echo "We seem to have an error when trying to SET PASSWORD FOR 'root'@'localhost'";
						echo ""
						do_exit 1 "*********************************"
				fi
			fi

			${MYSQL_BIN} --user=root --password='' -e "quit" >/dev/null 2>&1
			if [ "$?" = "0" ]; then
				echo "MySQL root password seems to be unset, setting using MySQL queries..."
				if [ "${USE_NEW_SET_PASSWORD}" = "1" ]; then
					echo "Setting password: ALTER USER 'root'@'localhost' ${INDENTIFIED_WITH_STRING} BY '${MYSQLPASSWORD}';"
					${MYSQL_BIN} --user=root --password="${MYSQL_ROOT_PASS}" -e "ALTER USER 'root'@'localhost' ${INDENTIFIED_WITH_STRING} BY '${MYSQLPASSWORD}';" --host=${MYSQLHOST} >/dev/null 2>&1
				else
					echo "Setting password: SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${MYSQLPASSWORD}');"
					${MYSQL_BIN} --user=root --password="${MYSQL_ROOT_PASS}" -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${MYSQLPASSWORD}');" --host=${MYSQLHOST} 2>&1 >/dev/null
				fi
			fi

			${MYSQL_BIN} --user=root --password="${MYSQLPASSWORD}" -e "quit" >/dev/null 2>&1
			if [ "$?" != "0" ]; then
				do_exit 1 "Unable to login using root MySQL credentials. Aborting installation..."
			fi

			#Creating da_admin user
			${MYSQL_BIN} --user=root --password="${MYSQLPASSWORD}" -e "CREATE USER 'da_admin'@'localhost' ${INDENTIFIED_WITH_STRING} BY '${MYSQLPASSWORD}';" 2>&1 >/dev/null
			if [ "${USE_NEW_SET_PASSWORD}" = "1" ]; then
				${MYSQL_BIN} --user=root --password="${MYSQL_ROOT_PASS}" -e "ALTER USER 'root'@'localhost' ${INDENTIFIED_WITH_STRING} BY '${MYSQLPASSWORD}';" --host=${MYSQLHOST} >/dev/null 2>&1
			else
				${MYSQL_BIN} --user=root --password="${MYSQL_ROOT_PASS}" -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${MYSQLPASSWORD}');" --host=${MYSQLHOST} >/dev/null 2>&1 
			fi
			${MYSQL_BIN} --user=root --password="${MYSQLPASSWORD}" -e "GRANT ALL PRIVILEGES ON *.* TO 'da_admin'@'localhost' WITH GRANT OPTION;" 2>&1 >/dev/null
		
			#Dropping MySQL test databases
			${MYSQL_BIN} --user=root --password="${MYSQLPASSWORD}" -e "DROP DATABASE IF EXISTS test;" 2>&1 >/dev/null
			${MYSQL_BIN} --user=root --password="${MYSQLPASSWORD}" -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';" 2>&1 >/dev/null
			if [ "${MARIADB_OPT}" != "10.4" ] && [ "${MARIADB_OPT}" != "10.5" ] && [ "${MARIADB_OPT}" != "10.6" ] && [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
				${MYSQL_BIN} --user=root --password="${MYSQLPASSWORD}" -e "DELETE FROM mysql.user WHERE User='';" 2>&1 >/dev/null
				${MYSQL_BIN} --user=root --password="${MYSQLPASSWORD}" -e "DELETE FROM mysql.user WHERE User='root' AND Host!='localhost';" 2>&1 >/dev/null
				${MYSQL_BIN} --user=root --password="${MYSQLPASSWORD}" -e "FLUSH PRIVILEGES;"  2>&1 >/dev/null
			fi
			SQL_PATH_IS_SETUP="yes"
			initMySQL
		fi
	fi
}

doMySQL() {
	if [ "${MYSQL_INST_OPT}" != "yes" ] && [ "${MYSQL_INST_OPT}" != "mariadb" ] && [ "${MYSQL_INST_OPT}" != "mysql" ]; then
		do_exit 1 "You cannot install ${MYSQLNAME}, because you do not have it set in options.conf file."
	fi
	ensureBuildPackages
	install_debs libncurses-dev libaio1 libncurses5
	install_rpms ncurses-devel libaio

	if [ "${MYSQL_INST_OPT}" = "mysql" ] && has_mariadb && [ -e ${MYSQL_BIN} ] && [ -d ${MYSQL_DATA}/mysql ]; then
		MYSQL_MAIN="`mysql_main`"
		if [ "${MYSQL_MAIN}" != "5.5" ] && [ "${MYSQL_OPT}" != "5.5" ]; then
			echo "mysql_inst=mysql is set in the options.conf, but MariaDB is currently installed"
			do_exit 1 "If you wish to use MySQL, please install MySQL 5.5 first, and then you'd be able to upgrade to a newer version of it. Please note that MariaDB 10.x migration to MySQL is considered a downgrade and might not work."
		fi
	fi

	if [ "${MYSQL_INST_OPT}" = "mysql" ] && [ -e ${MYSQL_BIN} ] && [ -d ${MYSQL_DATA}/mysql ]; then
		MYSQL_MAIN="`mysql_main`"
		if [ "${MYSQL_MAIN}" != "${MYSQL_OPT}" ]; then
			if ! echo "5.1 ${MYSQL_SET}" | grep -m1 -q "${MYSQL_MAIN} ${MYSQL_OPT}"; then
				echo "MySQL ${MYSQL_MAIN} cannot be directly upgraded to ${MYSQL_OPT}"
				do_exit 1 "If you wish to upgrade MySQL to ${MYSQL_OPT}, do it in increments, upgrading ${MYSQL_MAIN} to the next version released, and going up until you reach ${MYSQL_OPT}."
			fi
		fi
	fi

	if [ "${MYSQL_INST_OPT}" = "mariadb" ] && [ -e ${MYSQL_BIN} ] && [ -d ${MYSQL_DATA}/mysql ]; then
		MYSQL_MAIN="`mysql_main`"
		UPGRADE_TEXT="MySQL ${MYSQL_MAIN} cannot be directly upgraded to MariaDB ${MARIADB_OPT}, as this is considered a downgrade. More info: https://help.directadmin.com/item.php?id=563"
		if [ "${MYSQL_MAIN}" = "8.0" ]; then
			do_exit 1 "${UPGRADE_TEXT}"
		elif [ "${MYSQL_MAIN}" = "5.7" ] && [ "${MYSQL_OPT}" = "5.5" ]; then
			do_exit 1 "${UPGRADE_TEXT}"
		elif [ "${MYSQL_MAIN}" = "5.7" ] && [ "${MYSQL_OPT}" = "10.0" ]; then
			do_exit 1 "${UPGRADE_TEXT}"
		elif [ "${MYSQL_MAIN}" = "5.7" ] && [ "${MYSQL_OPT}" = "10.1" ]; then
			do_exit 1 "${UPGRADE_TEXT}"
		fi
	fi

	if ! grep -m1 -q 'mysql' /etc/group; then
		addUserGroup mysql mysql 
	fi

	if [ ! -d /var/run/mysqld ]; then
		mkdir -p /var/run/mysqld
		chown -R mysql:mysql /var/run/mysqld
		chmod 700 /var/run/mysqld
	fi

	doMySQLback

	if [ ! -e /root/.skip_mysql_install ]; then
		#setup a basic my.cnf file.
		MYCNF=/etc/my.cnf
		if [ ! -e $MYCNF ]; then
			echo "[mysqld]" > $MYCNF
			echo "local-infile=0" >> $MYCNF
			echo "innodb_file_per_table" >> $MYCNF

			#we don't want conflicts
			if distro_is_debian; then
				echo "" >> $MYCNF
				echo "[client]" >> $MYCNF
				echo "socket=/usr/local/mysql/data/mysql.sock" >> $MYCNF
				if [ -d /etc/mysql ]; then
					mv /etc/mysql /etc/mysql.moved
				fi
			fi
			if rhel_version_is 9; then
				echo "" >> $MYCNF
				echo "[client]" >> $MYCNF
				echo "socket=/var/lib/mysql/mysql.sock" >> $MYCNF
			fi
		fi
	fi
	cd ${WORKDIR}

	SQL_PATH=${WORKDIR}/mysql
	mkdir -p ${SQL_PATH}

	set_service mysqld OFF
	initMySQL

	NEW_MYSQLCHECK_ARGS=false
	if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
		if [ "${MYSQL_OPT}" = "5.7" ] || [ "${MYSQL_OPT}" = "8.0" ]; then
			NEW_MYSQLCHECK_ARGS=true
		fi
	fi

	if ${NEW_MYSQLCHECK_ARGS}; then
		MYSQLCHECK_ARGS="-A"
	else
		MYSQLCHECK_ARGS="--fix-db-names --fix-table-names -A"
	fi

	if distro_is_debian || rhel_version_is 9 || [ "${MYSQL_FORCE_COMPILE_OPT}" = "yes" ]; then
		if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
			#libsystemd-daemon0 and /lib/x86_64-linux-gnu/libsystemd-daemon.so.0
			#LINUX_STR=linux-systemd
			LINUX_STR=linux-systemd
			MACHINE=x86_64
			if is_arm64; then
				MACHINE=aarch64
			fi

			MYSQLURL=${WEBPATH_SERVICES}/all/mariadb/${MARIADB_OPT}/${MARIADB_VER}
			MYSQLPACK=mariadb-${MARIADB_VER}-${LINUX_STR}-${MACHINE}
		else
			MACHINE=x86_64
			MYSQLURL=${WEBPATH_SERVICES}/all/mysql/${MYSQL_OPT}/${MYSQL_VER}/64-bit
			LINUX_STR=linux-glibc2.12
			MYSQLPACK=mysql-${MYSQL_VER}-${LINUX_STR}-${MACHINE}
		fi

		if [ "${MYSQL_INST_OPT}" = "mariadb" ] && [ "${MARIADB_OPT}" = "10.6" ]; then
			ensure_libpmem
		fi
		#debian needs libnuma1 now, as well: libnuma-dev libnuma1
		ensure_libnuma
		ensure_libtirpc
		ensure_rpcgen
			
		cd /usr/local
		if [ "${MYSQL_OPT}" = "8.0" ] && [ "${MYSQL_INST_OPT}" = "mysql" ]; then
			install_rpms xz
			install_debs xz-utils
			MYSQL_PACK_EXT="tar.xz"
			MYSQL_EXTRACT_OPT="xJf"
			MYSQL_CONTENT_OPT="tJf"
		else
			MYSQL_PACK_EXT="tar.gz"
			MYSQL_EXTRACT_OPT="xzf"
			MYSQL_CONTENT_OPT="tzf"
		fi
		if [ "${MYSQL_FORCE_COMPILE_OPT}" != "yes" ]; then
			if [ ! -s ${MYSQLPACK}.${MYSQL_PACK_EXT} ]; then
				safeDownloadWithMove "/usr/local/${MYSQLPACK}.${MYSQL_PACK_EXT}" "${MYSQLURL}/${MYSQLPACK}.${MYSQL_PACK_EXT}"
			fi
		fi

		if [ ! -s "/usr/local/${MYSQLPACK}.${MYSQL_PACK_EXT}" ]; then
			MYSQL_FORCE_COMPILE_OPT=yes
		fi

		if [ "${MYSQL_FORCE_COMPILE_OPT}" = "yes" ]; then
			if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
				install_debs libsystemd-dev libssl-dev
			else
				install_debs zlib1g-dev libssl-dev pkg-config
			fi
			ensure_cmake
			echo "Attempting to compile a package from source..."
			cd ${WORKDIR}
			compile_mysql_binary
			cd ${WORKDIR}

			if [ ! -s ${MYSQLPACK}.${MYSQL_PACK_EXT} ]; then
				#sometimes it's linux, sometimes it's linux2.6.. sometimes it's just linux.
				#Debian 6 was kernel 2.6, but when 5.6 is compiled, is linux. 5.5 is linux. Consistent? no.
				if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
					PACK_PRE=mariadb-${MARIADB_VER}
				else
					PACK_PRE=mysql-${MYSQL_VER}
				fi
				BINPACK=`ls ${PACK_PRE}-*aarch64.${MYSQL_PACK_EXT} ${PACK_PRE}-*i386.${MYSQL_PACK_EXT} ${PACK_PRE}-*i686.${MYSQL_PACK_EXT} ${PACK_PRE}-*i486.${MYSQL_PACK_EXT} ${PACK_PRE}-*x86_64.${MYSQL_PACK_EXT} 2>/dev/null | head -n 1`

				if [ "$BINPACK" = "" ]; then
					do_exit 1 "Cannot find ${MYSQLPACK} package for installation"
				fi

				echo "Found created package: $BINPACK"

				GLIBC14_BINPACK=`echo $BINPACK | grep -c 'linux-glibc_214'`
				if [ ${GLIBC14_BINPACK} -gt 0 ]; then
					LINUX_STR=`echo $BINPACK | cut -d- -f3,4`
					MACHINE=`echo $BINPACK | cut -d- -f5 | cut -d. -f1`
				else
					LINUX_STR=`echo $BINPACK | cut -d- -f3`
					MACHINE=`echo $BINPACK | cut -d- -f4 | cut -d. -f1`
				fi

				if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
					MYSQLPACK=mariadb-${MARIADB_VER}-${LINUX_STR}-${MACHINE}
				else
					MYSQLPACK=mysql-${MYSQL_VER}-${LINUX_STR}-${MACHINE}
				fi
			fi
			mv -f ${MYSQLPACK}.${MYSQL_PACK_EXT} /usr/local 2>/dev/null
		fi

		cd /usr/local
		
		#we need the non tar.gz form .. but its not basic, it differs from tar.gz
		#since we know the name of the file, we can get its contents which will tell us.
		MYSQLPACK_REALNAME=`tar ${MYSQL_CONTENT_OPT} ${MYSQLPACK}.${MYSQL_PACK_EXT} | head -n 1 | cut -d/ -f1`
		if [ "${MYSQLPACK_REALNAME}" = "" ]; then
			do_exit 1 "MYSQLPACK_REALNAME is invalid: ${MYSQLPACK_REALNAME}. Exiting..."
		fi

		echo "Stopping mysqld ..."
		control_service mysqld stop
		if systemctl is-active --quiet mysqld; then
			echo "Service didn't get stopped, sleeping for 20 secs and re-trying ..."
			sleep 20
			echo "Stopping mysqld ..."
			control_service mysqld stop
		fi

		if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
			if [ "${MYSQL_OPT}" = "5.7" ]; then
				MYSQL_SYSTEMD=${CB_SYSTEMD}/mysqld57.service.binary
				if [ -e ${CB_CUST_SYSTEMD}/mysqld57.service.binary ]; then
					MYSQL_SYSTEMD=${CB_CUST_SYSTEMD}/mysqld57.service.binary
				fi
			else
				MYSQL_SYSTEMD=${CB_SYSTEMD}/mysqld.service.binary
				if [ -e ${CB_CUST_SYSTEMD}/mysqld.service.binary ]; then
					MYSQL_SYSTEMD=${CB_CUST_SYSTEMD}/mysqld.service.binary
				fi
			fi
			if distro_is_debian && [ -e ${CB_CUST_SYSTEMD}/mysqld.service.debian ]; then
				MYSQL_SYSTEMD=${CB_CUST_SYSTEMD}/mysqld.service.debian
			fi
		else
			MYSQL_SYSTEMD=${CB_SYSTEMD}/mariadb.service.binary
			if [ -e ${CB_CUST_SYSTEMD}/mariadb.service.binary ]; then
				MYSQL_SYSTEMD=${CB_CUST_SYSTEMD}/mariadb.service.binary
			fi
		fi
					
		cp -pf ${MYSQL_SYSTEMD} ${SYSTEMDDIR}/mysqld.service
		if [ -L ${SYSTEMDDIR}/mariadb.service ]; then
				rm -f ${SYSTEMDDIR}/mariadb.service
		fi
		DISABLE_PRIVATETMP=false
		if [ -e /proc/1/environ ]; then
			if cat /proc/1/environ | tr '\0' '\n' | grep -q ^container=lxc; then
				DISABLE_PRIVATETMP=true
			fi
		fi
		if ${DISABLE_PRIVATETMP}; then
			echo "LXC detected. Disabling PrivateTmp feature in mysqld.service for MySQL."
			perl -pi -e 's#PrivateTmp\=true#PrivateTmp=false#' ${SYSTEMDDIR}/mysqld.service
		fi
		if [ "${MYSQL_DATA}" != "/var/lib/mysql" ] && [ ! -e /var/lib/mysql ]; then
			ln -s "${MYSQL_DATA}" /var/lib/mysql
		fi
		if [ -d "/home/mysql" ]; then
			perl -pi -e 's#ProtectHome\=true#ProtectHome=false#' ${SYSTEMDDIR}/mysqld.service
		fi
		if [ -e ${SYSTEMDDIR}/mysql.service ]; then
			systemctl disable mysql.service
			mv -f ${SYSTEMDDIR}/mysql.service ${SYSTEMDDIR}/mysqld.service
			systemctl daemon-reload
			systemctl enable mysqld.service
		fi
		systemctl daemon-reload
		systemctl enable mysqld.service

		backup_libmysqlclient

		tar ${MYSQL_EXTRACT_OPT} ${MYSQLPACK}.${MYSQL_PACK_EXT} --no-same-owner --exclude="${MYSQLPACK}/data"
		if [ $? -ne 0 ]; then
			do_exit 1 "Failed to extract: ${MYSQLPACK}.${MYSQL_PACK_EXT}. Exiting..."
		fi
		rm -f mysql ${MYSQLPACK}.${MYSQL_PACK_EXT}
		ln -s ${MYSQLPACK_REALNAME} mysql
		cd mysql

		chown -R mysql:mysql /usr/local/mysql
		chown -R mysql:mysql /usr/local/${MYSQLPACK_REALNAME}

		if [ -e my.cnf ]; then
			mv -f my.cnf my.cnf.orig
		fi

		if [ -d data ]; then
			rm -rf data
		fi
		ln -s ${MYSQL_DATA} ./data 2>/dev/null

		for i in /usr/local/mysql/bin/*; do {
			if [ ! -e /usr/local/bin/${i##*/} ]; then
				echo "Linking ${i} -> /usr/local/bin/${i##*/}..."
				ln -s "${i}" "/usr/local/bin/${i##*/}"
				chown -h mysql. "/usr/local/bin/${i##*/}"
			fi
		};
		done

		if [ -d ${MYSQL_DATA} ]; then
			chown -R mysql:mysql ${MYSQL_DATA}
		fi

		MYSQLPATH="`echo ${PATH} | grep /usr/local/mysql/bin | wc -l`"
		if [ "${MYSQLPATH}" -eq 0 ]; then
			export PATH=${PATH}:/usr/local/mysql/bin
		fi

		if [ -d /etc/mysql ]; then
			if [ ! -L /etc/mysql/my.cnf ]; then
				mv -f /etc/mysql/my.cnf /etc/mysql/my.cnf.back
				ln -s /etc/my.cnf /etc/mysql/my.cnf
			fi
		fi
		if rhel_version_is 9; then
			if [ ! -e /usr/lib64/libncurses.so.5 ] && [ -e /usr/lib64/libncurses.so.6 ]; then
				#no libncurses-compat-libs there, symlinking .6 to .5 does the trick
				ln -sf /usr/lib64/libncurses.so.6 /usr/lib64/libncurses.so.5
			fi
			if [ ! -e /usr/lib64/libtinfo.so.5 ] && [ -e /usr/lib64/libtinfo.so.6 ]; then
				#no libncurses-compat-libs there, symlinking .6 to .5 does the trick
				ln -sf /usr/lib64/libtinfo.so.6 /usr/lib64/libtinfo.so.5
			fi
		fi
		setup_my_cnf
		if ! ${SQL_PATH_IS_EMPTY}; then
			control_service mysqld start

			echo "Giving mysqld a few seconds to start up..."
			sleep 5
		
			if ! /usr/local/mysql/bin/mysql --defaults-extra-file=${DA_MY_CNF} -e "select 1" >/dev/null 2>&1; then
				echo "Giving mysqld a another few seconds to start up..."
				sleep 10
			fi

			if ! /usr/local/mysql/bin/mysql --defaults-extra-file=${DA_MY_CNF} -e "select 1" >/dev/null 2>&1; then
				echo "Giving mysqld last 20 seconds to start up..."
				sleep 20
			fi

			if [ -e /usr/local/mysql/bin/mysql_upgrade ]; then
				if ! ${SKIP_MYSQL_UPGRADE}; then
					MARIADB_SKIP_VERSION_CHECK=
					if [ "`/usr/local/mysql/bin/mysql_upgrade --help | grep -c skip-version-check`" -gt 0 ]; then
						MARIADB_SKIP_VERSION_CHECK=--skip-version-check
					fi

					/usr/local/mysql/bin/mysql_upgrade --defaults-extra-file=${DA_MY_CNF} ${MARIADB_SKIP_VERSION_CHECK}
					
					if [ "$?" -ne 0 ]; then		#Ticket 23399
						echo "${boldon}Error running '/usr/local/mysql/bin/mysql_upgrade --defaults-extra-file=${DA_MY_CNF} ${MARIADB_SKIP_VERSION_CHECK}'${boldoff}"
						sleep 10				
					fi
				fi
			elif [ -e /usr/local/mysql/bin/mysql_fix_privilege_tables ]; then
				/usr/local/mysql/bin/mysql_fix_privilege_tables --defaults-extra-file=${DA_MY_CNF}
			fi
		fi

		restore_libmysqlclient

		if ${SQL_PATH_IS_EMPTY}; then
			setup_mysql_root_user
		fi
		set_service mysqld ON
		writeLog "${MYSQLPACK} installed"
	else
		if [ "${MYSQL_OPT}" = "5.5" ] || [ "${MYSQL_OPT}" = "5.6" ] || [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
			if [ ! -e /usr/lib/libaio.so.1 ] && [ ! -e /usr/lib64/libaio.so.1 ] && [ ! -e /lib64/libaio.so.1 ] && [ ! -e /lib/libaio.so.1 ] && [ ! -e /lib/i386-linux-gnu/libaio.so.1 ]; then
				echo "Cannot find libaio.so.1, installing using yum..."
				install_rpms libaio
			fi
		fi
		
		if [ "${MYSQL_INST_OPT}" = "mariadb" ] && [ "${MARIADB_OPT}" = "10.6" ]; then
			ensure_libpmem
		fi

		ensure_libnuma
		ensure_libtirpc
		ensure_rpcgen
		
		if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
			MYSQL_NAME=MySQL
			if rhel_version_is 7; then
				MYSQL_EXT_OS=el7
			elif rhel_version_is 8; then
				MYSQL_EXT_OS=el8
			fi
			MYSQLURL=all/mysql/${MYSQL_OPT}/${MYSQL_VER}/64-bit
			MYSQL_EXT=${MYSQL_EXT_OS}.x86_64
			
			if [ "${MYSQL_OPT}" != "5.5" ] && [ "${MYSQL_OPT}" != "5.6" ]; then
				MYSQL_NAME=mysql-community
			fi

			MYSQLCLIENT=${MYSQL_NAME}-client-${MYSQL_VER}-1.$MYSQL_EXT.rpm
			MYSQLDEVEL=${MYSQL_NAME}-devel-${MYSQL_VER}-1.$MYSQL_EXT.rpm
			MYSQLSERVER=${MYSQL_NAME}-server-${MYSQL_VER}-1.$MYSQL_EXT.rpm
			MYSQLSHARED=${MYSQL_NAME}-shared-${MYSQL_VER}-1.$MYSQL_EXT.rpm
			if [ "${MYSQL_OPT}" = "5.7" ] || [ "${MYSQL_OPT}" = "8.0" ]; then
				MYSQLLIBS=${MYSQL_NAME}-libs-${MYSQL_VER}-1.$MYSQL_EXT.rpm
				if rhel_version_is 7; then
					MYSQLLIBSCOMPAT=${MYSQL_NAME}-libs-compat-${MYSQL_VER}-1.$MYSQL_EXT.rpm
				fi
				MYSQLCOMMON=${MYSQL_NAME}-common-${MYSQL_VER}-1.$MYSQL_EXT.rpm
			fi
		else
			MYSQLURL=all/mariadb/${MARIADB_OPT}/${MARIADB_VER}
			if rhel_version_is 7; then
				RPM_FILE_LIST="centos7-64.txt"
			else
				RPM_FILE_LIST="centos8-64.txt"
			fi

			if [ ! -s mysql/${RPM_FILE_LIST} ]; then
				safeDownloadWithMove "${WORKDIR}/mysql/${RPM_FILE_LIST}" "${WEBPATH_SERVICES}/${MYSQLURL}/${RPM_FILE_LIST}"
			fi

			if ! grep -m1 -q "MariaDB-${MARIADB_VER}-" mysql/${RPM_FILE_LIST}; then
				rm -f mysql/${RPM_FILE_LIST}
				safeDownloadWithMove "${WORKDIR}/mysql/${RPM_FILE_LIST}" "${WEBPATH_SERVICES}/${MYSQLURL}/${RPM_FILE_LIST}"
			fi

			if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
				if [ "${MARIADB_OPT}" != "5.5" ] && [ "${MARIADB_OPT}" != "10.0" ]; then
					GALERA_VER=${versions_txt["galera_versions"]}
					if rhel_version_is 7; then
						LIBJEMALLOC_VER=${versions_txt["jemalloc_versions"]}
						LIBJEMALLOC_FILE=jemalloc-${LIBJEMALLOC_VER}-1.el7.x86_64.rpm
						LIBJEMALLOC_DEV_FILE=jemalloc-devel-${LIBJEMALLOC_VER}-1.el7.x86_64.rpm
						GALERA_FILE=galera-4-${GALERA_VER}-1.el7.centos.x86_64.rpm
					else
						GALERA_FILE=galera-4-${GALERA_VER}-1.el8.x86_64.rpm
					fi
				fi
			fi
			MYSQLCLIENT=`get_line_from_file "MariaDB-.*client.*.rpm" mysql/${RPM_FILE_LIST}`
			MYSQLDEVEL=`get_line_from_file "MariaDB-.*devel.*.rpm" mysql/${RPM_FILE_LIST}`
			MYSQLSERVER=`get_line_from_file "MariaDB-.*server.*.rpm" mysql/${RPM_FILE_LIST}`
			MYSQLSHARED=`get_line_from_file "MariaDB-.*shared.*.rpm" mysql/${RPM_FILE_LIST}`
			MYSQLCOMMON=`get_line_from_file "MariaDB-.*common.*.rpm" mysql/${RPM_FILE_LIST}`
			MYSQLBACKUP=`get_line_from_file "MariaDB-.*backup.*.rpm" mysql/${RPM_FILE_LIST}`
			if rhel_version_is 7; then
				MYSQLCOMPAT=`get_line_from_file "MariaDB-.*compat.*.rpm" mysql/${RPM_FILE_LIST}`
				HAS_MYSQLCOMPAT=true
			else
				MYSQLCOMPAT=""
				HAS_MYSQLCOMPAT=false
			fi

			if [ "${MYSQLCLIENT}" = "" ] || [ "${MYSQLCLIENT}" = "" ] || [ "${MYSQLCLIENT}" = "" ] || [ "${MYSQLCLIENT}" = "" ] || [ "${MYSQLCLIENT}" = "" ]; then
				do_exit 1 "RPM package set is incomplete. Unable to find names in mysql/${RPM_FILE_LIST}."
			fi
		fi

		cd ${SQL_PATH}

		MYSQL57_8x_SET=false
		if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
			if [ "${MYSQL_OPT}" = "5.7" ] || [ "${MYSQL_OPT}" = "8.0" ]; then
				MYSQL57_8x_SET=true
			fi
		fi
			
		if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
			if [ "${MARIADB_OPT}" != "5.5" ] && [ "${MARIADB_OPT}" != "10.0" ]; then
				if rhel_version_is 7; then
					if [ ! -s ${SQL_PATH}/${LIBJEMALLOC_FILE} ]; then
						safeDownloadWithMove "${WORKDIR}/mysql/${LIBJEMALLOC_FILE}" "${WEBPATH_SERVICES}/all/mariadb/jemalloc/${LIBJEMALLOC_VER}/${LIBJEMALLOC_FILE}"
					fi
					if [ ! -s ${SQL_PATH}/${LIBJEMALLOC_DEV_FILE} ]; then
						safeDownloadWithMove "${WORKDIR}/mysql/${LIBJEMALLOC_DEV_FILE}" "${WEBPATH_SERVICES}/all/mariadb/jemalloc/${LIBJEMALLOC_VER}/${LIBJEMALLOC_DEV_FILE}"
					fi
				fi
				if [ ! -s ${SQL_PATH}/${GALERA_FILE} ]; then
					safeDownloadWithMove "${WORKDIR}/mysql/${GALERA_FILE}" "${WEBPATH_SERVICES}/all/mariadb/galera/${GALERA_VER}/${GALERA_FILE}"
				fi
				if [ ! -s ${SQL_PATH}/${MYSQLBACKUP} ]; then
					safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLBACKUP}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLBACKUP}"
				fi
			fi
		fi
		if [ ! -s ${SQL_PATH}/${MYSQLCLIENT} ]; then
			safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLCLIENT}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLCLIENT}"
		fi
		if [ ! -s ${SQL_PATH}/${MYSQLDEVEL} ]; then
			safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLDEVEL}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLDEVEL}"
		fi
		if [ ! -s ${SQL_PATH}/${MYSQLSERVER} ]; then
			safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLSERVER}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLSERVER}"
		fi
		if [ ! -s ${SQL_PATH}/${MYSQLSHARED} ]; then
			if ! ${MYSQL57_8x_SET}; then
				safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLSHARED}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLSHARED}"
			fi
		fi
		ADD_MYSQL_LIBS=""
		if ${MYSQL57_8x_SET}; then
			if [ ! -s ${SQL_PATH}/${MYSQLLIBS} ]; then
				safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLLIBS}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLLIBS}"
			fi
			if [ ! -s ${SQL_PATH}/${MYSQLCOMMON} ]; then
				safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLCOMMON}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLCOMMON}"
			fi
			if rhel_version_is 7; then
				if [ ! -s ${SQL_PATH}/${MYSQLLIBSCOMPAT} ]; then
					safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLLIBSCOMPAT}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLLIBSCOMPAT}"
				fi
				ADD_MYSQL_LIBS="${MYSQLLIBS} ${MYSQLLIBSCOMPAT} ${MYSQLCOMMON}"
			else
				ADD_MYSQL_LIBS="${MYSQLLIBS} ${MYSQLCOMMON}"
			fi
		else
			ADD_MYSQL_LIBS=${MYSQLSHARED}
		fi
		if [ "${MYSQL_INST_OPT}" = "mariadb" ] || has_mariadb; then
			if [ ! -s ${SQL_PATH}/${MYSQLCOMMON} ]; then
				safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLCOMMON}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLCOMMON}"
			fi
			if ${HAS_MYSQLCOMPAT}; then
				if [ ! -s ${SQL_PATH}/${MYSQLCOMPAT} ]; then
					safeDownloadWithMove "${WORKDIR}/mysql/${MYSQLCOMPAT}" "${WEBPATH_SERVICES}/${MYSQLURL}/${MYSQLCOMPAT}"
				fi
			fi
		fi
		
		cd ${SQL_PATH}
		
		FILE1=${SQL_PATH}/${MYSQLCLIENT}
		FILE2=${SQL_PATH}/${MYSQLDEVEL}
		FILE3=${SQL_PATH}/${MYSQLSERVER}
		FILE4=${SQL_PATH}/${MYSQLSHARED}
		if [ "${MYSQL_INST_OPT}" = "mariadb" ] || has_mariadb; then
			FILE5=${SQL_PATH}/${MYSQLCOMMON}
			if ${HAS_MYSQLCOMPAT}; then
				FILE6=${SQL_PATH}/${MYSQLCOMPAT}
			fi
			if [ "${MARIADB_OPT}" = "10.1" ] || [ "${MARIADB_OPT}" = "10.2" ] || [ "${MARIADB_OPT}" = "10.3" ] || [ "${MARIADB_OPT}" = "10.4" ] || [ "${MARIADB_OPT}" = "10.5" ] || [ "${MARIADB_OPT}" = "10.6" ]; then
				FILE10=${SQL_PATH}/${MYSQLBACKUP}
			fi
		fi
		if ${MYSQL57_8x_SET}; then
			FILE7=${SQL_PATH}/${MYSQLLIBS}
			if rhel_version_is 7; then
				FILE8=${SQL_PATH}/${MYSQLLIBSCOMPAT}
			fi
			FILE9=${SQL_PATH}/${MYSQLCOMMON}
		fi
		checkFile ${FILE1}
		checkFile ${FILE2}
		checkFile ${FILE3}
		if ! ${MYSQL57_8x_SET}; then
			checkFile ${FILE4}
		fi
		if [ "${MYSQL_INST_OPT}" = "mariadb" ] ; then
			checkFile ${FILE5}
			if ${HAS_MYSQLCOMPAT}; then
				checkFile ${FILE6}
			fi
			if [ "${MARIADB_OPT}" = "10.1" ] || [ "${MARIADB_OPT}" = "10.2" ] || [ "${MARIADB_OPT}" = "10.3" ] || [ "${MARIADB_OPT}" = "10.4" ] || [ "${MARIADB_OPT}" = "10.5" ] || [ "${MARIADB_OPT}" = "10.6" ]; then
				checkFile ${FILE10}
			fi
			echo "Installing dependencies..."
			if rhel_version_is 7 || rhel_version_is 8; then
				install_rpms boost-program-options perl-Compress-Raw-Bzip2 perl-Compress-Raw-Zlib perl-Compress-Raw-Zlib perl-DBI perl-Data-Dumper perl-IO-Compress perl-Net-Daemon perl-PlRPC lsof nmap rsync pcre2 socat
			fi
		fi
		if ${MYSQL57_8x_SET}; then
			checkFile ${FILE7}
			if rhel_version_is 7; then
				checkFile ${FILE8}
			fi
			checkFile ${FILE9}
		fi

		if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
			if [ "${MARIADB_OPT}" = "10.1" ] || [ "${MARIADB_OPT}" = "10.2" ] || [ "${MARIADB_OPT}" = "10.3" ] || [ "${MARIADB_OPT}" = "10.4" ] || [ "${MARIADB_OPT}" = "10.5" ] || [ "${MARIADB_OPT}" = "10.6" ]; then
				if rhel_version_is 7; then
					echo "Installing libjemalloc..."
					checkFile ${SQL_PATH}/${LIBJEMALLOC_FILE}
					checkFile ${SQL_PATH}/${LIBJEMALLOC_DEV_FILE}
					rpm -Uhv --nodeps --force ${SQL_PATH}/${LIBJEMALLOC_FILE} ${SQL_PATH}/${LIBJEMALLOC_DEV_FILE}
				fi
				echo "Installing galera..."
				checkFile ${SQL_PATH}/${GALERA_FILE}
				rpm -Uhv --nodeps --force ${SQL_PATH}/${GALERA_FILE}
			fi
		fi
		
		echo "Stopping mysqld ..."
		control_service mysqld stop
		if systemctl is-active --quiet mysqld; then
			echo "Service didn't get stopped, sleeping for 20 secs and re-trying ..."
			sleep 20
			echo "Stopping mysqld ..."
			control_service mysqld stop
		fi

		#MariaDB renames my.cnf to rpmsave when removing RPMs, if we detect rpmsave before installation, we rename the file: https://mariadb.atlassian.net/browse/MDEV-4954
		if [ -e /etc/my.cnf.rpmsave ]; then
			mv -f /etc/my.cnf.rpmsave /etc/my.cnf.rpmsave.custombuild
		fi
		if [ -e /etc/logrotate.d/mysql.rpmsave ]; then
			mv -f /etc/logrotate.d/mysql.rpmsave /etc/logrotate.d/mysql.rpmsave.custombuild
		fi
		if [ -e /etc/logrotate.d/mysql ]; then
			mv -f /etc/logrotate.d/mysql /etc/logrotate.d/mysql.rpmsave
		fi
		if [ -e /etc/my.cnf.d/mysql-clients.cnf.rpmsave ]; then
			mv -f /etc/my.cnf.d/mysql-clients.cnf.rpmsave /etc/my.cnf.d/mysql-clients.cnf.rpmsave.custombuild
		fi
		if [ -e /etc/my.cnf.d/server.cnf.rpmsave ]; then
			mv -f /etc/my.cnf.d/server.cnf.rpmsave /etc/my.cnf.d/server.cnf.rpmsave.custombuild
		fi

		if [ -e /usr/bin/mysql ]; then
			MYSQL_MAIN="`mysql_main`"
			MYSQL_V="`/usr/bin/mysql --version | grep -m1 -o '[0-9]*\.[0-9]*\.[0-9]*'`"
			MYSQL_UPGRADE="`/usr/bin/mysql --version | grep -c MariaDB`"
			if  [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
				MYSQL_UPGRADE_VER=${MARIADB_OPT}
			else
				MYSQL_UPGRADE_VER=${MYSQL_OPT}
			fi
			#Switch from MySQL to MariaDB
			if [ "${MYSQL_INST_OPT}" = "mariadb" ] && [ "${MYSQL_UPGRADE}" = "0" ]; then
				echo "Upgrading MySQL ${MYSQL_MAIN} to MariaDB ${MARIADB_OPT}"
				for i in `rpm -qa | grep -i "^mysql" | grep -v "MySQL-python"`; do
					rpm -ev --noscripts $i --nodeps
				done
				for i in `rpm -qa | grep -i "^mariadb"`; do
					rpm -ev --noscripts $i --nodeps
				done
				if [ "${MARIADB_OPT}" = "10.1" ] || [ "${MARIADB_OPT}" = "10.2" ] || [ "${MARIADB_OPT}" = "10.3" ] || [ "${MARIADB_OPT}" = "10.4" ] || [ "${MARIADB_OPT}" = "10.5" ] || [ "${MARIADB_OPT}" = "10.6" ]; then
					rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${MYSQLSHARED} ${MYSQLCOMMON} ${MYSQLCOMPAT} ${MYSQLBACKUP}
				else
					rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${MYSQLSHARED} ${MYSQLCOMMON} ${MYSQLCOMPAT}
				fi
			#Switch from MariaDB to MySQL
			elif [ "${MYSQL_INST_OPT}" = "mysql" ] && [ "${MYSQL_UPGRADE}" = "1" ]; then
				echo "Upgrading MariaDB ${MYSQL_MAIN} to MySQL ${MYSQL_OPT}"
				for i in `rpm -qa | grep -i "^mysql" | grep -v "MySQL-python"`; do
					rpm -ev --noscripts $i --nodeps
				done
				for i in `rpm -qa | grep -i "^mariadb"`; do
					rpm -ev --noscripts $i --nodeps
				done
				if ${MYSQL57_8x_SET}; then
					rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${ADD_MYSQL_LIBS}
				else
					rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${MYSQLSHARED} ${MYSQLCOMMON} ${MYSQLCOMPAT}
				fi
			elif [ "${MYSQL_MAIN}" != "${MYSQL_UPGRADE_VER}" ]; then
				if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
					echo "Upgrading ${MYSQLNAME} ${MYSQL_V} to ${MYSQL_VER}"
					for i in `rpm -qa | grep -i "^mysql" | grep -v "MySQL-python"`; do
						rpm -ev --noscripts $i --nodeps
					done
					
					rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${ADD_MYSQL_LIBS}
				else
					echo "Upgrading ${MYSQLNAME} ${MYSQL_V} to ${MARIADB_VER}"
					for i in `rpm -qa | grep -i "^mysql" | grep -v "MySQL-python"`; do
						rpm -ev --noscripts $i --nodeps
					done
					for i in `rpm -qa | grep -i "^mariadb"`; do
						rpm -ev --noscripts $i --nodeps
					done
					if [ "${MARIADB_OPT}" = "10.1" ] || [ "${MARIADB_OPT}" = "10.2" ] || [ "${MARIADB_OPT}" = "10.3" ] || [ "${MARIADB_OPT}" = "10.4" ] || [ "${MARIADB_OPT}" = "10.5" ] || [ "${MARIADB_OPT}" = "10.6" ]; then
						rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${MYSQLSHARED} ${MYSQLCOMMON} ${MYSQLCOMPAT} ${MYSQLBACKUP}
					else
						rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${MYSQLSHARED} ${MYSQLCOMMON} ${MYSQLCOMPAT}
					fi
				fi
			else
				if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
					echo "Updating ${MYSQLNAME} ${MYSQL_V} to ${MYSQL_VER}"
					rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${ADD_MYSQL_LIBS}
				else
					#In case mysql=5.5 & mariadb=5.5
					for i in `rpm -qa | grep -i "^mysql" | grep -v "MySQL-python"`; do
						rpm -ev --noscripts $i --nodeps
					done
					echo "Updating ${MYSQLNAME} ${MYSQL_V} to ${MARIADB_VER}"
					if [ "${MARIADB_OPT}" = "10.1" ] || [ "${MARIADB_OPT}" = "10.2" ] || [ "${MARIADB_OPT}" = "10.3" ] || [ "${MARIADB_OPT}" = "10.4" ] || [ "${MARIADB_OPT}" = "10.5" ] || [ "${MARIADB_OPT}" = "10.6" ]; then
						rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${MYSQLSHARED} ${MYSQLCOMMON} ${MYSQLCOMPAT} ${MYSQLBACKUP}
					else
						rpm -Uhv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${MYSQLSHARED} ${MYSQLCOMMON} ${MYSQLCOMPAT}
					fi
				fi
			fi
		else
			if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
				echo "Cannot find /usr/bin/mysql, installing MySQL"
				rpm -ihv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${ADD_MYSQL_LIBS}
			else
				echo "Cannot find /usr/bin/mysql, installing MariaDB"
				if [ "${MARIADB_OPT}" = "10.1" ] || [ "${MARIADB_OPT}" = "10.2" ] || [ "${MARIADB_OPT}" = "10.3" ] || [ "${MARIADB_OPT}" = "10.4" ] || [ "${MARIADB_OPT}" = "10.5" ] || [ "${MARIADB_OPT}" = "10.6" ]; then
					rpm -ihv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${MYSQLSHARED} ${MYSQLCOMMON} ${MYSQLCOMPAT} ${MYSQLBACKUP}
				else
					rpm -ihv --nodeps --force ${MYSQLCLIENT} ${MYSQLDEVEL} ${MYSQLSERVER} ${MYSQLSHARED} ${MYSQLCOMMON} ${MYSQLCOMPAT}
				fi
			fi
		fi

		#Move rpmsave file back to original one: https://mariadb.atlassian.net/browse/MDEV-4954 
		if [ -e /etc/my.cnf.rpmsave ]; then
			if [ -e /etc/my.cnf ]; then
				mv -f /etc/my.cnf /etc/my.cnf.rpmnew
			fi
			mv -f /etc/my.cnf.rpmsave /etc/my.cnf
		fi
		if [ -e /etc/my.cnf.d/server.cnf.rpmsave ]; then
			if [ -e /etc/my.cnf.d/server.cnf ]; then
				mv -f /etc/my.cnf.d/server.cnf /etc/my.cnf.d/server.cnf.rpmnew
			fi
			mv -f /etc/my.cnf.d/server.cnf.rpmsave /etc/my.cnf.d/server.cnf
		fi
		if [ -e /etc/my.cnf.d/mysql-clients.cnf.rpmsave ]; then
			if [ -e /etc/my.cnf.d/mysql-clients.cnf ]; then
				mv -f /etc/my.cnf.d/mysql-clients.cnf /etc/my.cnf.d/mysql-clients.cnf.rpmnew
			fi
			mv -f /etc/my.cnf.d/mysql-clients.cnf.rpmsave /etc/my.cnf.d/mysql-clients.cnf
		fi
		#Move logrotate file back to original one
		if [ -e /etc/logrotate.d/mysql.rpmsave ]; then
			if [ -e /etc/logrotate.d/mysql ]; then
				mv -f /etc/logrotate.d/mysql /etc/logrotate.d/mysql.rpmnew
			fi
			mv -f /etc/logrotate.d/mysql.rpmsave /etc/logrotate.d/mysql
		fi
		MYSQL_SYSTEMD=${CB_SYSTEMD}/mysqld.service
		
		if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
			MYSQL_SYSTEMD_NAME=mysqld.service
			if [ "${MYSQL_OPT}" = "5.7" ] || [ "${MYSQL_OPT}" = "8.0" ]; then
				MYSQL_SYSTEMD=${CB_SYSTEMD}/mysqld57.service
				if [ ! -s "${MYSQL_SYSTEMD}" ] && [ -s /usr/lib/systemd/system/mysqld.service ]; then
					MYSQL_SYSTEMD=/usr/lib/systemd/system/mysqld.service
					echo "Using ${MYSQL_SYSTEMD}"
				fi
			fi
		fi

		if [ -e ${CB_CUST_SYSTEMD}/mysqld.service ]; then
			MYSQL_SYSTEMD=${CB_CUST_SYSTEMD}/mysqld.service
		fi
		if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
			MYSQL_SYSTEMD_NAME=mariadb.service
			if [ "${MARIADB_OPT}" = "10.1" ] || [ "${MARIADB_OPT}" = "10.2" ] || [ "${MARIADB_OPT}" = "10.3" ] || [ "${MARIADB_OPT}" = "10.4" ] || [ "${MARIADB_OPT}" = "10.5" ] || [ "${MARIADB_OPT}" = "10.6" ]; then
				MYSQL_SYSTEMD=${CB_SYSTEMD}/mariadb.service
				if [ -e ${CB_CUST_SYSTEMD}/mariadb.service ]; then
					MYSQL_SYSTEMD=${CB_CUST_SYSTEMD}/mariadb.service
				fi
			else
				MYSQL_SYSTEMD=${CB_SYSTEMD}/mariadb55.service
				if [ -e ${CB_CUST_SYSTEMD}/mariadb55.service ]; then
					MYSQL_SYSTEMD=${CB_CUST_SYSTEMD}/mariadb55.service
				fi
			fi
		fi
		if [ -e ${SYSTEMDDIR}/mysqld.service ] || [ -L ${SYSTEMDDIR}/mysqld.service ]; then
			rm -f ${SYSTEMDDIR}/mysqld.service
		fi
		if [ -e ${SYSTEMDDIR}/mariadb.service ] || [ -L ${SYSTEMDDIR}/mariadb.service ]; then
			rm -f ${SYSTEMDDIR}/mariadb.service
		fi
		if [ -e ${SYSTEMDDIR}/mysql.service ] || [ -L ${SYSTEMDDIR}/mysql.service ]; then
			rm -f ${SYSTEMDDIR}/mysql.service
		fi
		cp -pf ${MYSQL_SYSTEMD} ${SYSTEMDDIR}/${MYSQL_SYSTEMD_NAME}
		MYSQL_SYSTEMD_WAIT=${CB_SYSTEMD}/scripts/mysql-wait-ready
		if [ -e ${CB_CUST_SYSTEMD}/scripts/mysql-wait-ready ]; then
			MYSQL_SYSTEMD_WAIT=${CB_CUST_SYSTEMD}/scripts/mysql-wait-ready
		fi
		if [ -d /usr/libexec ]; then
			cp -f ${MYSQL_SYSTEMD_WAIT} /usr/libexec/mysql-wait-ready
		fi
		DISABLE_PRIVATETMP=false
		if [ -e /proc/1/environ ]; then
			if cat /proc/1/environ | tr '\0' '\n' | grep -q ^container=lxc; then
				DISABLE_PRIVATETMP=true
			fi
		fi
		if ${DISABLE_PRIVATETMP}; then
			echo "LXC detected. Disabling PrivateTmp feature in mysqld.service for MySQL."
			perl -pi -e 's#PrivateTmp \= true#PrivateTmp = false#' ${SYSTEMDDIR}/${MYSQL_SYSTEMD_NAME}
		fi
		systemctl daemon-reload
		systemctl enable ${MYSQL_SYSTEMD_NAME}

		setup_my_cnf

		if ! ${SQL_PATH_IS_EMPTY}; then
			control_service mysqld start

			echo "Giving mysqld a few seconds to start up..."
			sleep 5

			if ! /usr/bin/mysql --defaults-extra-file=${DA_MY_CNF} -e "select 1" >/dev/null 2>&1; then
				echo "Giving mysqld a another few seconds to start up..."
				sleep 10
			fi

			if ! /usr/bin/mysql --defaults-extra-file=${DA_MY_CNF} -e "select 1" >/dev/null 2>&1; then
				echo "Giving mysqld last 20 seconds to start up..."
				sleep 20
			fi

			if ! ${SKIP_MYSQL_UPGRADE}; then
				if [ -e /usr/bin/mysql_upgrade ]; then
					/usr/bin/mysql_upgrade --defaults-extra-file=${DA_MY_CNF}
				elif [ -e /usr/bin/mysql_fix_privilege_tables ]; then
					/usr/bin/mysql_fix_privilege_tables --defaults-extra-file=${DA_MY_CNF}
				fi
			fi

			if [ -e /usr/bin/mysqlcheck ]; then
				/usr/bin/mysqlcheck --defaults-extra-file=${DA_MY_CNF} ${MYSQLCHECK_ARGS}
			fi

			# Fixing "gcc: /usr/lib/mysql/libmysqlclient.so: No such file or directory"
			if [ -d /usr/lib/mysql ] && [ -s /usr/lib/libmysqlclient.so ] && [ -d /usr/lib/mysql/ ]; then
				cp -f /usr/lib/libmysqlclient.* /usr/lib/mysql/
			fi
		fi
		
		if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
			writeLog "${MYSQL_INST_OPT} ${MARIADB_VER} installed"
		else
			writeLog "${MYSQL_INST_OPT} ${MYSQL_VER} installed"
		fi
		
	fi

	if [ -e /etc/my.cnf ] && [ ! -h /etc/mysql/my.cnf ] && [ -d /etc/mysql ]; then
		mv /etc/mysql/my.cnf /etc/mysql/my.cnf.backup
		ln -sf /etc/my.cnf /etc/mysql/my.cnf
	fi
    
	if ${SQL_PATH_IS_EMPTY}; then
		setup_mysql_root_user
	fi
	set_service mysqld ON
	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
	echo "Restarting MySQL."
	control_service mysqld restart
	
	if [ "${MYSQL_INST_OPT}" = "mariadb" ]; then
		if [ "${MARIADB_OPT}" = "5.5" ] || [ "${MARIADB_OPT}" = "5.6" ] || [ "${MARIADB_OPT}" = "10.1" ] || [ "${MARIADB_OPT}" = "10.2" ] || [ "${MARIADB_OPT}" = "10.3" ]; then
			MAX_USERNAME_LENGTH=`${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} -e "select CHARACTER_MAXIMUM_LENGTH from information_schema.columns where table_schema = 'mysql' AND table_name = 'user' AND COLUMN_NAME = 'User';" -sss 2>/dev/null`
			if [ "${MAX_USERNAME_LENGTH}" = "16" ]; then
				echo "Increasing Max Username Length from 16 to 80..."
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.user         MODIFY User         CHAR(80)  BINARY NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.db           MODIFY User         CHAR(80)  BINARY NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.tables_priv  MODIFY User         CHAR(80)  BINARY NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.columns_priv MODIFY User         CHAR(80)  BINARY NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.procs_priv   MODIFY User         CHAR(80)  BINARY NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.proc         MODIFY definer      CHAR(141) COLLATE utf8_bin NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.event        MODIFY definer      CHAR(141) COLLATE utf8_bin NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.proxies_priv MODIFY User         CHAR(80)  COLLATE utf8_bin NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.proxies_priv MODIFY Proxied_user CHAR(80)  COLLATE utf8_bin NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.proxies_priv MODIFY Grantor      CHAR(141) COLLATE utf8_bin NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.servers      MODIFY Username     CHAR(80)                   NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.procs_priv   MODIFY Grantor      CHAR(141) COLLATE utf8_bin NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "ALTER TABLE mysql.tables_priv  MODIFY Grantor      CHAR(141) COLLATE utf8_bin NOT NULL DEFAULT '';"
				${MYSQL_BIN} --defaults-extra-file=${DA_MY_CNF} mysql -e "FLUSH PRIVILEGES;"
			fi
		fi
	fi
	echo "Installation completed."
	cd ${WORKDIR}
}

####################################################

doPhpIni() {
	if [ "${PHP_INI_OPT}" = "no" ]; then
		do_exit 1 "Cannot install php.ini because it is not set in options.conf."
	fi

	TMPVAR="PHP${PHP1_SHORTRELEASE}_DOWNLOADURL"
	safeDownloadWithMove "${WORKDIR}/php-${PHP1_RELEASE_VER}.tar.gz" "${!TMPVAR}"

	FILE=${WORKDIR}/php-${PHP1_RELEASE_VER}.tar.gz

	checkFile ${FILE}
	echo "Extracting ..."
	tar xzf ${FILE} --no-same-owner
	cd php-${PHP1_RELEASE_VER}
	if [ $? -ne 0 ]; then
		do_exit 1 "Failed to change directory to: php-${PHP1_RELEASE_VER}. Exiting..."
	fi

	COUNT=`grep -m1 -c '^date.timezone' php.ini-${PHP_INI_TYPE_OPT}`
	COUNT2=`grep -m1 -c ';date.timezone' php.ini-${PHP_INI_TYPE_OPT}`
	if [ "$COUNT" -eq 0 ] && [ "$COUNT2" -eq 0 ]; then
		echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to php.ini, please change it by yourself to fit your own needs.${boldoff}"
		echo "date.timezone = \"${PHP_TIMEZONE_OPT}\"" >> php.ini-${PHP_INI_TYPE_OPT}
	elif [ "$COUNT" -eq 0 ]; then
		echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to php.ini, please change it by yourself to fit your own needs.${boldoff}"
		perl -pi -e "s#;date.timezone.*#date.timezone = \"${PHP_TIMEZONE_OPT}\"#" php.ini-${PHP_INI_TYPE_OPT}
	fi

	/usr/bin/perl -pi -e 's/upload_max_filesize = 2M/upload_max_filesize = 64M/' php.ini-${PHP_INI_TYPE_OPT}
	/usr/bin/perl -pi -e 's/post_max_size = 8M/post_max_size = 64M/' php.ini-${PHP_INI_TYPE_OPT}

	#short_open_tag: https://help.directadmin.com/item.php?id=438
	perl -pi -e 's/^short_open_tag = Off/short_open_tag = On/' php.ini-${PHP_INI_TYPE_OPT}

	if [ "${X_MAIL_HEADER_OPT}" = "yes" ]; then
		echo "Enabling mail.add_x_header option in php.ini"
		/usr/bin/perl -pi -e 's/mail.add_x_header = Off/mail.add_x_header = On/' php.ini-${PHP_INI_TYPE_OPT}
		/usr/bin/perl -pi -e 's/mail.add_x_header = 0/mail.add_x_header = On/' php.ini-${PHP_INI_TYPE_OPT}
		if ! grep -m1 -q '^mail.add_x_header' php.ini-${PHP_INI_TYPE_OPT}; then
			echo "mail.add_x_header = On" >> php.ini-${PHP_INI_TYPE_OPT}
		fi
	else
		echo "Disabling mail.add_x_header option in php.ini"
		/usr/bin/perl -pi -e 's/^mail.add_x_header =/;mail.add_x_header =/' php.ini-${PHP_INI_TYPE_OPT}
	fi

	PHP_INI_VAR=PHP_INI_FPM${PHP1_SHORTRELEASE}
	cp -f php.ini-${PHP_INI_TYPE_OPT} ${!PHP_INI_VAR}
	writeLog "${!PHP_INI_VAR} installed"

	echo "Done for php1_release."
	
	cd ${WORKDIR}

	if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		PHP_VERSION2_EVAL_VAR=PHP${PHP2_SHORTRELEASE}_VER
		PHP_VERSION2_VAR=${!PHP_VERSION2_EVAL_VAR}
		PHP2_DOWNLOADURL="PHP${PHP2_SHORTRELEASE}_DOWNLOADURL"
		safeDownloadWithMove "${WORKDIR}/php-${PHP2_RELEASE_VER}.tar.gz" "${!PHP2_DOWNLOADURL}"
		FILE=${WORKDIR}/php-${PHP2_RELEASE_VER}.tar.gz

		checkFile ${FILE}
		echo "Extracting ..."
		tar xzf ${FILE} --no-same-owner
		cd php-${PHP2_RELEASE_VER}

		COUNT=`grep -m1 -c '^date.timezone' php.ini-${PHP_INI_TYPE_OPT}`
		COUNT2=`grep -m1 -c ';date.timezone' php.ini-${PHP_INI_TYPE_OPT}`
		if [ "$COUNT" -eq 0 ] && [ "$COUNT2" -eq 0 ]; then
			echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to php.ini, please change it by yourself to fit your own needs.${boldoff}"
			echo "date.timezone = \"${PHP_TIMEZONE_OPT}\"" >> php.ini-${PHP_INI_TYPE_OPT}
		elif [ "$COUNT" -eq 0 ]; then
			echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to php.ini, please change it by yourself to fit your own needs.${boldoff}"
			perl -pi -e "s#;date.timezone.*#date.timezone = \"${PHP_TIMEZONE_OPT}\"#" php.ini-${PHP_INI_TYPE_OPT}
		fi

		/usr/bin/perl -pi -e 's/upload_max_filesize = 2M/upload_max_filesize = 64M/' php.ini-${PHP_INI_TYPE_OPT}
		/usr/bin/perl -pi -e 's/post_max_size = 8M/post_max_size = 64M/' php.ini-${PHP_INI_TYPE_OPT}

		#short_open_tag: https://help.directadmin.com/item.php?id=438
		/usr/bin/perl -pi -e 's/^short_open_tag = Off/short_open_tag = On/' php.ini-${PHP_INI_TYPE_OPT}

		if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
			PHP_INI_VAR=PHP_INI_FPM${PHP2_SHORTRELEASE}
			cp -f php.ini-${PHP_INI_TYPE_OPT} ${!PHP_INI_VAR}
			writeLog "${!PHP_INI_VAR} installed"
		fi
		echo "Done for php2_release"
	fi

	cd ${WORKDIR}

	if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		PHP_VERSION3_EVAL_VAR=PHP${PHP3_SHORTRELEASE}_VER
		PHP_VERSION3_VAR=${!PHP_VERSION3_EVAL_VAR}
		PHP3_DOWNLOADURL="PHP${PHP3_SHORTRELEASE}_DOWNLOADURL"
		safeDownloadWithMove "${WORKDIR}/php-${PHP3_RELEASE_VER}.tar.gz" "${!PHP3_DOWNLOADURL}"
		FILE=${WORKDIR}/php-${PHP3_RELEASE_VER}.tar.gz

		checkFile ${FILE}
		echo "Extracting ..."
		tar xzf ${FILE} --no-same-owner
		cd php-${PHP3_RELEASE_VER}

		COUNT=`grep -m1 -c '^date.timezone' php.ini-${PHP_INI_TYPE_OPT}`
		COUNT2=`grep -m1 -c ';date.timezone' php.ini-${PHP_INI_TYPE_OPT}`
		if [ "$COUNT" -eq 0 ] && [ "$COUNT2" -eq 0 ]; then
			echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to php.ini, please change it by yourself to fit your own needs.${boldoff}"
			echo "date.timezone = \"${PHP_TIMEZONE_OPT}\"" >> php.ini-${PHP_INI_TYPE_OPT}
		elif [ "$COUNT" -eq 0 ]; then
			echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to php.ini, please change it by yourself to fit your own needs.${boldoff}"
			perl -pi -e "s#;date.timezone.*#date.timezone = \"${PHP_TIMEZONE_OPT}\"#" php.ini-${PHP_INI_TYPE_OPT}
		fi

		/usr/bin/perl -pi -e 's/upload_max_filesize = 2M/upload_max_filesize = 64M/' php.ini-${PHP_INI_TYPE_OPT}
		/usr/bin/perl -pi -e 's/post_max_size = 8M/post_max_size = 64M/' php.ini-${PHP_INI_TYPE_OPT}

		#short_open_tag: https://help.directadmin.com/item.php?id=438
		/usr/bin/perl -pi -e 's/^short_open_tag = Off/short_open_tag = On/' php.ini-${PHP_INI_TYPE_OPT}

		if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
			PHP_INI_VAR=PHP_INI_FPM${PHP3_SHORTRELEASE}
			cp -f php.ini-${PHP_INI_TYPE_OPT} ${!PHP_INI_VAR}
			writeLog "${!PHP_INI_VAR} installed"
		fi
		echo "Done for php3_release"
	fi

	cd ${WORKDIR}

	if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		PHP_VERSION4_EVAL_VAR=PHP${PHP4_SHORTRELEASE}_VER
		PHP_VERSION4_VAR=${!PHP_VERSION4_EVAL_VAR}
		PHP4_DOWNLOADURL="PHP${PHP4_SHORTRELEASE}_DOWNLOADURL"
		safeDownloadWithMove "${WORKDIR}/php-${PHP4_RELEASE_VER}.tar.gz" "${!PHP4_DOWNLOADURL}"
		FILE=${WORKDIR}/php-${PHP4_RELEASE_VER}.tar.gz

		checkFile ${FILE}
		echo "Extracting ..."
		tar xzf ${FILE} --no-same-owner
		cd php-${PHP4_RELEASE_VER}

		COUNT=`grep -m1 -c '^date.timezone' php.ini-${PHP_INI_TYPE_OPT}`
		COUNT2=`grep -m1 -c ';date.timezone' php.ini-${PHP_INI_TYPE_OPT}`
		if [ "$COUNT" -eq 0 ] && [ "$COUNT2" -eq 0 ]; then
			echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to php.ini, please change it by yourself to fit your own needs.${boldoff}"
			echo "date.timezone = \"${PHP_TIMEZONE_OPT}\"" >> php.ini-${PHP_INI_TYPE_OPT}
		elif [ "$COUNT" -eq 0 ]; then
			echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to php.ini, please change it by yourself to fit your own needs.${boldoff}"
			perl -pi -e "s#;date.timezone.*#date.timezone = \"${PHP_TIMEZONE_OPT}\"#" php.ini-${PHP_INI_TYPE_OPT}
		fi

		/usr/bin/perl -pi -e 's/upload_max_filesize = 2M/upload_max_filesize = 64M/' php.ini-${PHP_INI_TYPE_OPT}
		/usr/bin/perl -pi -e 's/post_max_size = 8M/post_max_size = 64M/' php.ini-${PHP_INI_TYPE_OPT}

		#short_open_tag: https://help.directadmin.com/item.php?id=438
		/usr/bin/perl -pi -e 's/^short_open_tag = Off/short_open_tag = On/' php.ini-${PHP_INI_TYPE_OPT}

		if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
			PHP_INI_VAR=PHP_INI_FPM${PHP4_SHORTRELEASE}
			cp -f php.ini-${PHP_INI_TYPE_OPT} ${!PHP_INI_VAR}
			writeLog "${!PHP_INI_VAR} installed"
		fi
		echo "Done for php4_release"
	fi

	cd ${WORKDIR}

}

####################################################

disable_asm_atomic() {
	# for this error:
	# /usr/include/mysql/my_global.h:361:24: error: asm/atomic.h: No such file or directory

	MY_GLOBAL=/usr/include/mysql/my_global.h
	if distro_is_debian; then
		MY_GLOBAL=/usr/local/mysql/include/my_global.h
	fi

	if [ "${PHP1_RELEASE_OPT}" = "5.3" ] || [ "${PHP2_RELEASE_OPT}" = "5.3" ] || [ "${PHP3_RELEASE_OPT}" = "5.3" ] || [ "${PHP4_RELEASE_OPT}" = "5.3" ]; then
		if [ -e ${MY_GLOBAL} ]; then
			echo "Disabling asm/atomic in ${MY_GLOBAL}"
			perl -pi -e 's#\#include <asm/atomic.h>#//\#include <asm/atomic.h>#' ${MY_GLOBAL}
		fi
	fi
}

####################################################

set_sendmail_link() {
	ln -sfn /usr/sbin/exim /usr/sbin/sendmail
}

####################################################

php_version_to_mode() {
	local php_version=$1

	# There are bugs when doExtensions_build gets passed short PHP version
	# instead of full version with dot. This bug propogates to this function
	# so cases with shortrelease is for compatibility reasons.
	case "${php_version}" in
		'') echo '';;
		no) echo '';;
		"${PHP1_RELEASE_OPT}") echo "${PHP1_MODE_OPT}";;
		"${PHP2_RELEASE_OPT}") echo "${PHP2_MODE_OPT}";;
		"${PHP3_RELEASE_OPT}") echo "${PHP3_MODE_OPT}";;
		"${PHP4_RELEASE_OPT}") echo "${PHP4_MODE_OPT}";;
		"${PHP1_SHORTRELEASE}") echo "${PHP1_MODE_OPT}";;
		"${PHP2_SHORTRELEASE}") echo "${PHP2_MODE_OPT}";;
		"${PHP3_SHORTRELEASE}") echo "${PHP3_MODE_OPT}";;
		"${PHP4_SHORTRELEASE}") echo "${PHP4_MODE_OPT}";;
		*)  echo '';;
	esac
}

doExtensions_build() {
	EXTENSION_INT_RELEASE=$1
	EXTENSION_INT_MODE=$(php_version_to_mode "$1")
	EXTENSION_NAME=$2
	local vv=${EXTENSION_INT_RELEASE//./}

	if [ -z "${EXTENSION_INT_RELEASE}" ] || [ "${EXTENSION_INT_RELEASE}" = "no" ]; then
		return
	fi

	if [ "${EXTENSION_NAME}" = "" ]; then
		EXTENSION_NAME="all"
	fi

	if [ "${EXTENSION_INT_MODE}" = "no" ]; then
		do_exit 1 "Cannot build PHP extensions for mode ${EXTENSION_INT_MODE}."
	else
		SUHOSIN_UPLOADSCAN_FILENAME=/usr/local/php${vv}/bin/php_uploadscan.sh
		if [ -d /usr/local/php${vv} ]; then
			mkdir -p /usr/local/php${vv}/lib/php.conf.d
		fi
		EXTENSION_INT_EXT_DIR=`/usr/local/php${vv}/bin/php-config --extension-dir`
		EXTENSION_INT_PHP_INI=/usr/local/php${vv}/lib/php.ini
		EXTENSION_INT_EXT_INI=/usr/local/php${vv}/lib/php.conf.d/10-directadmin.ini
	fi

	#Make extensions file empty
	echo -n '' > ${EXTENSION_INT_EXT_INI}

	#We do comment out ioncube/zend from the old php.ini file only, because old configs cannot exist
	if [ -e ${EXTENSION_INT_PHP_INI} ]; then
		if [ "${HTSCANNER_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=htscanner.so|;extension=htscanner.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${SUHOSIN_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=suhosin.so|;extension=suhosin.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_GMP_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=gmp.so|;extension=gmp.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_IGBINARY_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=igbinary.so|;extension=igbinary.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${IMAGICK_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=imagick.so|;extension=imagick.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_LDAP_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=ldap.so|;extension=ldap.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_PHALCON_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=phalcon.so|;extension=phalcon.so|' ${EXTENSION_INT_PHP_INI}
			perl -pi -e 's|^extension=psr.so|;extension=psr.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_READLINE_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=readline.so|;extension=readline.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_REDIS_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=redis.so|;extension=redis.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_SNUFFLEUPAGUS_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=snuffleupagus.so|;extension=snuffleupagus.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_BZ2_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=bz2.so|;extension=bz2.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_IMAP_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=imap.so|;extension=imap.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${PHP_XMLRPC_OPT}" = "yes" ]; then
			perl -pi -e 's|^extension=xmlrpc.so|;extension=xmlrpc.so|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${OPCACHE_OPT}" = "yes" ]; then
			perl -pi -e "s|^zend_extension=${EXTENSION_INT_EXT_DIR}/opcache.so|;zend_extension=${EXTENSION_INT_EXT_DIR}/opcache.so|" ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${IONCUBE_OPT}" = "yes" ]; then
			perl -pi -e 's|^zend_extension=/usr/local/lib/ioncube|;zend_extension=/usr/local/lib/ioncube|' ${EXTENSION_INT_PHP_INI}
		fi
		if [ "${ZEND_OPT}" = "yes" ]; then
			perl -pi -e 's|^zend_extension=/usr/local/lib/ZendGuardLoader.so|;zend_extension=/usr/local/lib/ZendGuardLoader.so|' ${EXTENSION_INT_PHP_INI}
			perl -pi -e 's|^zend_extension=/usr/local/lib/ZendOptimizer_|;zend_extension=/usr/local/lib/ZendOptimizer_|' ${EXTENSION_INT_PHP_INI}
		fi

		#Make extensions file empty
		echo -n '' > ${EXTENSION_INT_EXT_INI}

		if [ -e ${EXTENSION_INT_EXT_INI} ]; then
			echo "extension_dir=${EXTENSION_INT_EXT_DIR}" >> ${EXTENSION_INT_EXT_INI}
			if [ "${SUHOSIN_OPT}" = "yes" ] && [ "${EXTENSION_INT_RELEASE}" != "5.3" ] && [ "${EXTENSION_INT_RELEASE}" != "7.0" ] && [ "${EXTENSION_INT_RELEASE}" != "7.1" ] && [ "${EXTENSION_INT_RELEASE}" != "7.2" ] && [ "${EXTENSION_INT_RELEASE}" != "7.3" ] && [ "${EXTENSION_INT_RELEASE}" != "7.4" ] && [ "${EXTENSION_INT_RELEASE}" != "8.0" ] && [ "${EXTENSION_INT_RELEASE}" != "8.1" ] && [ "${EXTENSION_INT_RELEASE}" != "8.2" ]; then
				echo "extension=suhosin.so" >> ${EXTENSION_INT_EXT_INI}
				if [ "${SUHOSIN_PHP_UPLOADSCAN_OPT}" = "yes" ] && [ -e /usr/local/bin/clamdscan ]; then
					cp -f ${SUHOSIN_PHP_UPLOADSCAN_SCRIPT} ${SUHOSIN_UPLOADSCAN_FILENAME}
					chmod 755 ${SUHOSIN_UPLOADSCAN_FILENAME}
					echo "suhosin.upload.verification_script=\"${SUHOSIN_UPLOADSCAN_FILENAME}\"" >> ${EXTENSION_INT_EXT_INI}
				elif [ "${SUHOSIN_PHP_UPLOADSCAN_OPT}" = "yes" ] && [ ! -e /usr/local/bin/clamdscan ]; then
					if [ "${EXTENSION_NAME}" = "suhosin" ] || [ "${EXTENSION_NAME}" = "all" ]; then
						echo "Cannot enable suhosin upload verification script (suhosin_php_uploadscan option), because /usr/local/bin/clamdscan does not exist on the system."
					fi
				fi
				if [ -e ${WORKDIR}/${SUHOSIN_INI} ]; then
					cat ${WORKDIR}/${SUHOSIN_INI} >> ${EXTENSION_INT_EXT_INI}
					echo "" >> ${EXTENSION_INT_EXT_INI}
				fi
				if [ "${EXTENSION_NAME}" = "suhosin" ] || [ "${EXTENSION_NAME}" = "all" ]; then
					echo "suhosin ${SUHOSIN_VER} is now installed for PHP ${EXTENSION_INT_RELEASE}."
				fi
			fi

			if [ "${HTSCANNER_OPT}" = "yes" ] && [ "${EXTENSION_INT_MODE}" != "lsphp" ] && [ "${EXTENSION_INT_RELEASE}" != "8.0" ] && [ "${EXTENSION_INT_RELEASE}" != "8.1" ] && [ "${EXTENSION_INT_RELEASE}" != "8.2" ]; then
				echo "extension=htscanner.so" >> ${EXTENSION_INT_EXT_INI}
				if [ "${EXTENSION_NAME}" = "htscanner" ] || [ "${EXTENSION_NAME}" = "all" ]; then
					echo "htscanner ${HTSCANNER_VER} is now installed for PHP ${EXTENSION_INT_RELEASE}."
				fi
			fi

			if [ "${PHP_IGBINARY_OPT}" = "yes" ]; then
				if php_supports_igbinary_extension "${vv}"; then
					echo "extension=igbinary.so" >> ${EXTENSION_INT_EXT_INI}
				else
					echo "There is no igbinary available for PHP ${EXTENSION_INT_RELEASE}."
				fi
			fi

			if [ "${IONCUBE_OPT}" = "yes" ]; then
				if [ "${EXTENSION_INT_RELEASE}" != "8.0" ] && [ "${EXTENSION_INT_RELEASE}" != "8.2" ]; then
					echo "zend_extension=/usr/local/lib/ioncube/ioncube_loader_lin_${EXTENSION_INT_RELEASE}.so" >> ${EXTENSION_INT_EXT_INI}
					if [ "${EXTENSION_NAME}" = "ioncube" ] || [ "${EXTENSION_NAME}" = "all" ]; then
						echo "ionCube loader ${IONCUBE_VER} is now installed for PHP ${EXTENSION_INT_RELEASE}."
					fi
				else
					echo "There is no ionCube loader available for PHP ${EXTENSION_INT_RELEASE}."
				fi
			fi

			if [ "${PHP_PHALCON_OPT}" = "yes" ]; then
				if php_supports_phalcon5_extension "${vv}"; then
					echo "extension=phalcon.so" >> "${EXTENSION_INT_EXT_INI}"
				elif php_supports_phalcon4_extension "${vv}"; then
					echo "extension=psr.so" >> "${EXTENSION_INT_EXT_INI}"
					echo "extension=phalcon.so" >> "${EXTENSION_INT_EXT_INI}"
				else
					echo "There is no phalcon available for PHP ${EXTENSION_INT_RELEASE}."
				fi
			fi

			if [ "${PHP_SNUFFLEUPAGUS_OPT}" = "yes" ]; then
				if [ "${EXTENSION_INT_RELEASE}" != "5.3" ] && [ "${EXTENSION_INT_RELEASE}" != "5.4" ] && [ "${EXTENSION_INT_RELEASE}" != "5.5" ] && [ "${EXTENSION_INT_RELEASE}" != "5.6" ]; then
					echo "extension=snuffleupagus.so" >> ${EXTENSION_INT_EXT_INI}
					echo "sp.configuration_file=/usr/local/php${vv}/lib/php.conf.d/snuffleupagus.rules" >> ${EXTENSION_INT_EXT_INI}
					if [ ! -e /usr/local/php${vv}/lib/php.conf.d/snuffleupagus.rules ]; then
						touch /usr/local/php${vv}/lib/php.conf.d/snuffleupagus.rules
					fi
				else
					echo "There is no snuffleupagus available for PHP ${EXTENSION_INT_RELEASE}."
				fi
			fi

			if [ "${PHP_BZ2_OPT}" = "yes" ]; then
				echo "extension=bz2.so" >> ${EXTENSION_INT_EXT_INI}
			fi

			if [ "${PHP_GMP_OPT}" = "yes" ]; then
				echo "extension=gmp.so" >> ${EXTENSION_INT_EXT_INI}
			fi

			if [ "${PHP_READLINE_OPT}" = "yes" ]; then
				echo "extension=readline.so" >> ${EXTENSION_INT_EXT_INI}
			fi

			if [ "${PHP_REDIS_OPT}" = "yes" ]; then
				if [ "${EXTENSION_INT_RELEASE}" != "5.3" ] && [ "${EXTENSION_INT_RELEASE}" != "5.4" ] && [ "${EXTENSION_INT_RELEASE}" != "5.5" ] && [ "${EXTENSION_INT_RELEASE}" != "5.6" ]; then
					echo "extension=redis.so" >> ${EXTENSION_INT_EXT_INI}
				fi
			fi

			if [ "${IMAGICK_OPT}" = "yes" ]; then
				echo "extension=imagick.so" >> ${EXTENSION_INT_EXT_INI}
			fi

			if [ "${PHP_IMAP_OPT}" = "yes" ]; then
				echo "extension=imap.so" >> ${EXTENSION_INT_EXT_INI}
			fi

			if [ "${PHP_LDAP_OPT}" = "yes" ]; then
				echo "extension=ldap.so" >> ${EXTENSION_INT_EXT_INI}
			fi

			if [ "${PHP_XMLRPC_OPT}" = "yes" ]; then
				echo "extension=xmlrpc.so" >> ${EXTENSION_INT_EXT_INI}
			fi

			if [ "${ZEND_OPT}" = "yes" ]; then
				# Only supported by PHP5
				if echo "${EXTENSION_INT_RELEASE}" | grep -m1 -q '^5'; then
					echo "zend_extension=/usr/local/lib/ZendGuardLoader${EXTENSION_INT_RELEASE}.so" >> ${EXTENSION_INT_EXT_INI}
					if [ "${EXTENSION_NAME}" = "zend" ] || [ "${EXTENSION_NAME}" = "all" ]; then
						echo "Zend Guard loader is now installed for PHP ${EXTENSION_INT_RELEASE}."
					fi
				elif [ "${EXTENSION_NAME}" = "zend" ] || [ "${EXTENSION_NAME}" = "all" ]; then
					echo "There is no Zend Guard loader available for PHP ${EXTENSION_INT_RELEASE}."
				fi
			fi

			if [ "${OPCACHE_OPT}" = "yes" ]; then
				echo "zend_extension=${EXTENSION_INT_EXT_DIR}/opcache.so" >> ${EXTENSION_INT_EXT_INI}
				if [ -e ${WORKDIR}/${OPCACHE_INI} ]; then
					cat ${WORKDIR}/${OPCACHE_INI} >> ${EXTENSION_INT_EXT_INI}
					echo "" >> ${EXTENSION_INT_EXT_INI}

				fi
				if [ "${EXTENSION_INT_RELEASE}" = "5.4" ] || [ "${EXTENSION_INT_RELEASE}" = "5.4" ]; then
					SHOW_EXT_VERSION=" ${OPCACHE_VER}"
				else
					SHOW_EXT_VERSION=""
				fi
				if [ "${EXTENSION_NAME}" = "opcache" ] || [ "${EXTENSION_NAME}" = "all" ]; then
					echo "opCache${SHOW_EXT_VERSION} is now installed for PHP ${EXTENSION_INT_RELEASE}."
				fi
			fi
		fi
	fi
}

restart_php() {
	# All arguments are PHP versions to restart, example:
	#    restart_php 8.1 7.4 8.2 ...

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	local webserver=''
	local php_version
	for php_version in "$@"; do
		case "$(php_version_to_mode "${php_version}")" in
			fastcgi) webserver=yes;;
			lsphp)   webserver=yes;;
			php-fpm)
				echo "Restarting php-fpm${php_version//./}"
				control_service "php-fpm${php_version//./}" restart
				;;
		esac
	done

	if [ -n "${webserver}" ]; then
		restart_webserver
	fi
}

restart_webserver() {
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "Restarting nginx service"
		control_service nginx stop >/dev/null 2>&1
		control_service nginx start
	fi
	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "Restarting apache service"
		control_service httpd restart
	fi
	if [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		echo "Restarting litespeed service"
		control_service litespeed reload
	fi
}

doExtensions() {
	local skip_restart=$1  # if 1 restart will NOT be called
	local name=${2:-all}   # name of PHP extension

	local php_version
	for php_version in "${!options_conf_php[@]}"; do
		doExtensions_build "${php_version}" "${name}"
	done

	if [ "${skip_restart}" != "1" ]; then
		restart_php "${!options_conf_php[@]}"
	fi
}

####################################################

doPHPHtscanner() {
	ensureBuildPackages
	install_rpms autoconf
	install_debs autoconf
	HTSCANNER_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
	cd ${WORKDIR}
	if [ "${HTSCANNER_OPT}" = "no" ]; then
		do_exit 1 "Cannot build htscanner, because you do not have it set in php_extensions.conf file."
	fi
	if [ -z $1 ] || [ "$1" = "no" ]; then
		return
	fi
	if [ -z $2 ]; then
		SKIP_RESTART=0
	else
		SKIP_RESTART=$2
	fi
	safeDownloadWithMove "${WORKDIR}/htscanner-${HTSCANNER_VER}.tgz" "${HTSCANNER_DOWNLOADURL}"

	FILE=${WORKDIR}/htscanner-${HTSCANNER_VER}.tgz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE}
	cd htscanner-${HTSCANNER_VER}

	echo "Installing htscanner2-${HTSCANNER_VER} PHP extension for PHP $1..."

	/usr/local/php${HTSCANNER_INT_SHORTRELEASE}/bin/phpize
	./configure --enable-htscanner --with-php-config=/usr/local/php${HTSCANNER_INT_SHORTRELEASE}/bin/php-config
	echo "Trying to make htscanner2-${HTSCANNER_VER} PHP extension..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing htscanner2-${HTSCANNER_VER} PHP extension..."
	make install

	make clean
	doExtensions_build $1 htscanner

	echo "htscanner2 PHP extension has been installed successfully."

	cd ${WORKDIR}
}

####################################################

doZend_build() {
	cd ${WORKDIR}

	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		do_exit 1 "Missing parameters for doZend call. Exiting..."
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi

	ZEND_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
	if [ "$1" = "5.3" ]; then
		ZEND_INT_FILENAME=${ZENDFILE_GUARD53}
		ZEND_INT_ZENDNAME=${ZENDNAME_PHP53}
		ZEND_INT_LONGVER="$1"
		ZEND_TARBALL_FORMAT=1
	elif [ "$1" = "5.4" ]; then
		ZEND_INT_FILENAME=${ZENDFILE_GUARD54}
		ZEND_INT_ZENDNAME=${ZENDNAME_PHP54}
		ZEND_INT_LONGVER="$1"
		ZEND_TARBALL_FORMAT=1
	elif [ "$1" = "5.5" ]; then
		ZEND_INT_FILENAME=${ZENDFILE_GUARD55}
		ZEND_INT_ZENDNAME=${ZENDNAME_PHP55}
		ZEND_INT_LONGVER="$1"
		ZEND_TARBALL_FORMAT=0
	elif [ "$1" = "5.6" ]; then
		ZEND_INT_FILENAME=${ZENDFILE_GUARD56}
		ZEND_INT_ZENDNAME=${ZENDNAME_PHP56}
		ZEND_INT_LONGVER="$1"
		ZEND_TARBALL_FORMAT=0
	elif [ ! -z "$1" ]; then
		echo "Zend guard loader not supported for PHP version ($1) set in configuration file"
		return
	fi
	safeDownloadWithMove "${WORKDIR}/${ZEND_INT_FILENAME}" "${WEBPATH}/${ZEND_INT_FILENAME}"

	if [ "${ZEND_OPT}" != "yes" ]; then
		do_exit 1 "You cannot install Zend Guard Loader, because you do not have it set in the options.conf file."
	fi

	cd ${WORKDIR}
	tar xzf ${ZEND_INT_FILENAME} --no-same-owner
	if [ ${ZEND_TARBALL_FORMAT} -eq 1 ]; then
		cp -fp ${ZEND_INT_ZENDNAME}/php-${ZEND_INT_LONGVER}.x/ZendGuardLoader.so /usr/local/lib/ZendGuardLoader${ZEND_INT_LONGVER}.so
	else
		OPCACHE_EXTENSION_DIR_SHORT_RELEASE=`echo ${ZEND_INT_LONGVER} | tr -d '.'`
		OPCACHE_EXT_DIR=`/usr/local/php${OPCACHE_EXTENSION_DIR_SHORT_RELEASE}/bin/php-config --extension-dir`
		cp -fp ${ZEND_INT_ZENDNAME}/ZendGuardLoader.so /usr/local/lib/ZendGuardLoader${ZEND_INT_LONGVER}.so
	fi
	chmod 755 /usr/local/lib/ZendGuardLoader${ZEND_INT_LONGVER}.so
	chown root:root /usr/local/lib/ZendGuardLoader${ZEND_INT_LONGVER}.so
	doExtensions_build ${ZEND_INT_LONGVER} zend
}

####################################################

doZend() {
	cd ${WORKDIR}

	doZend_build ${PHP1_RELEASE_OPT} ${PHP1_MODE_OPT} 1

	if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		doZend_build ${PHP2_RELEASE_OPT} ${PHP2_MODE_OPT} 1
	fi
	if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		doZend_build ${PHP3_RELEASE_OPT} ${PHP3_MODE_OPT} 1
	fi
	if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		doZend_build ${PHP4_RELEASE_OPT} ${PHP4_MODE_OPT} 1
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	SKIP_WEBSERVER_RESTART=0

	if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
		if [ "${PHP2_MODE_OPT}" = "php-fpm" ] || [ "${PHP2_RELEASE_OPT}" = "no" ]; then
			SKIP_WEBSERVER_RESTART=1
		fi
		if [ "${PHP3_MODE_OPT}" = "php-fpm" ] || [ "${PHP3_RELEASE_OPT}" = "no" ]; then
			SKIP_WEBSERVER_RESTART=1
		fi
		if [ "${PHP4_MODE_OPT}" = "php-fpm" ] || [ "${PHP4_RELEASE_OPT}" = "no" ]; then
			SKIP_WEBSERVER_RESTART=1
		fi
	fi

	if [ "${SKIP_WEBSERVER_RESTART}" = "0" ]; then
		if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			control_service nginx stop >/dev/null 2>&1
			control_service nginx start
		fi
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			control_service httpd restart
		fi
		if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
			control_service litespeed reload
		fi
	fi

	if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
		echo "Restarting php-fpm${PHP1_SHORTRELEASE}."
		control_service php-fpm${PHP1_SHORTRELEASE} restart
	fi
	if [ "${PHP2_MODE_OPT}" = "php-fpm" ] && [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		echo "Restarting php-fpm${PHP2_SHORTRELEASE}."
		control_service php-fpm${PHP2_SHORTRELEASE} restart
	fi
	if [ "${PHP3_MODE_OPT}" = "php-fpm" ] && [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		echo "Restarting php-fpm${PHP3_SHORTRELEASE}."
		control_service php-fpm${PHP3_SHORTRELEASE} restart
	fi
	if [ "${PHP4_MODE_OPT}" = "php-fpm" ] && [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		echo "Restarting php-fpm${PHP4_SHORTRELEASE}."
		control_service php-fpm${PHP4_SHORTRELEASE} restart
	fi
	
	writeLog "zend installed"
}

####################################################

doIoncube() {
	cd ${WORKDIR}

	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		IONCUBE_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi

	rm -f ${IONCUBEFILE}
	safeDownloadWithMove "${WORKDIR}/${IONCUBEFILE}" "${IONCUBE_DOWNLOADURL}"
	if [ "${IONCUBE_OPT}" != "yes" ]; then
		do_exit 1 "You cannot install ionCube loader, because you do not have it set in php_extensions.conf file."
	fi

	tar xzf ${IONCUBEFILE} --no-same-owner

	if [ -d ioncube ]; then
		chown -R root:root ioncube
	fi

	if [ -d /usr/local/lib/ioncube ]; then
		rm -rf /usr/local/lib/ioncube
	fi

	mv -f ioncube /usr/local/lib/

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} ioncube
	else
		doExtensions_build ${1} ioncube
	fi
	
	writeLog "Ioncube ${IONCUBE_VER} installed"
}

####################################################

installSuhosin() {
	if [ -z $1 ] || [ "$1" = "no" ]; then
		return
	fi
	install_rpms autoconf
	install_debs autoconf
	echo "Installing suhosin-${SUHOSIN_VER} PHP extension for PHP $1..."

	/usr/local/php$1/bin/phpize
	./configure --with-php-config=/usr/local/php$1/bin/php-config
	echo "Trying to make suhosin-${SUHOSIN_VER} PHP extension..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	make install

	make clean
}

doSuhosin() {
	cd ${WORKDIR}
	if [ "${SUHOSIN_OPT}" = "no" ]; then
		do_exit 1 "Cannot build suhosin, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		SUHOSIN_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi

	safeDownloadWithMove "${WORKDIR}/suhosin-${SUHOSIN_VER}.tar.gz" "${SUHOSIN_DOWNLOADURL}"

	FILE=${WORKDIR}/suhosin-${SUHOSIN_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE}
	cd suhosin-${SUHOSIN_VER}

	if [ "${FOR_ALL}" = "no" ]; then
		if [ "${SUHOSIN_INT_SHORTRELEASE}" != "53" ] && [ "${SUHOSIN_INT_SHORTRELEASE}" != "70" ] && [ "${SUHOSIN_INT_SHORTRELEASE}" != "71" ] && [ "${SUHOSIN_INT_SHORTRELEASE}" != "72" ] && [ "${SUHOSIN_INT_SHORTRELEASE}" != "73" ] && [ "${SUHOSIN_INT_SHORTRELEASE}" != "74" ]; then
			installSuhosin ${SUHOSIN_INT_SHORTRELEASE} $2
		fi
	else
		if [ "${PHP1_SHORTRELEASE}" != "53" ] && [ "${PHP1_SHORTRELEASE}" != "70" ] && [ "${PHP1_SHORTRELEASE}" != "71" ] && [ "${PHP1_SHORTRELEASE}" != "72" ] && [ "${PHP1_SHORTRELEASE}" != "73" ] && [ "${PHP1_SHORTRELEASE}" != "74" ]; then
			installSuhosin ${PHP1_SHORTRELEASE} ${PHP1_MODE_OPT}
		fi
		if [ "${PHP2_RELEASE_OPT}" != "no" ] && [ "${PHP2_SHORTRELEASE}" != "53" ] && [ "${PHP2_SHORTRELEASE}" != "70" ] && [ "${PHP2_SHORTRELEASE}" != "71" ] && [ "${PHP2_SHORTRELEASE}" != "72" ] && [ "${PHP2_SHORTRELEASE}" != "73" ] && [ "${PHP2_SHORTRELEASE}" != "74" ]; then
			installSuhosin ${PHP2_SHORTRELEASE} ${PHP2_MODE_OPT}
		fi
		if [ "${PHP3_RELEASE_OPT}" != "no" ] && [ "${PHP3_SHORTRELEASE}" != "53" ] && [ "${PHP3_SHORTRELEASE}" != "70" ] && [ "${PHP3_SHORTRELEASE}" != "71" ] && [ "${PHP3_SHORTRELEASE}" != "72" ] && [ "${PHP3_SHORTRELEASE}" != "73" ] && [ "${PHP3_SHORTRELEASE}" != "74" ]; then
			installSuhosin ${PHP3_SHORTRELEASE} ${PHP3_MODE_OPT}
		fi
		if [ "${PHP4_RELEASE_OPT}" != "no" ] && [ "${PHP4_SHORTRELEASE}" != "53" ] && [ "${PHP4_SHORTRELEASE}" != "70" ] && [ "${PHP4_SHORTRELEASE}" != "71" ] && [ "${PHP4_SHORTRELEASE}" != "72" ] && [ "${PHP4_SHORTRELEASE}" != "73" ] && [ "${PHP4_SHORTRELEASE}" != "74" ]; then
			installSuhosin ${PHP4_SHORTRELEASE} ${PHP4_MODE_OPT}
		fi
	fi

	if [ "${SUHOSIN_PHP_UPLOADSCAN_OPT}" = "yes" ] && [ ! -e /usr/bin/clamdscan ]; then
		if [ "${CLAMAV_OPT}" = "no" ]; then
			do_exit 1 "Cannot install suhosin with PHP upload scan using ClamAV, because /usr/bin/clamdscan does not exist on the system and clamav=no is set in the options.conf file."
		fi
		doclamav
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} suhosin
	else
		doExtensions_build ${1} suhosin
	fi
	echo "suhosin ${SUHOSIN_VER} PHP extension has been installed successfully."
	writeLog "suhosin ${SUHOSIN_VER} installed"

	cd ${WORKDIR}
}

installOpcache() {
	if [ -z $1 ] || [ "$1" = "no" ]; then
		return
	fi
	install_rpms autoconf
	install_debs autoconf
	echo "Installing zendopcache-${OPCACHE_VER} PHP extension for PHP $1..."

	if [ "$1" = "53" ] || [ "$1" = "54" ]; then
		/usr/local/php$1/bin/phpize
		./configure --with-php-config=/usr/local/php$1/bin/php-config
		echo "Trying to make zendopcache-${OPCACHE_VER} PHP extension..."
		if ! make; then
			do_exit 1 "*** The make has failed. Exiting..."
		fi
		make install
		make clean
		
		echo "opCache ${OPCACHE_VER} PHP extension has been installed successfully for PHP$1."
		writeLog "opCache ${OPCACHE_VER} installed for PHP$1"
	fi
}

doOpcache() {
	cd ${WORKDIR}
	if [ "${OPCACHE_OPT}" = "no" ]; then
		do_exit 1 "Cannot build opCache, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		OPCACHE_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
	fi

	SKIP_RESTART=1
	if [ "$1" != "1" ]; then
		SKIP_RESTART=0
	fi

	if [ "${PHP1_RELEASE_OPT}" = "5.3" ] || [ "${PHP1_RELEASE_OPT}" = "5.4" ] || [ "${PHP2_RELEASE_OPT}" = "5.3" ] || [ "${PHP2_RELEASE_OPT}" = "5.4" ] || [ "${PHP3_RELEASE_OPT}" = "5.3" ] || [ "${PHP3_RELEASE_OPT}" = "5.4" ] || [ "${PHP4_RELEASE_OPT}" = "5.3" ] || [ "${PHP4_RELEASE_OPT}" = "5.4" ]; then
		safeDownloadWithMove "${WORKDIR}/zendopcache-${OPCACHE_VER}.tgz" "${OPCACHE_DOWNLOADURL}"

		FILE=${WORKDIR}/zendopcache-${OPCACHE_VER}.tgz
		checkFile ${FILE}
		echo "Extracting ${FILE}..."

		tar xzf ${FILE}
		cd zendopcache-${OPCACHE_VER}

		if [ "${FOR_ALL}" = "no" ]; then
			installOpcache ${OPCACHE_INT_SHORTRELEASE} $2
		else
			installOpcache ${PHP1_SHORTRELEASE} ${PHP1_MODE_OPT}
			if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
				installOpcache ${PHP2_SHORTRELEASE} ${PHP2_MODE_OPT}
			fi
			if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
				installOpcache ${PHP3_SHORTRELEASE} ${PHP3_MODE_OPT}
			fi
			if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
				installOpcache ${PHP4_SHORTRELEASE} ${PHP4_MODE_OPT}
			fi
		fi
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} opcache
	else
		doExtensions_build ${1} opcache
	fi

	cd ${WORKDIR}
}

####################################################

doModLsapi() {
	if [ "${CLOUDLINUX_OPT}" = "yes" ] && [ "${PHP1_MODE_OPT}" = "lsphp" ]; then
		if is_cloudlinux_solo; then
			echo "lsphp PHP1_MODE is not supported on CloudLinux Solo Edition" 1>&2
			return 1
		fi
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			install_rpms make gcc-c++ cmake psmisc

			if [ -e "/usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp" ]; then
				cp -pf "/usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp" /usr/local/bin/lsphp
			elif [ -e "/usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp${PHP1_SHORTRELEASE}" ]; then
				cp -pf "/usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp${PHP1_SHORTRELEASE}" /usr/local/bin/lsphp
			fi

			if ! grep -m1 -q 'exclude=.*liblsapi' /etc/yum.conf; then
				perl -pi -e 's|exclude\=|exclude=liblsapi* |g' /etc/yum.conf
			fi
			if has_rpms_installed mod_lsapi; then
				rpm -e mod_lsapi >/dev/null 2>&1
			fi

			local cached_file=${CB_CACHE_DIR}/mod_lsapi-${MOD_LSAPI_VER}.tar.gz
			download_with_cache "${cached_file}" "${WEBPATH_CL}/mod_lsapi-${MOD_LSAPI_VER}.tar.gz" || return 1
			(
				local tmp_dir
				if ! tmp_dir=$(mktemp --directory --tmpdir="${CB_TMP_DIR}" --suffix=".mod_lsapi"); then
					echo "${FUNCNAME[0]}: failed to create temp dir for extracting '${cached_file}'" 1>&2
					return 1
				fi
				trap 'rm -rf "${tmp_dir}"' EXIT

				if ! tar xzf "${cached_file}" --strip-components=1 -C "${tmp_dir}"; then
					echo "${FUNCNAME[0]}: failed to extract '${cached_file}' into '${tmp_dir}'" 1>&2
					return 1
				fi

				set -e
				cd "${tmp_dir}"
				sh ./install/da_cb_install stable "${MOD_LSAPI_VER}"
				if [ -e /usr/include/criu/criu.h ];then
					cmake -DWITH_CRIU:BOOLEAN=TRUE .
				else
					cmake .
				fi
				make install
				if [ ! -e /etc/httpd/conf/extra/mod_lsapi.conf ]; then
					sed -i 's|^#\(AddType application/x-httpd-lsphp\)|\1|' conf/mod_lsapi.conf
					sed -i 's|/etc/httpd/modules/mod_lsapi\.so|/usr/lib/apache/mod_lsapi.so|' conf/mod_lsapi.conf
					install_file conf/mod_lsapi.conf /etc/httpd/conf/extra/mod_lsapi.conf 644 root:root
				fi
			)
			# Bash ignores '-e' mode in "(set -e; ...) || ...", we must check $?
			# shellcheck disable=SC2181
			if [ $? -ne 0 ]; then
				echo "failed to build mod_lsapi ${MOD_LSAPI_VER}" 1>&2
				return 1
			fi

			#Inserting mod_lsapi to apache config
			if ! grep -q -F "/etc/httpd/conf/extra/mod_lsapi.conf" /etc/httpd/conf/extra/httpd-includes.conf; then
				echo "Adding mod_lsapi to apache configuration (extra/httpd-includes.conf)."
				{
					echo ""
					echo "# For mod_lsphp settings"
					echo "Include /etc/httpd/conf/extra/mod_lsapi.conf"
				} >> /etc/httpd/conf/extra/httpd-includes.conf
			else
				perl -pi -e 's|^#Include /etc/httpd/conf/extra/mod_lsapi.conf|Include /etc/httpd/conf/extra/mod_lsapi.conf|' /etc/httpd/conf/extra/httpd-includes.conf
			fi
			if [ "$1" != "0" ]; then
				control_service httpd restart
			fi
		fi
	else
		if [ -e /etc/httpd/conf/extra/httpd-includes.conf ]; then
			#Removing mod_lsapi from apache config
			if grep -m1 -q -e '^Include /etc/httpd/conf/extra/mod_lsapi.conf' /etc/httpd/conf/extra/httpd-includes.conf; then
				echo "Removing mod_lsapi from apache configuration (extra/httpd-includes.conf)."
				perl -pi -e 's|^Include /etc/httpd/conf/extra/mod_lsapi.conf|#Include /etc/httpd/conf/extra/mod_lsapi.conf|' /etc/httpd/conf/extra/httpd-includes.conf
				if [ "$1" != "0" ]; then
					if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
						control_service httpd restart
					fi
				fi
			fi
		fi
	fi
}

####################################################

doModHostingLimits() {
	ensureBuildPackages
	if [ "${CLOUDLINUX_OPT}" = "yes" ] && ! is_cloudlinux_solo; then
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			install_rpms liblve-devel cmake
			cd ${WORKDIR}
			safeDownloadWithMove "${WORKDIR}/mod_hostinglimits-${MOD_HOSTINGLIMITS_VER}.tar.gz" "${WEBPATH_CL}/mod_hostinglimits-${MOD_HOSTINGLIMITS_VER}.tar.gz"
			CL_MODDIR="mod_hostinglimits-${MOD_HOSTINGLIMITS_VER}"
			tar xzf mod_hostinglimits-${MOD_HOSTINGLIMITS_VER}.tar.gz
			cd ${CL_MODDIR}
			if [ -e ./install/da_cb_install ]; then
				sh ./install/da_cb_install ${MOD_HOSTINGLIMITS_VER}
			fi
			cmake CMakeLists.txt
			make install
			if [ ! -s /etc/httpd/conf/extra/modhostinglimits.conf ]; then
				safeDownloadWithMove "/etc/httpd/conf/extra/modhostinglimits.conf" "https://repo.cloudlinux.com/cloudlinux/confs/modhostinglimits.conf"
				perl -pi -e 's#/etc/httpd/modules/mod_hostinglimits.so#/usr/lib/apache/mod_hostinglimits.so#' /etc/httpd/conf/extra/modhostinglimits.conf
			fi
			#Inserting mod_hostinglimits to apache config
			if ! grep -m1 -q -e "modhostinglimits.conf" /etc/httpd/conf/extra/httpd-includes.conf; then
				echo "Adding mod_hostinglimits to apache configuration (extra/httpd-includes.conf)."
				if [ ! -z "`tail -c 1 /etc/httpd/conf/extra/httpd-includes.conf`" ]; then
					echo "" >> /etc/httpd/conf/extra/httpd-includes.conf
				fi
				echo "#For LVE settings" >> /etc/httpd/conf/extra/httpd-includes.conf
				echo "Include /etc/httpd/conf/extra/modhostinglimits.conf" >> /etc/httpd/conf/extra/httpd-includes.conf
			else
				perl -pi -e 's|^#Include /etc/httpd/conf/extra/modhostinglimits.conf|Include /etc/httpd/conf/extra/modhostinglimits.conf|' /etc/httpd/conf/extra/httpd-includes.conf
			fi
			cd ${WORKDIR}
			rm -rf ${CL_MODDIR}
			if [ "$1" != "0" ]; then
				control_service httpd restart
			fi
		fi
	else
		#Removing mod_hostinglimits from apache config
		if grep -m1 -q -e '^Include /etc/httpd/conf/extra/modhostinglimits.conf' /etc/httpd/conf/extra/httpd-includes.conf; then
			echo "Removing mod_hostinglimits from apache configuration (extra/httpd-includes.conf)."
			perl -pi -e 's|^Include /etc/httpd/conf/extra/modhostinglimits.conf|#Include /etc/httpd/conf/extra/modhostinglimits.conf|' /etc/httpd/conf/extra/httpd-includes.conf
			if [ "$1" != "0" ]; then
				if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
					control_service httpd restart
				fi
			fi
		fi
	fi
}

####################################################

doModProctitle() {
	ensureBuildPackages
	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			install_rpms cmake
			cd ${WORKDIR}
			safeDownloadWithMove "${WORKDIR}/mod_proctitle-${MOD_PROCTITLE_VER}.tar.gz" "${WEBPATH_CL}/mod_proctitle-${MOD_PROCTITLE_VER}.tar.gz"
			CL_MODDIR="mod_proctitle-${MOD_PROCTITLE_VER}"
			tar xzf mod_proctitle-${MOD_PROCTITLE_VER}.tar.gz
			cd ${CL_MODDIR}
			cmake CMakeLists.txt
			make install
			if [ ! -s /etc/httpd/conf/extra/modproctitle.conf ]; then
				cp -f conf/modproctitle.conf /etc/httpd/conf/extra/modproctitle.conf
			fi
			#Inserting mod_proctitle to apache config
			if ! grep -m1 -q -e "modproctitle.conf" /etc/httpd/conf/extra/httpd-includes.conf; then
				echo "Adding mod_proctitle to apache configuration (extra/httpd-includes.conf)."
				if [ ! -z "`tail -c 1 /etc/httpd/conf/extra/httpd-includes.conf`" ]; then
					echo "" >> /etc/httpd/conf/extra/httpd-includes.conf
				fi
				echo "#For mod_proctitle settings" >> /etc/httpd/conf/extra/httpd-includes.conf
				echo "Include /etc/httpd/conf/extra/modproctitle.conf" >> /etc/httpd/conf/extra/httpd-includes.conf
			else
				perl -pi -e 's|^#Include /etc/httpd/conf/extra/modproctitle.conf|Include /etc/httpd/conf/extra/modproctitle.conf|' /etc/httpd/conf/extra/httpd-includes.conf
			fi
			cd ${WORKDIR}
			rm -rf ${CL_MODDIR}
			if [ "$1" != "0" ]; then
				control_service httpd restart
			fi
		fi
	else
		#Removing mod_proctitle from apache config
		if grep -m1 -q -e '^Include /etc/httpd/conf/extra/modproctitle.conf' /etc/httpd/conf/extra/httpd-includes.conf; then
			echo "Removing mod_proctitle from apache configuration (extra/httpd-includes.conf)."
			perl -pi -e 's|^Include /etc/httpd/conf/extra/modproctitle.conf|#Include /etc/httpd/conf/extra/modproctitle.conf|' /etc/httpd/conf/extra/httpd-includes.conf
			if [ "$1" != "0" ]; then
				if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
					control_service httpd restart
				fi
			fi
		fi
	fi
}

####################################################

doSetupFcgidSh() {
	if [ ! -d /usr/local/safe-bin ]; then
		mkdir -p /usr/local/safe-bin
		chmod 511 /usr/local/safe-bin
		chown apache:apache /usr/local/safe-bin
	fi
	FCGID_SCRIPT_NAME="fcgid"
	cp -f ${WORKDIR}/configure/fastcgi/${FCGID_SCRIPT_NAME}.sh /usr/local/safe-bin/fcgid${1}.sh
	if [ -e ${WORKDIR}/custom/fastcgi/fcgid${1}.sh ]; then
		cp -f ${WORKDIR}/custom/fastcgi/fcgid${1}.sh /usr/local/safe-bin/fcgid${1}.sh
	elif [ -e ${WORKDIR}/custom/fastcgi/${FCGID_SCRIPT_NAME}.sh ]; then
		cp -f ${WORKDIR}/custom/fastcgi/${FCGID_SCRIPT_NAME}.sh /usr/local/safe-bin/fcgid${1}.sh
	fi
	chown apache:apache /usr/local/safe-bin/fcgid${1}.sh
	chmod 555 /usr/local/safe-bin/fcgid${1}.sh
}

doPhp_build() {
	#We want pkg-config to report
	export PKG_CONFIG_PATH=/usr/local/icu/lib/pkgconfig:/usr/local/lib64/pkgconfig:/usr/local/lib/pkgconfig:/usr/lib/x86_64-linux-gnu/pkgconfig
	ensureBuildPackages
	install_debs pkg-config libssl-dev libsystemd-dev libkrb5-dev libcurl4-openssl-dev libpng-dev libfreetype6-dev libwebp-dev libjpeg-dev libxslt-dev libsodium-dev libicu-dev libsqlite3-dev libonig-dev
	install_rpms pkgconfig  openssl-devel systemd-devel krb5-devel libcurl-devel libpng-devel freetype-devel libwebp-devel libjpeg-devel libxslt-devel libsodium-devel libicu-devel sqlite-devel oniguruma-devel

	#$1 is PHP release
	#$2 is PHP mode
	INT_RELEASE=$1
	INT_MODE=$2
	SHORT_RELEASE=`echo ${INT_RELEASE} | tr -d '.'`
	PHP_VERSION_EVAL_VAR=PHP${SHORT_RELEASE}_VER
	PHP_DOWNLOADURL_EVAL_VAR=PHP${SHORT_RELEASE}_DOWNLOADURL
	PHP_VER=${!PHP_VERSION_EVAL_VAR}
	PHP_DOWNLOADURL=${!PHP_DOWNLOADURL_EVAL_VAR}

	if [ -d /usr/local/lib/php.conf.d ] && [ ! -d /usr/local/php${SHORT_RELEASE}/lib/php.conf.d ] && [ ! -L /usr/local/lib/php.conf.d ]; then
		mkdir -p /usr/local/php${SHORT_RELEASE}/lib
		mv -v /usr/local/lib/php.conf.d /usr/local/php${SHORT_RELEASE}/lib/php.conf.d
		ln -sf /usr/local/php${SHORT_RELEASE}/lib/php.conf.d /usr/local/lib/php.conf.d
	fi

	if [ -d /usr/local/lib/php ] && [ ! -d /usr/local/php${SHORT_RELEASE}/lib/php ] && [ ! -L /usr/local/lib/php ]; then
		mkdir -p /usr/local/php${SHORT_RELEASE}/lib
		mv -v /usr/local/lib/php /usr/local/php${SHORT_RELEASE}/lib/php
		ln -sf /usr/local/php${SHORT_RELEASE}/lib/php /usr/local/lib/php
	fi

	if [ -s /usr/local/lib/php.ini ] && [ ! -s /usr/local/php${SHORT_RELEASE}/lib/php.ini ] && [ ! -L /usr/local/lib/php.ini ]; then
		mkdir -p /usr/local/php${SHORT_RELEASE}/lib
		mv -v /usr/local/lib/php.ini /usr/local/php${SHORT_RELEASE}/lib/php.ini
		ln -sf /usr/local/php${SHORT_RELEASE}/lib/php.ini /usr/local/lib/php.ini
	fi

	INT_MAIN_VERSION=false
	if [ "${PHP1_RELEASE_OPT}" = "${INT_RELEASE}" ] && [ "${PHP1_MODE_OPT}" = "${INT_MODE}" ]; then
		INT_MAIN_VERSION=true
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ ! -d /etc/httpd/conf/extra ]; then
			doApache2
		fi
	fi
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ ! -d ${NGINXCONF} ]; then
			doNginx
		fi
	fi

	#needed for PHP <7.4
	if distro_is_debian && ! debian_version_is 9 && [ ! -e /usr/local/include/freetype2/ft2build.h ] && [ ! -s /usr/bin/freetype-config ]; then
		safeDownloadWithMove "/usr/bin/freetype-config" "${WEBPATH}/freetype-config"
		chmod +x /usr/bin/freetype-config
	fi

	if distro_is_debian && ! debian_version_is 9 && [ ! -d /usr/local/icu ]; then
		safeDownloadWithMove "/usr/bin/icu-config" "${WEBPATH}/icu-config"
		chmod +x /usr/bin/icu-config
	fi
	if [ "${INT_RELEASE}" = "5.3" ] || [ "${INT_RELEASE}" = "5.4" ] || [ "${INT_RELEASE}" = "5.5" ] || [ "${INT_RELEASE}" = "5.6" ] || [ "${INT_RELEASE}" = "7.0" ] || [ "${INT_RELEASE}" = "7.1" ]; then
		if [ ! -e /usr/include/mcrypt.h ] && [ ! -e /usr/local/include/mcrypt.h ]; then
			install_debs libmcrypt-dev
			install_rpms libmcrypt-devel
		fi
	fi
	if [ "${INT_RELEASE}" != "5.3" ] && [ "${INT_RELEASE}" != "5.4" ] && [ "${INT_RELEASE}" != "5.5" ] && [ "${INT_RELEASE}" != "5.6" ] && [ "${INT_RELEASE}" != "7.0" ] && [ "${INT_RELEASE}" != "7.1" ] && [ "${INT_RELEASE}" != "7.2" ] && [ "${INT_RELEASE}" != "7.3" ]; then
		if [ ! -e /usr/lib/libzip.so ] && [ ! -e /usr/lib64/libzip.so ] && [ ! -e /usr/lib/x86_64-linux-gnu/libzip.so ] && [ ! -e /usr/lib/aarch64-linux-gnu/libzip.so ] && [ ! -e /usr/local/lib/libzip.so ] && [ ! -e /usr/local/lib64/libzip.so ]; then
			if rhel_version_is 7; then
				rpm -ihf "${WEBPATH}/centos7_deps/libzip-0.11.2-6.el7.psychotic.x86_64.rpm"
				rpm -ihf "${WEBPATH}/centos7_deps/libzip-devel-0.11.2-6.el7.psychotic.x86_64.rpm"
			else
				install_rpms libzip-devel
			fi
			install_debs libzip-dev
		fi
	fi

	if ${INT_MAIN_VERSION}; then
		doRewriteCLPhpHandler
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ] && [ "${MODSECURITY_OPT}" = "yes" ] && [ ! -e /usr/lib/apache/mod_security2.so ]; then
			doModSecurity
		fi
		
		if [ "${HAVE_FCGID}" = "yes" ]; then
			doModFCGID
		fi

		if [ "${HAVE_FCGID}" = "yes" ] || [ "${HAVE_FPM_CGI}" = "yes" ]; then
			if [ "${HTSCANNER_OPT}" = "yes" ] && [ ! -e /usr/lib/apache/mod_htscanner2.so ]; then
				doModHtscanner
			fi
		fi
	fi

	setupLogrotate php-fpm

	#just double check the location of libmysqlclient.so
	if [ -e /usr/lib64 ]; then
		if [ ! -e /usr/lib64/mysql/libmysqlclient.so ] && [ -e /usr/lib64/libmysqlclient.so ]; then
			ln -s ../libmysqlclient.so /usr/lib64/mysql/libmysqlclient.so
		fi
	fi

	if [ -e /usr/lib/libmysqlclient.so ] && [ ! -e /usr/lib/mysql/libmysqlclient.so ] && [ -d /usr/lib/mysql ]; then
		ln -s /usr/lib/libmysqlclient.so /usr/lib/mysql/libmysqlclient.so
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		doApacheCheck
	fi

	cd ${WORKDIR}
	ldconfig

	INT_EXT_DIR="no"
	if [ -e /usr/local/php${SHORT_RELEASE}/bin/php-config  ]; then
		INT_EXT_DIR=`/usr/local/php${SHORT_RELEASE}/bin/php-config --extension-dir`
	fi

	safeDownloadWithMove "${WORKDIR}/php-${PHP_VER}.tar.gz" "${PHP_DOWNLOADURL}"
	
	cd ${WORKDIR}
	FILE=${WORKDIR}/php-${PHP_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ..."
	tar xzf ${FILE} --no-same-owner
	echo "Done."

	disable_asm_atomic


	if [ "${INT_RELEASE}" = "5.3" ] || [ "${INT_RELEASE}" = "5.4" ]; then
		if [ -e /lib/x86_64-linux-gnu/libsystemd-daemon.so.0 ] && [ ! -e /lib/x86_64-linux-gnu/libsystemd-daemon.so ]; then
			ln -s /lib/x86_64-linux-gnu/libsystemd-daemon.so.0 /lib/x86_64-linux-gnu/libsystemd-daemon.so
			ldconfig
		fi
	fi

	OV=`openssl_version | cut -d. -f1,2`
	OPENSSL_11_OR_HIGHER=false
	if [ "${OV}" != "" ] && [ "`version_cmp ${OV} 1.1 'php 5.x vs openssl 1.1.0 ver check'`" -ge 0 ]; then
		OPENSSL_11_OR_HIGHER=true
	fi

	cd php-${PHP_VER}

	#Don't build ZTS version of PHP, we load MPM dynamically
	if [ -s sapi/apache2handler/config.m4 ]; then
		perl -pi -e 's|PHP_BUILD_THREAD_SAFE|PHP_BUILD_NOT_THREAD_SAFE|g' sapi/apache2handler/config.m4
	fi
	if [ -s sapi/apache2filter/config.m4 ]; then
		perl -pi -e 's|PHP_BUILD_THREAD_SAFE|PHP_BUILD_NOT_THREAD_SAFE|g' sapi/apache2filter/config.m4
	fi

	perl -pi -e 's|\(\(_libiconv_version >> 8\) & 0x0f\), \(_libiconv_version & 0x0f\)\)|_libiconv_version >> 8, _libiconv_version & 0xff\)|' ext/iconv/iconv.c
	perl -pi -e 's|"html_errors=0\\n"|"html_errors=0\\n"\n\t"disable_functions=\\n"|g' ./sapi/cli/php_cli.c
	if [ "${INT_MODE}" = "lsphp" ] && [ "${WEBSERVER_OPT}" != "apache" ] && [ "${WEBSERVER_OPT}" != "nginx_apache" ]; then
		PHP_LSAPI_VER="`curl -k -L --silent --fail https://update.litespeedtech.com/ws/latest.php | grep 'PHP-LSAPI' | cut -d= -f2`"
		# If we were unable to get the version from external source - set some default one
		if ! echo "${PHP_LSAPI_VER}" | grep -m1 -q '^[0-9]*\.[0-9]*'; then
			PHP_LSAPI_VER=8.0
		elif [ "${PHP_LSAPI_VER}" = "7.9" ]; then
			#PHP 8.1 is not compatible with 7.9, and 8.0 is not yet in latest.php on update.litespeedtech.com
			PHP_LSAPI_VER=8.0
		fi
		safeDownloadWithMove "${WORKDIR}/php-${PHP_VER}/php-litespeed-${PHP_LSAPI_VER}.tgz" "https://www.litespeedtech.com/packages/lsapi/php-litespeed-${PHP_LSAPI_VER}.tgz"
		cd sapi
		mv litespeed litespeed_orig
		tar xzf ../php-litespeed-${PHP_LSAPI_VER}.tgz --no-same-owner
		if [ -d litespeed ]; then
			mv -f litespeed/*.h litespeed_orig/
			mv -f litespeed/*.c litespeed_orig/
			rm -rf litespeed
		elif [ -d litespeed-${PHP_LSAPI_VER} ]; then
			mv -f litespeed-${PHP_LSAPI_VER}/*.h litespeed_orig/
			mv -f litespeed-${PHP_LSAPI_VER}/*.c litespeed_orig/
			rm -rf litespeed-${PHP_LSAPI_VER}
		fi
		mv litespeed_orig litespeed
		cd ../
	elif [ "${INT_MODE}" = "lsphp" ] && [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		safeDownloadWithMove "${WORKDIR}/php-litespeed-${CL_PHP_LSAPI_VER}.tgz" "${WEBPATH_CL}/php-litespeed-${CL_PHP_LSAPI_VER}.tgz"
		cd sapi
		mv litespeed litespeed_orig
		tar xzf ../php-litespeed-${CL_PHP_LSAPI_VER}.tgz --no-same-owner
		if [ -d litespeed ]; then
			mv -f litespeed/*.h litespeed_orig/
			mv -f litespeed/*.c litespeed_orig/
			rm -rf litespeed
		elif [ -d litespeed-${CL_PHP_LSAPI_VER} ]; then
			mv -f litespeed-${CL_PHP_LSAPI_VER}/*.h litespeed_orig/
			mv -f litespeed-${CL_PHP_LSAPI_VER}/*.c litespeed_orig/
			rm -rf litespeed-${CL_PHP_LSAPI_VER}
		fi
		mv litespeed_orig litespeed
		cd ../
	fi

	#make sure we have the sendmail link
	set_sendmail_link

	#some reports of missing -lltdl, problem found to be simple missing link
	if [ ! -e /usr/lib/libltdl.so ]; then
		ln -sf libltdl.so.3 /usr/lib/libltdl.so
	fi

	echo "Configuring php-${PHP_VER}..."

	PHP_INI_INT=${PHP_INI}
	PHP_EXT_INT=${PHP_EXT}

	AUTOCONF213="/usr/bin/autoconf-2.13"

	if [ "${INT_RELEASE}" = "5.3" ]; then
		if [ ! -e ${AUTOCONF213} ]; then
			install_debs autoconf2.13
			install_rpms autoconf213 
		fi
		if [ -e ${AUTOCONF213} ]; then
			touch ac*
			${AUTOCONF213}
		fi
	fi

	if [ "${INT_RELEASE}" = "7.1" ] || [ "${INT_RELEASE}" = "7.2" ]; then
		patch -p1 --fuzz=1 < ${WORKDIR}/patches/fpm_scoreboard_proc_oob_fix_v4.patch
		perl -pi -e 's|php_info_print_table_row\(2, "Configuration File \(php.ini\) Path"|php_info_print_table_row(2, "PHP-FPM security patch", "yes");\n\t\tphp_info_print_table_row(2, "Configuration File (php.ini) Path"|g' ./ext/standard/info.c
	fi

	if [ "${INT_RELEASE}" = "7.0" ]; then
		patch -p1 --fuzz=1 < ${WORKDIR}/patches/fpm_scoreboard_proc_oob_fix_v4_7.0.patch
		perl -pi -e 's|php_info_print_table_row\(2, "Configuration File \(php.ini\) Path"|php_info_print_table_row(2, "PHP-FPM security patch", "yes");\n\t\tphp_info_print_table_row(2, "Configuration File (php.ini) Path"|g' ./ext/standard/info.c
	fi

	if [ "${INT_RELEASE}" = "5.6" ]; then
		patch -p1 --fuzz=1 < ${WORKDIR}/patches/fpm_scoreboard_proc_oob_fix_v4_5.6.patch
		perl -pi -e 's|php_info_print_table_row\(2, "Configuration File \(php.ini\) Path"|php_info_print_table_row(2, "PHP-FPM security patch", "yes");\n\t\tphp_info_print_table_row(2, "Configuration File (php.ini) Path"|g' ./ext/standard/info.c
	fi

	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		if [ -e ${WORKDIR}/patches/cloudlinux/fpm-lve-php${INT_RELEASE}_autoconf.patch ]; then
			patch -p1 --fuzz=1 < ${WORKDIR}/patches/cloudlinux/fpm-lve-php${INT_RELEASE}_autoconf.patch
		fi
		if [ "${INT_RELEASE}" = "5.3" ] && [ -e ${AUTOCONF213} ]; then
			touch ac*
			${AUTOCONF213}
		else
			install_rpms autoconf
			install_debs autoconf
			touch ac*
			autoconf
		fi
	fi
	if [ "${INT_RELEASE}" = "5.3" ] && [ "${PHP53_VER}" != "5.2.17" ]; then
		echo "Patching PHP to fix bug #67541."
		patch -p1 < ${WORKDIR}/patches/php-5.3.28_apache-2.4.10-fpm.patch
		echo "Patching PHP to fix bug #52419."
		patch -p1 < ${WORKDIR}/patches/multi-sapi-5.3.29.patch
		if [ -e ${AUTOCONF213} ]; then
			touch ac*
			${AUTOCONF213} >/dev/null 2>&1
		else
			install_rpms autoconf
			install_debs autoconf
			touch ac*
			autoconf >/dev/null
		fi
	fi

	if ${OPENSSL_11_OR_HIGHER}; then
		if [ "${INT_RELEASE}" = "5.6" ]; then
			echo "Patching PHP to fix OpenSSL >=1.1 compatibility."
			patch -p1 < ${WORKDIR}/patches/php-5.6-libssl-1.1.patch
		fi
	fi

	if [ "${INT_RELEASE}" = "5.3" ] || [ "${INT_RELEASE}" = "5.4" ]; then
		if [ "${PHP53_VER}" != "5.2.17" ]; then
			#Still pathcing for #67541
			patch -p0 < ${WORKDIR}/patches/Another_fix_for_mod_proxy_fcgi_v2.patch
			echo "Patching is done."
		fi
	fi

	if [ "${INT_RELEASE}" = "7.3" ]; then
		patch -p1 < ${WORKDIR}/patches/php_mysqlnd_sha2_auth.patch
		echo "Patching MySQLnd to support SHA2 auth is done."
	fi

	if [ -s sapi/fpm/fpm/fpm_children.c ]; then
		echo "Patching php-fpm for per-user process grouping"
		patch -p0 < ${WORKDIR}/patches/fpm_children_cgroup.patch
	fi

	if [ -s sapi/fpm/fpm/fpm_unix.c ]; then
		#Ticket 21336: [pool user] failed to chown() the socket '/usr/local/php56/sockets/user.sock': Disk quota exceeded (122)
		echo "Patching php-fpm to not fail on startup if User quota maxed out on socket chown"
		patch -p0 < ${WORKDIR}/patches/fpm-quota-chown.patch
	fi

	PHP_INI_INT_VAR=PHP_INI_FPM${SHORT_RELEASE}
	PHP_INI_INT=${!PHP_INI_INT_VAR}
	PHP_EXT_INT_VAR=PHP_EXT_FPM${SHORT_RELEASE}
	PHP_EXT_INT=${!PHP_EXT_INT_VAR}

	local config_script=${configure_scripts_active[php${SHORT_RELEASE}_${INT_MODE}]}

	# Embed mode is used for nginx unit
	if grep -q -m1 'with-apxs2' "${config_script}"; then
		perl -pi -e 's#./configure --with-apxs2 #./configure --enable-embed #' "${config_script}"
	elif ! grep -q -m1 'enable-embed' "${config_script}"; then
		perl -pi -e 's#./configure #./configure --enable-embed #' "${config_script}"
	fi

	#we need to make sure that the mysql path is set.
	MYSQL_H=""

	if [ -d /usr/local/mysql/include ]; then
		MYSQL_H=/usr/local/mysql
	fi

	if [ "${MYSQL_H}" = "" ]; then
		if [ -e /usr/include/mysql/mysql.h ]; then
			MYSQL_H=/usr
		fi
	fi

	if [ "${MYSQL_H}" != "" ]; then
		perl -pi -e "s#with-mysql\s#with-mysql=${MYSQL_H} #" "${config_script}"
		perl -pi -e "s#with-mysql\"#with-mysql=${MYSQL_H}\"#" "${config_script}"
		perl -pi -e "s#with-pdo-mysql\"#with-pdo-mysql=${MYSQL_H}\"#" "${config_script}"
		perl -pi -e "s#with-pdo-mysql\s#with-pdo-mysql=${MYSQL_H} #" "${config_script}"
	fi

	if [ "${INT_RELEASE}" != "5.3" ] && [ "${INT_RELEASE}" != "5.4" ] && [ "${INT_RELEASE}" != "5.5" ] && [ "${INT_RELEASE}" != "5.6" ] && [ "${INT_RELEASE}" != "7.0" ] && [ "${INT_RELEASE}" != "7.1" ] && [ "${INT_RELEASE}" != "7.2" ]; then
		if [ ! -e /usr/local/bin/pcre2-config ] && [ -e /usr/bin/pcre2-config ]; then
			if grep -m1 -q 'with-pcre-regex=/usr/local' "${config_script}"; then
				perl -pi -e 's#with-pcre-regex=/usr/local#with-pcre-regex=/usr#g' "${config_script}"
			fi
		fi
	fi
	if [ ! -e /usr/local/bin/pcre-config ] && [ -e /usr/bin/pcre-config ]; then
		if grep -m1 -q 'with-pcre-regex=/usr/local' "${config_script}"; then
			perl -pi -e 's#with-pcre-regex=/usr/local#with-pcre-regex=/usr#g' "${config_script}"
			if [ -e /usr/lib64/libpcre.so ] && [ ! -e /usr/lib/libpcre.so ]; then
				ln -s /usr/lib64/libpcre.so /usr/lib/libpcre.so
			fi
			if [ -e /usr/lib/x86_64-linux-gnu/libpcre.so ] && [ ! -e /usr/lib/libpcre.so ]; then
				ln -s /usr/lib/x86_64-linux-gnu/libpcre.so /usr/lib/libpcre.so
			fi
			if [ -e /usr/lib/aarch64-linux-gnu/libpcre.so ] && [ ! -e /usr/lib/libpcre.so ]; then
				ln -s /usr/lib/aarch64-linux-gnu/libpcre.so /usr/lib/libpcre.so
			fi
			if [ -e /usr/lib/x86_64-linux-gnu/libpcre.a ] && [ ! -e /usr/lib/libpcre.a ]; then
				ln -s /usr/lib/x86_64-linux-gnu/libpcre.a /usr/lib/libpcre.a
			fi
			if [ -e /usr/lib/aarch64-linux-gnu/libpcre.a ] && [ ! -e /usr/lib/libpcre.a ]; then
				ln -s /usr/lib/aarch64-linux-gnu/libpcre.a /usr/lib/libpcre.a
			fi	
		fi
	fi

	#needed for PHP-versions <7.3
	if [ -e /usr/include/x86_64-linux-gnu/curl/easy.h ] && [ ! -e /usr/include/curl/easy.h ] && [ ! -d /usr/local/include/curl/easy.h ]; then
		ln -sf /usr/include/x86_64-linux-gnu/curl /usr/include/curl
	fi
	if [ ! -e /usr/local/lib/libpng.so ]; then
		if [ -e /usr/lib64/libpng.so ]; then
			LIBPNG_DIR="/usr/lib64"
		elif [ -e /usr/lib/x86_64-linux-gnu/libpng.so ]; then
			LIBPNG_DIR="/usr/lib/x86_64-linux-gnu"
		elif [ -e /usr/lib/aarch64-linux-gnu/libpng.so ]; then
			LIBPNG_DIR="/usr/lib/aarch64-linux-gnu"
		else
			LIBPNG_DIR="/usr/lib"
		fi

		if grep -m1 -q 'with-png-dir=/usr/local/lib' "${config_script}"; then
			perl -pi -e "s#with-png-dir=/usr/local/lib#with-png-dir=${LIBPNG_DIR}#g" "${config_script}"
		fi
	fi

	if [ ! -e /usr/local/lib/libjpeg.so ]; then
		if [ -e /usr/lib64/libjpeg.so ]; then
			LIBJPEG_DIR="/usr/lib64"
		elif [ -e /usr/lib/x86_64-linux-gnu/libjpeg.so ]; then
			LIBJPEG_DIR="/usr/lib/x86_64-linux-gnu"
		elif [ -e /usr/lib/aarch64-linux-gnu/libjpeg.so ]; then
			LIBJPEG_DIR="/usr/lib/aarch64-linux-gnu"
		else
			LIBJPEG_DIR="/usr/lib"
		fi
		
		if grep -m1 -q 'with-jpeg-dir=/usr/local/lib' "${config_script}"; then
			perl -pi -e "s#with-jpeg-dir=/usr/local/lib#with-jpeg-dir=${LIBJPEG_DIR}#g" "${config_script}"
		fi
	fi

	if [ ! -e /usr/local/lib/libwebp.so ]; then
		if [ -e /usr/lib64/libwebp.so ]; then
			LIBWEBP_DIR="/usr/lib64"
		elif [ -e /usr/lib/x86_64-linux-gnu/libwebp.so ]; then
			LIBWEBP_DIR="/usr/lib/x86_64-linux-gnu"
		elif [ -e /usr/lib/aarch64-linux-gnu/libwebp.so ]; then
			LIBWEBP_DIR="/usr/lib/x86_64-linux-gnu"
		else
			LIBWEBP_DIR="/usr/lib"
		fi
		
		if grep -m1 -q 'with-webp-dir=/usr/local/lib' "${config_script}"; then
			perl -pi -e "s#with-webp-dir=/usr/local/lib#with-webp-dir=${LIBWEBP_DIR}#g" "${config_script}"
		fi
	fi

	if [ ! -e /usr/local/lib/libfreetype.so ]; then
		if [ -e /usr/lib64/libfreetype.so ]; then
			LIBFREETYPE_DIR="/usr/lib64"
		elif [ -e /usr/lib/x86_64-linux-gnu/libfreetype.so ]; then
			LIBFREETYPE_DIR="/usr/lib/x86_64-linux-gnu"
		elif [ -e /usr/lib/aarch64-linux-gnu/libfreetype.so ]; then
			LIBFREETYPE_DIR="/usr/lib/aarch64-linux-gnu"
		else
			LIBFREETYPE_DIR="/usr/lib"
		fi
		
		if grep -m1 -q 'with-freetype-dir=/usr/local/lib' "${config_script}"; then
			perl -pi -e "s#with-freetype-dir=/usr/local/lib#with-freetype-dir=${LIBFREETYPE_DIR}#g" "${config_script}"
		fi
	fi

	if [ ! -e /usr/local/bin/iconv ]; then
		LIBICONV_DIR="/usr"
		
		if grep -m1 -q 'with-iconv=/usr/local' "${config_script}"; then
			perl -pi -e "s#with-iconv=/usr/local#with-iconv-dir=${LIBICONV_DIR}#g" "${config_script}"
		fi
	elif [ "${INT_RELEASE}" = "8.0" ] || [ "${INT_RELEASE}" = "8.1" ] || [ "${INT_RELEASE}" = "8.2" ]; then
		if ! grep -m1 -q 'with-iconv' "${config_script}"; then
			perl -pi -e 's#./configure #./configure --with-iconv=/usr/local #' "${config_script}"
		fi
	fi

	if [ ! -e /usr/local/icu/lib/libicudata.so ]; then
		LIBICU_DIR="/usr"
		
		if grep -m1 -q 'with-icu-dir=/usr/local/icu' "${config_script}"; then
			perl -pi -e "s#with-icu-dir=/usr/local/icu#with-icu-dir=${LIBICU_DIR}#g" "${config_script}"
		fi
	fi

	#we need to make sure that the mysqli path is set.
	MYSQLI_BIN=""
	if [ -e /usr/local/bin/mysql_config ]; then
		MYSQLI_BIN=/usr/local/bin/mysql_config
	fi
	if [ "${MYSQLI_BIN}" = "" ]; then
		if [ -e /usr/mysql/bin/mysql_config ]; then
			MYSQLI_BIN=/usr/mysql/bin/mysql_config
		fi
	fi
	if [ "${MYSQLI_BIN}" = "" ]; then
		if [ -e /usr/local/mysql/bin/mysql_config ]; then
			MYSQLI_BIN=/usr/local/mysql/bin/mysql_config
		fi
	fi
	if [ "${MYSQLI_BIN}" = "" ]; then
		if [ -e /usr/bin/mysql_config ]; then
			MYSQLI_BIN=/usr/bin/mysql_config
		fi
	fi

	if [ "${MYSQLI_BIN}" != "" ]; then
		perl -pi -e "s#with-mysqli\s#with-mysqli=${MYSQLI_BIN} #" "${config_script}"
		perl -pi -e "s#with-mysqli\"#with-mysqli=${MYSQLI_BIN}\"#" "${config_script}"
	fi

	MYSQL_SOCK='/var/lib/mysql/mysql.sock'
	if [ ! -e ${MYSQL_SOCK} ]; then
		if [ -x "${MYSQLI_BIN}" ]; then
			MYSQL_SOCK_NEW="`${MYSQLI_BIN} --socket`"
		fi
		if [ "${MYSQL_SOCK_NEW}" != "" ]; then
			MYSQL_SOCK="${MYSQL_SOCK_NEW}" 
		fi
	fi

	if [ "${MYSQL_SOCK}" = "/tmp/mysql.sock" ] && distro_is_debian; then
		MYSQL_SOCK=/usr/local/mysql/data/mysql.sock
	fi

	perl -pi -e "s#/var/lib/mysql/mysql.sock#${MYSQL_SOCK}#" "${config_script}"

	#if this is a 64bit system,make sure libmysqlclient is correct.
	if [ -e /usr/lib64/libmysqlclient.so ] && [ ! -e /usr/lib/libmysqlclient.so ]; then
		if [ "${MYSQL_OPT}" = "5.7" ] || [ "${MYSQL_OPT}" = "8.0" ]; then
			ln -s /usr/lib64/mysql/libmysqlclient.so /usr/lib/libmysqlclient.so
		else
			ln -s /usr/lib64/libmysqlclient.so /usr/lib/libmysqlclient.so
		fi
	fi

	#Reported a problem in ticket ID 9605
	#CFLAGS="`getGccOptions`" "${config_script}"

	# ICU 61+ compatibility with PHP 5.x
	if [ "${INT_RELEASE}" = "5.3" ] || [ "${INT_RELEASE}" = "5.4" ] || [ "${INT_RELEASE}" = "5.5" ] || [ "${INT_RELEASE}" = "5.6" ] || [ "${INT_RELEASE}" = "7.0" ]; then
		CXXFLAGS="-std=c++11 -DU_USING_ICU_NAMESPACE=1" "${config_script}"
	else
		"${config_script}"
	fi
	if [ $? -ne 0 ]; then
		printf "\n*** There was an error while trying to configure php. Check the configure file\n"
		do_exit 1
	fi

	echo "Done Configuration."

	perl -pi -e 's|$(PHP_RPATHS)|$(NATIVE_RPATHS) $(PHP_RPATHS)|g' Makefile

	#A fix for "ext/intl/msgformat/msgformat_helpers.o: undefined reference"
	if [ "${INT_RELEASE}" = "5.3" ]; then
		sed -i '/EXTRA_LIBS = /s|$| -lstdc++|' Makefile
		perl -pi -e 's|    \@\$\(INSTALL\)|\t\@\$\(INSTALL\)|g' Makefile
	fi

	echo "Trying to make php..."
	if ! C_INCLUDE_PATH=/usr/kerberos/include make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi

	#change the pear settings to remove the -n option.
	#the default memory limit was messing this up.
	/usr/bin/perl -pi -e 's/PEAR_INSTALL_FLAGS = .*/PEAR_INSTALL_FLAGS = -dshort_open_tag=0 -dsafe_mode=0/' Makefile

	#Remove symlink if exists
	if [ -h /usr/local/php${SHORT_RELEASE}/sbin/php-fpm${SHORT_RELEASE} ]; then
		rm -f /usr/local/php${SHORT_RELEASE}/sbin/php-fpm${SHORT_RELEASE}
	fi

	if [ -e ${PHP_INI_INT} ]; then

		#short_open_tag: https://help.directadmin.com/item.php?id=438
		perl -pi -e 's/^short_open_tag = Off/short_open_tag = On/' ${PHP_INI_INT}

		if [ "${INT_RELEASE}" != "5.3" ]; then
			echo "Making PHP ${INT_RELEASE} installation compatible with php.ini file"
			/usr/bin/perl -pi -e 's/^register_long_arrays/;register_long_arrays/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^magic_quotes_gpc/;magic_quotes_gpc/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^safe_mode/;safe_mode/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^register_globals/;register_globals/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^register_long_arrays/;register_long_arrays/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^allow_call_time_pass_reference/;allow_call_time_pass_reference/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^define_syslog_variables/;define_syslog_variables/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^highlight.bg/;highlight.bg/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^session.bug_compat_42/;session.bug_compat_42/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^session.bug_compat_warn/;session.bug_compat_warn/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^y2k_compliance/;y2k_compliance/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^magic_quotes_runtime/;magic_quotes_runtime/' ${PHP_INI_INT}
			/usr/bin/perl -pi -e 's/^magic_quotes_sybase/;magic_quotes_sybase/' ${PHP_INI_INT}
		fi
	fi

	PHP_EXT_INT_OLD="`echo ${PHP_EXT_INT} | perl -p0 -e 's|10-directadmin.ini|directadmin.ini|'`"
	if [ -e ${PHP_EXT_INT_OLD} ]; then
		rm -f ${PHP_EXT_INT_OLD}
	fi

	if [ -e ${PHP_EXT_INT} ]; then
		echo "Temporary disabling extensions..."
		mv -f ${PHP_EXT_INT} ${PHP_EXT_INT}.cb_backup
	fi

	if [ ! -d /usr/local/php${SHORT_RELEASE}/bin ]; then
		mkdir -p /usr/local/php${SHORT_RELEASE}/bin
	fi

	echo "Installing php..."
	make install

	if [ -e ${PHP_EXT_INT}.cb_backup ]; then
		echo "Enabling temporary disabled extensions..."
		mv -f ${PHP_EXT_INT}.cb_backup ${PHP_EXT_INT}
	fi

	#############################################################
	#we need to have this piece of code here, because without installation we do not have /usr/local/php53(54)/lib available, so we cannot copy php.ini there
	#old note: this was moved here, again for pear (before make install)
	echo "Copying php.ini.."
	if [ ! -e ${PHP_INI_INT} ]; then
		cp php.ini-${PHP_INI_TYPE_OPT} ${PHP_INI_INT}
	else
		echo "${PHP_INI_INT} already exists, skipping."
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if ${INT_MAIN_VERSION}; then
			rewrite_phpmodules
		fi
	fi

	COUNT=`grep -m1 -c '^date.timezone' ${PHP_INI_INT}`
	COUNT2=`grep -m1 -c ';date.timezone' ${PHP_INI_INT}`
	if [ "$COUNT" -eq 0 ] && [ "$COUNT2" -eq 0 ]; then
		echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to ${PHP_INI_INT}, please change it by yourself to fit your own needs.${boldoff}"
		echo "date.timezone = \"${PHP_TIMEZONE_OPT}\"" >> ${PHP_INI_INT}
	elif [ "$COUNT" -eq 0 ]; then
		echo "${boldon}Adding date.timezone = \"${PHP_TIMEZONE_OPT}\" to ${PHP_INI_INT}, please change it by yourself to fit your own needs.${boldoff}"
		perl -pi -e "s#;date.timezone.*#date.timezone = \"${PHP_TIMEZONE_OPT}\"#" ${PHP_INI_INT}
	fi
	/usr/bin/perl -pi -e 's/upload_max_filesize = 2M/upload_max_filesize = 64M/' ${PHP_INI_INT}
	/usr/bin/perl -pi -e 's/post_max_size = 8M/post_max_size = 64M/' ${PHP_INI_INT}

	if [ "${X_MAIL_HEADER_OPT}" = "yes" ]; then
		echo "Enabling  mail.add_x_header option in ${PHP_INI_INT}"
		/usr/bin/perl -pi -e 's/mail.add_x_header = Off/mail.add_x_header = On/' ${PHP_INI_INT}
		/usr/bin/perl -pi -e 's/mail.add_x_header = 0/mail.add_x_header = On/' ${PHP_INI_INT}
		COUNT=`grep -m1 -c '^mail.add_x_header' ${PHP_INI_INT}`
		if [ ${COUNT} -eq 0 ]; then
			echo "mail.add_x_header = On" >> ${PHP_INI_INT}
		fi
	else
		echo "Disabling mail.add_x_header option in ${PHP_INI_INT}"
		/usr/bin/perl -pi -e 's/^mail.add_x_header =/;mail.add_x_header =/' ${PHP_INI_INT}
	fi

	if [ -e /usr/local/php${SHORT_RELEASE}/bin/php${SHORT_RELEASE} ]; then
		echo "Creating symlink for /usr/local/php${SHORT_RELEASE}/bin/php${SHORT_RELEASE}..."
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/php${SHORT_RELEASE} /usr/local/php${SHORT_RELEASE}/bin/php
	fi
	if [ -e /usr/local/php${SHORT_RELEASE}/bin/lsphp${SHORT_RELEASE} ]; then
		echo "Creating symlink for /usr/local/php${SHORT_RELEASE}/bin/lsphp${SHORT_RELEASE}..."
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/lsphp${SHORT_RELEASE} /usr/local/php${SHORT_RELEASE}/bin/lsphp
	fi
	if [ -e /usr/local/php${SHORT_RELEASE}/bin/php-cgi${SHORT_RELEASE} ]; then
		echo "Creating symlink for /usr/local/php${SHORT_RELEASE}/bin/php-cgi${SHORT_RELEASE}..."
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/php-cgi${SHORT_RELEASE} /usr/local/php${SHORT_RELEASE}/bin/php-cgi
	fi
	if [ -e /usr/local/php${SHORT_RELEASE}/bin/php-config${SHORT_RELEASE} ]; then
		echo "Creating symlink for /usr/local/php${SHORT_RELEASE}/bin/php-config${SHORT_RELEASE}..."
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/php-config${SHORT_RELEASE} /usr/local/php${SHORT_RELEASE}/bin/php-config
	fi
	if [ -e /usr/local/php${SHORT_RELEASE}/bin/phpize${SHORT_RELEASE} ]; then
		echo "Creating symlink for /usr/local/php${SHORT_RELEASE}/bin/phpize${SHORT_RELEASE}..."
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/phpize${SHORT_RELEASE} /usr/local/php${SHORT_RELEASE}/bin/phpize
	fi
	
	if ${INT_MAIN_VERSION} && [ -e /usr/local/php${SHORT_RELEASE}/bin/php${SHORT_RELEASE} ]; then
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/php${SHORT_RELEASE} /usr/local/bin/php
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/pear /usr/local/bin/pear
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/pecl /usr/local/bin/pecl
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/phar /usr/local/bin/phar
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/phpize /usr/local/bin/phpize
		ln -sf /usr/local/php${SHORT_RELEASE}/bin/php-config /usr/local/bin/php-config
		if [ -e /usr/local/php${SHORT_RELEASE}/bin/lsphp ]; then
			cp -pf /usr/local/php${SHORT_RELEASE}/bin/lsphp /usr/local/bin/lsphp
		elif [ -e /usr/local/php${SHORT_RELEASE}/bin/lsphp${SHORT_RELEASE} ]; then
			cp -pf /usr/local/php${SHORT_RELEASE}/bin/lsphp${SHORT_RELEASE} /usr/local/bin/lsphp
		fi
	fi

	doPhpConf

	#############################################################
	#PHP Extensions
	if [ "${PHP_PHALCON_OPT}" = "yes" ]; then
		compile_php_phalcon_extension "${INT_RELEASE}"
	fi
	if [ "${PHP_SNUFFLEUPAGUS_OPT}" = "yes" ]; then
		if [ "${EXTENSION_INT_RELEASE}" != "5.3" ] && [ "${EXTENSION_INT_RELEASE}" != "5.4" ] && [ "${EXTENSION_INT_RELEASE}" != "5.5" ] && [ "${EXTENSION_INT_RELEASE}" != "5.6" ]; then
			doSnuffleupagus ${INT_RELEASE} ${INT_MODE} 1
		fi
	fi
	if [ "${PHP_IGBINARY_OPT}" = "yes" ]; then
		compile_php_igbinary_extension "${INT_RELEASE}"
	fi
	if [ "${PHP_REDIS_OPT}" = "yes" ]; then
		if [ "${EXTENSION_INT_RELEASE}" != "5.3" ] && [ "${EXTENSION_INT_RELEASE}" != "5.4" ] && [ "${EXTENSION_INT_RELEASE}" != "5.5" ] && [ "${EXTENSION_INT_RELEASE}" != "5.6" ]; then
			doPHPRedis ${INT_RELEASE} ${INT_MODE} 1
		fi
	fi
	if [ "${PHP_GMP_OPT}" = "yes" ]; then
		doPHPGmp ${INT_RELEASE} ${INT_MODE} 1
	fi
	if [ "${PHP_READLINE_OPT}" = "yes" ]; then
		doPHPReadline ${INT_RELEASE} ${INT_MODE} 1
	fi
	if [ "${PHP_XMLRPC_OPT}" = "yes" ]; then
		doPHPXmlrpc ${INT_RELEASE} ${INT_MODE} 1
	fi
	if [ "${PHP_IMAP_OPT}" = "yes" ]; then
		doPHPImap ${INT_RELEASE} ${INT_MODE} 1
	fi
	if [ "${PHP_BZ2_OPT}" = "yes" ]; then
		doPHPBz2 ${INT_RELEASE} ${INT_MODE} 1
	fi
	if [ "${INT_RELEASE}" != "8.0" ] && [ "${INT_RELEASE}" != "8.1" ] && [ "${INT_RELEASE}" != "8.2" ]; then
		if [ "${HTSCANNER_OPT}" = "yes" ]; then
			doPHPHtscanner ${INT_RELEASE} 1
		fi
	fi

	if [ "${PHP_LDAP_OPT}" = "yes" ]; then
		doPHPLDAP ${INT_RELEASE} ${INT_MODE} 1
	fi

	if [ "${OPCACHE_OPT}" = "yes" ]; then
		doOpcache ${INT_RELEASE} ${INT_MODE} 1
	fi

	if [ "${SUHOSIN_OPT}" = "yes" ]; then
		if [ "${INT_RELEASE}" != "5.3" ] && [ "${INT_RELEASE}" != "7.0" ] && [ "${INT_RELEASE}" != "7.1" ] && [ "${INT_RELEASE}" != "7.2" ] && [ "${INT_RELEASE}" != "7.3" ] && [ "${INT_RELEASE}" != "7.4" ] && [ "${INT_RELEASE}" != "8.0" ] && [ "${INT_RELEASE}" != "8.1" ] && [ "${INT_RELEASE}" != "8.2" ]; then
			doSuhosin ${INT_RELEASE} ${INT_MODE} 1
		else
			echo "This suhosin version does not support PHP ${INT_RELEASE}."
		fi
	fi

	if [ "${IONCUBE_OPT}" = "yes" ]; then
		doIoncube ${INT_RELEASE} ${INT_MODE} 1
	fi

	if [ "${IMAGICK_OPT}" = "yes" ]; then
		doIMagick ${INT_RELEASE} ${INT_MODE} 1
	fi

	#Only supported by PHP5
	if echo "${INT_RELEASE}" | grep -m1 -q '^5'; then
		if [ "${ZEND_OPT}" = "yes" ]; then
			doZend_build ${INT_RELEASE} ${INT_MODE} 1
		fi
	fi

	#Install Nginx Unit extension
	if [ -d /usr/lib/unit/modules ] && [ ! -s /usr/lib/unit/modules/php${INT_RELEASE}.unit.so ] && [ "${UNIT_OPT}" != "yes" ]; then
		if /usr/local/php${SHORT_RELEASE}/bin/php -i | grep -m1 -q 'enable-embed'; then
			doNginxUnit_module php ${INT_RELEASE}
		fi
	fi

	#############################################################

	if [ -s /usr/local/bin/php ] && [ ! -e /bin/php ]; then
		ln -s /usr/local/bin/php /bin/php
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	if [ "${INT_MODE}" = "php-fpm" ]; then
		#configuration
		mkdir -p /usr/local/php${SHORT_RELEASE}/sockets
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			chown apache:apache /usr/local/php${SHORT_RELEASE}/sockets
		elif [ "${WEBSERVER_OPT}" = "nginx" ]; then
			chown nginx:nginx /usr/local/php${SHORT_RELEASE}/sockets
		fi
		FPM_SOCK_CHMOD=700
		chmod ${FPM_SOCK_CHMOD} /usr/local/php${SHORT_RELEASE}/sockets

		if [ ! -s /usr/local/php${SHORT_RELEASE}/etc/php-fpm.conf ]; then
			PHP_FPM_CONF_FILE=${WORKDIR}/configure/fpm/conf/php-fpm.conf.${SHORT_RELEASE}
			if [ -e ${WORKDIR}/custom/php-fpm/conf/fpm.conf.${SHORT_RELEASE} ]; then
				cp -f ${WORKDIR}/custom/php-fpm/conf/fpm.conf.${SHORT_RELEASE} /usr/local/php${SHORT_RELEASE}/etc/php-fpm.conf
			elif [ -e ${WORKDIR}/custom/fpm/conf/fpm.conf.${SHORT_RELEASE} ]; then
				cp -f ${WORKDIR}/custom/fpm/conf/fpm.conf.${SHORT_RELEASE} /usr/local/php${SHORT_RELEASE}/etc/php-fpm.conf
			else
				cp -f ${PHP_FPM_CONF_FILE} /usr/local/php${SHORT_RELEASE}/etc/php-fpm.conf
			fi
		fi
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			perl -pi -e 's/nginx/apache/' /usr/local/php${SHORT_RELEASE}/etc/php-fpm.conf
		elif [ "${WEBSERVER_OPT}" = "nginx" ]; then
			perl -pi -e 's/apache/nginx/' /usr/local/php${SHORT_RELEASE}/etc/php-fpm.conf
		fi

		echo "Enabling php-fpm${SHORT_RELEASE} in systemd..."
		if [ -e ${CB_CUST_SYSTEMD}/php-fpm${SHORT_RELEASE}.service ]; then
			cp -f ${CB_CUST_SYSTEMD}/php-fpm${SHORT_RELEASE}.service ${SYSTEMDDIR}/php-fpm${SHORT_RELEASE}.service
		elif [ -e ${CB_CUST_SYSTEMD}/php-fpm.service ]; then
			cp -f ${CB_CUST_SYSTEMD}/php-fpm.service ${SYSTEMDDIR}/php-fpm${SHORT_RELEASE}.service
		else
			cp -f ${CB_SYSTEMD}/php-fpm.service ${SYSTEMDDIR}/php-fpm${SHORT_RELEASE}.service
		fi
		chmod 644 ${SYSTEMDDIR}/php-fpm${SHORT_RELEASE}.service
		perl -pi -e "s#/usr/local/php/sbin/php-fpm#/usr/local/php${SHORT_RELEASE}/sbin/php-fpm${SHORT_RELEASE}#" ${SYSTEMDDIR}/php-fpm${SHORT_RELEASE}.service
		perl -pi -e "s#/run/php-fpm.pid#/run/php-fpm${SHORT_RELEASE}.pid#" ${SYSTEMDDIR}/php-fpm${SHORT_RELEASE}.service
		if [ "${INT_RELEASE}" = "5.3" ]; then
			perl -pi -e 's/Type\=notify/Type=simple/' ${SYSTEMDDIR}/php-fpm${SHORT_RELEASE}.service
		fi
		DISABLE_PRIVATETMP=false
		if [ "${CLAMAV_OPT}" = "yes" ] && [ "${SUHOSIN_PHP_UPLOADSCAN_OPT}" = "yes" ]; then
			DISABLE_PRIVATETMP=true
		fi
		if [ -e /proc/1/environ ]; then
			if cat /proc/1/environ | tr '\0' '\n' | grep -q ^container=lxc; then
				DISABLE_PRIVATETMP=true
			fi
		fi
		if ${DISABLE_PRIVATETMP}; then
			echo "Upload scan option detected in options.conf. Disabling PrivateTmp feature in php-fpm${SHORT_RELEASE}.service for ClamAV to be able to scan files in /tmp."
			perl -pi -e 's#PrivateTmp\=true#PrivateTmp=false#' ${SYSTEMDDIR}/php-fpm${SHORT_RELEASE}.service
		fi
		systemctl daemon-reload
		systemctl enable php-fpm${SHORT_RELEASE}.service

		if [ -e /usr/local/php${SHORT_RELEASE}/sbin/php-fpm ] && [ ! -e /usr/local/php${SHORT_RELEASE}/sbin/php-fpm${SHORT_RELEASE} ]; then
			mv /usr/local/php${SHORT_RELEASE}/sbin/php-fpm /usr/local/php${SHORT_RELEASE}/sbin/php-fpm${SHORT_RELEASE}
		fi

		if [ ! -e /usr/local/php${SHORT_RELEASE}/sbin/php-fpm ]; then
			rm -f /usr/local/php${SHORT_RELEASE}/sbin/php-fpm
			ln -sf /usr/local/php${SHORT_RELEASE}/sbin/php-fpm${SHORT_RELEASE} /usr/local/php${SHORT_RELEASE}/sbin/php-fpm
		fi
		fpmChecks
		control_service php-fpm${SHORT_RELEASE} restart

		#Make log files available in /var/log
		if [ ! -h /var/log/php-fpm${SHORT_RELEASE}.log ]; then
			ln -sf /usr/local/php${SHORT_RELEASE}/var/log/php-fpm.log /var/log/php-fpm${SHORT_RELEASE}.log
		fi
	elif [ "${INT_MODE}" = "fastcgi" ]; then
		doSetupFcgidSh ${SHORT_RELEASE}
	fi

	if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		if [ -e /usr/local/php${SHORT_RELEASE}/bin/lsphp ] || [ -e /usr/local/php${SHORT_RELEASE}/bin/lsphp${SHORT_RELEASE} ]; then
			mkdir -p /usr/local/lsws/fcgi-bin
			control_service litespeed stop
			sleep 2
			pkill -x -9 litespeed >/dev/null 2>&1
			if [ -e /usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp ]; then
				ln -sf /usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp /usr/local/bin/lsphp
			elif [ -e /usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp${PHP1_SHORTRELEASE} ]; then
				ln -sf /usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp${PHP1_SHORTRELEASE} /usr/local/bin/lsphp
			fi
			#Use /usr/local/bin/lsphp as PHP path
			perl -pi -e 's|\$SERVER_ROOT/fcgi-bin/lsphp5|/usr/local/bin/lsphp|g' /usr/local/lsws/conf/httpd_config.xml
			#Set appropriate path for lsphp
			perl -pi -e 's|<path>\$SERVER_ROOT/usr/local/bin/lsphp</path>|<path>/usr/local/bin/lsphp</path>|g' /usr/local/lsws/conf/httpd_config.xml
			#Log just errors
			perl -pi -e 's|DEBUG|ERROR|g' /usr/local/lsws/conf/httpd_config.xml
			if [ -e /usr/local/php${SHORT_RELEASE}/bin/lsphp${SHORT_RELEASE} ]; then
				cp -pf /usr/local/php${SHORT_RELEASE}/bin/lsphp${SHORT_RELEASE} ${LSWS_HOME}/fcgi-bin/lsphp-${INT_RELEASE}
			else
				cp -pf /usr/local/php${SHORT_RELEASE}/bin/lsphp ${LSWS_HOME}/fcgi-bin/lsphp-${INT_RELEASE}
			fi
			if ${INT_MAIN_VERSION}; then
				rm -f ${LSWS_HOME}/fcgi-bin/lsphp
				ln -s ${LSWS_HOME}/fcgi-bin/lsphp-${INT_RELEASE} ${LSWS_HOME}/fcgi-bin/lsphp
				rm -f ${LSWS_HOME}/fcgi-bin/lsphp${SHORT_RELEASE}
				ln -s ${LSWS_HOME}/fcgi-bin/lsphp-${INT_RELEASE} ${LSWS_HOME}/fcgi-bin/lsphp${SHORT_RELEASE}
				if [ ! -f "${LSWS_HOME}/fcgi-bin/lsphp4" ]; then
					ln -sf "${LSWS_HOME}/fcgi-bin/lsphp" "${LSWS_HOME}/fcgi-bin/lsphp4"
				fi
				if [ ! -f "${LSWS_HOME}/fcgi-bin/lsphp7" ]; then
					ln -sf "${LSWS_HOME}/fcgi-bin/lsphp" "${LSWS_HOME}/fcgi-bin/lsphp7"
				fi
				if [ ! -f "${LSWS_HOME}/fcgi-bin/lsphp8" ]; then
					ln -sf "${LSWS_HOME}/fcgi-bin/lsphp" "${LSWS_HOME}/fcgi-bin/lsphp8"
				fi
				if [ ! -f "${LSWS_HOME}/fcgi-bin/lsphp5" ]; then
					ln -sf "${LSWS_HOME}/fcgi-bin/lsphp" "${LSWS_HOME}/fcgi-bin/lsphp5"
				fi
				if [ ! -f "${LSWS_HOME}/fcgi-bin/lsphp55" ]; then
					ln -sf "${LSWS_HOME}/fcgi-bin/lsphp" "${LSWS_HOME}/fcgi-bin/lsphp55"
				fi
			fi
			control_service litespeed start
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		if [ -e /usr/local/php${SHORT_RELEASE}/bin/lsphp ] || [ -e /usr/local/php${SHORT_RELEASE}/bin/lsphp${SHORT_RELEASE} ]; then
			mkdir -p /usr/local/lsws/fcgi-bin
			control_service litespeed stop
			sleep 2
			pkill -x -9 litespeed >/dev/null 2>&1
			if ${INT_MAIN_VERSION}; then
				if [ -e /usr/local/php${SHORT_RELEASE}/bin/lsphp ]; then
					ln -sf /usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp /usr/local/bin/lsphp
				else
					ln -sf /usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp${PHP1_SHORTRELEASE} /usr/local/bin/lsphp
				fi
			fi
			control_service litespeed start
		fi
	fi

	if [ "${CLOUDLINUX_OPT}" = "yes" ] && [ "${INT_MODE}" = "lsphp" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ] && [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			if [ ! -s /usr/lib/apache/mod_lsapi.so ]; then
				doModLsapi 0
			else
				if [ -s ${STRINGS} ]; then
					MODLSAPIV="`${STRINGS} /usr/lib/apache/mod_lsapi.so | grep -m1 'version' | awk '{print $3}' | cut -d: -f1 | grep -o '.*[0-9][^a-z]'`"
					if [ "${MODLSAPIV}" != "${MOD_LSAPI_VER}" ]; then
						doModLsapi 0
					fi
				fi
			fi
		fi
	fi

	if ${INT_MAIN_VERSION}; then
		NATIVE_CONF=/etc/cl.selector/native.conf

		if [ -e ${NATIVE_CONF} ] && [ "${CLOUDLINUX_OPT}" = "yes" ] && [ -x /usr/sbin/cagefsctl ]; then
			/usr/sbin/cagefsctl --setup-cl-selector
		fi
	fi

	#install proactive defence if exists
	if [ -x /usr/share/i360-php/easyapache3/native_da.hook ]; then
		PHP_BUILD_BIN=/usr/local/php${SHORT_RELEASE}/bin/php
		/usr/share/i360-php/easyapache3/native_da.hook --install-i360 ${PHP_BUILD_BIN}
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		#Revert temporary MPM mode set (to be fail-proof with non-ZTS version)
		if [ -s ${PHPMODULES} ]; then
			set_apache_mpm
		fi
		echo "Restarting apache."
		control_service httpd restart
	fi
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "Restarting nginx."
		control_service nginx stop >/dev/null 2>&1
		control_service nginx start
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "Rewriting all users httpd.conf files, please wait..."
		"${DA_BIN}" taskq --run 'action=rewrite&value=httpd'
	elif [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		echo "Rewriting all users openlitespeed.conf files, please wait..."
		"${DA_BIN}" taskq --run 'action=rewrite&value=openlitespeed'
	elif [ "${WEBSERVER_OPT}" = "nginx" ]; then
		echo "Rewriting all users nginx.conf files, please wait..."
		"${DA_BIN}" taskq --run 'action=rewrite&value=nginx'
	fi

	echo "PHP ${PHP_VER} Installed."
	writeLog "PHP ${PHP_VER} installed"

	cd ${WORKDIR}
}

####################################################

doModAclr2() {
	cd ${WORKDIR}
	if [ "${WEBSERVER_OPT}" != "nginx_apache" ]; then
		do_exit 1 "Cannot build mod_aclr2, because of the chosen webserver in the options.conf file."
	fi
	safeDownloadWithMove "${WORKDIR}/mod_aclr2-${MOD_ACLR2_VER}.tar.gz" "${MOD_ACLR2_DOWNLOADURL}"

	FILE=${WORKDIR}/mod_aclr2-${MOD_ACLR2_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	#We don't have a directory in a tarball, so we create it here, and extract files to it
	mkdir -p mod_aclr2-${MOD_ACLR2_VER}
	tar xzf ${FILE} -C ./mod_aclr2-${MOD_ACLR2_VER}
	cd mod_aclr2-${MOD_ACLR2_VER}

	echo "Installing mod_aclr2-${MOD_ACLR2_VER}..."

	APXS=/usr/sbin/apxs
	if [ ! -e $APXS ]; then
		echo "cannot find $APXS, trying a different path"
		APXS=/usr/bin/apxs
	fi
	$APXS -c mod_aclr2.c
	$APXS -i -a -n aclr mod_aclr2.la

	if [ $? -ne 0 ]; then
		printf "\n*** There was an error while trying to install mod_aclr2-${MOD_ACLR2_VER}.\n"
		do_exit 1
	fi
 
	perl -pi -e 's|^LoadModule aclr_module|#LoadModule aclr_module|' /etc/httpd/conf/httpd.conf

	echo "mod_aclr2 has been installed successfully."
	writeLog "mod_aclr2 installed"

	cd ${WORKDIR}
}

####################################################

doModHtscanner() {
	cd ${WORKDIR}
	if [ "${HTSCANNER_OPT}" = "no" ]; then
		do_exit 1 "Cannot build htscanner, because you do not have it set in php_extensions.conf file."
	fi
	if [ ! -e /usr/sbin/apxs ]; then
		echo "/usr/sbin/apxs is not found, skipping htscanner for now."
		return
	fi
	safeDownloadWithMove "${WORKDIR}/htscanner-${HTSCANNER_VER}.tgz" "${HTSCANNER_DOWNLOADURL}"

	FILE=${WORKDIR}/htscanner-${HTSCANNER_VER}.tgz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE}
	cd htscanner-${HTSCANNER_VER}

	echo "Installing mod_htscanner2-${HTSCANNER_VER}..."

	APXS=/usr/sbin/apxs
	if [ ! -e $APXS ]; then
		echo "cannot find $APXS, trying a different path"
		APXS=/usr/bin/apxs
	fi
	$APXS -a -i -c mod_htscanner2.c

	if [ $? -ne 0 ]; then
		printf "\n*** There was an error while trying to install mod_htscanner2-${HTSCANNER_VER}.\n"
		do_exit 1
	fi

	set_LoadModule htscanner_module mod_htscanner2.so

	"${DA_BIN}" taskq --run 'action=rewrite&value=httpd'
	echo "mod_htscanner2 has been installed successfully."
	writeLog "mod_htscanner2 installed"

	cd ${WORKDIR}
}

####################################################

doModFCGID() {
	cd ${WORKDIR}
	if [ "${WEBSERVER_OPT}" = "nginx" ]; then
		do_exit 1 "Cannot build mod_fcgid, because nginx webserver is chosen in the options.conf file."
	fi
	safeDownloadWithMove "${WORKDIR}/mod_fcgid-${MOD_FCGID_VER}.tar.gz" "${MOD_FCGID_DOWNLOADURL}"

	FILE=${WORKDIR}/mod_fcgid-${MOD_FCGID_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE} --no-same-owner
	cd mod_fcgid-${MOD_FCGID_VER}

	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		patch -p1 < ${WORKDIR}/patches/cloudlinux/mod_fcgid_2_3_7.patch
	fi

	patch -p1 < ${WORKDIR}/patches/fcgid_cmdline_max.patch

	echo "Installing mod_fcgid-${MOD_FCGID_VER}..."

	APXS=/usr/sbin/apxs ./configure.apxs

	echo "Trying to make mod_fcgid-${MOD_FCGID_VER}..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing mod_fcgid-${MOD_FCGID_VER}..."
	make install

	set_LoadModule fcgid_module mod_fcgid.so
	
	if [ -e ${PHPMODULES} ]; then
		if ! grep -m1 -q 'httpd-fcgid.conf' ${PHPMODULES}; then
			echo "Include /etc/httpd/conf/extra/httpd-fcgid.conf" >> ${PHPMODULES}
		fi
	fi

	if [ ! -e ${HTTPDCONF}/extra/httpd-fcgid.conf ] && [ -e ${WORKDIR}/configure/ap2/conf/extra/httpd-fcgid.conf ]; then
		cp ${WORKDIR}/configure/ap2/conf/extra/httpd-fcgid.conf ${HTTPDCONF}/extra/httpd-fcgid.conf
	fi

	"${DA_BIN}" taskq --run 'action=rewrite&value=httpd'

	echo "mod_fcgid-${MOD_FCGID_VER} has been installed successfully."
	writeLog "mod_fcgid ${MOD_FCGID_VER} installed"

	cd ${WORKDIR}
	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
}

ensure_server_ca() {
	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		SSL_CA=${HTTPDCONF}/ssl.crt/server.ca
		SSL_CRT=${HTTPDCONF}/ssl.crt/server.crt
		SSL_KEY=${HTTPDCONF}/ssl.key/server.key
		mkdir -p ${HTTPDCONF}/ssl.crt
		ensure_dhparam ${HTTPDCONF}/ssl.crt/dhparams.pem
	elif [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		SSL_CA=${LSWS_HOME}/ssl.crt/server.ca
		SSL_CRT=${LSWS_HOME}/ssl.crt/server.crt
		SSL_KEY=${LSWS_HOME}/ssl.key/server.key
		mkdir -p ${LSWS_HOME}/ssl.crt
	elif [ "${WEBSERVER_OPT}" = "nginx" ]; then
		SSL_CA=${NGINXCONF}/ssl.crt/server.ca
		SSL_CRT=${NGINXCONF}/ssl.crt/server.crt
		mkdir -p ${NGINXCONF}/ssl.crt
		ensure_dhparam ${NGINXCONF}/ssl.crt/dhparams.pem
	else
		echo "Unknown value for webserver=${WEBSERVER_OPT}"
		return
	fi

	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		mkdir -p ${NGINXCONF}/ssl.crt
		mkdir -p ${NGINXCONF}/ssl.key
		ensure_dhparam ${NGINXCONF}/ssl.crt/dhparams.pem
	fi

	echo "Checking to ensure ${SSL_CA} is set."

	if [ ! -s ${SSL_CA} ]; then
		echo "Downloading new generic server.ca ..."
		safeDownloadWithMove "${SSL_CA}" "${WEBPATH_SERVICES}/all/ssl/server.ca"
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ]; then
		if [ -s ${SSL_CRT} ] && [ -s ${SSL_CA} ]; then
			cat ${SSL_CRT} > ${SSL_CRT}.combined
			#Sometimes we don't have a new line in SSL_CRT, so we add one to separate SSL_CRT and SSL_CA
			echo >> ${SSL_CRT}.combined
			cat ${SSL_CA} >> ${SSL_CRT}.combined
		fi
	fi
	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ -s ${SSL_CRT} ] && [ -s ${SSL_CA} ]; then
			cat ${SSL_CRT} > ${SSL_CRT}.combined
			#Sometimes we don't have a new line in SSL_CRT, so we add one to separate SSL_CRT and SSL_CA
			echo >> ${SSL_CRT}.combined
			cat ${SSL_CA} >> ${SSL_CRT}.combined
		fi
		NG_CA=${NGINXCONF}/ssl.crt/server.ca
		NG_CRT=${NGINXCONF}/ssl.crt/server.crt
		NG_KEY=${NGINXCONF}/ssl.key/server.key

		CP_FLAGS="-fu"
		if [ ! -L ${SSL_CA} ]; then
			cp ${CP_FLAGS} ${SSL_CA} ${NG_CA}
		fi
		if [ ! -L ${SSL_CRT} ]; then
			cp ${CP_FLAGS} ${SSL_CRT} ${NG_CRT}
		fi
		if [ ! -L ${SSL_KEY} ]; then
			cp ${CP_FLAGS} ${SSL_KEY} ${NG_KEY}
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		NG_CA=${NGINXCONF}/ssl.crt/server.ca
		NG_CRT=${NGINXCONF}/ssl.crt/server.crt

		if [ -s ${NG_CRT} ] && [ -s ${NG_CA} ]; then
			cat ${NG_CRT} > ${NG_CRT}.combined
			#Sometimes we don't have a new line in SSL_CRT, so we add one to separate SSL_CRT and SSL_CA
			echo >> ${SSL_CRT}.combined
			cat ${NG_CA} >> ${NG_CRT}.combined
		fi

		chmod 600 ${NGINXCONF}/ssl.crt/server.ca
		chmod 600 ${NGINXCONF}/ssl.crt/server.crt
		chmod 600 ${NG_CRT}.combined
	fi
}

backupHttp() {
	echo "Backing up certificate and key, and turning off httpd for DirectAdmins's check."

	if [ -e ${HTTPDCONF}/ssl.crt/server.crt ]; then
		cp -fp ${HTTPDCONF}/ssl.crt/server.crt ${HTTPDCONF}/ssl.crt/server.crt.backup
	fi
	if [ -e ${HTTPDCONF}/ssl.key/server.key ]; then
		cp -fp ${HTTPDCONF}/ssl.key/server.key ${HTTPDCONF}/ssl.key/server.key.backup
	fi
	if [ -e ${HTTPD_CONF} ]; then
		cp -fp ${HTTPD_CONF} ${HTTPD_CONF}.backup
	fi

	#turn off httpd service checking
	set_service httpd OFF
}

restoreHttp() {
	echo "Restoring certificate and key, and turning on httpd for DirectAdmins's check."

	if [ -e ${HTTPDCONF}/ssl.crt/server.crt.backup ]; then
		cp -fp ${HTTPDCONF}/ssl.crt/server.crt.backup ${HTTPDCONF}/ssl.crt/server.crt
		chmod 600 ${HTTPDCONF}/ssl.crt/server.crt
	fi
	if [ -e ${HTTPDCONF}/ssl.key/server.key.backup ]; then
		cp -fp ${HTTPDCONF}/ssl.key/server.key.backup ${HTTPDCONF}/ssl.key/server.key
		chmod 600 ${HTTPDCONF}/ssl.key/server.key
	fi
	if [ -e ${HTTPDCONF}/httpd.conf.backup ]; then
		cp -fp ${HTTPDCONF}/httpd.conf.backup ${HTTPDCONF}/httpd.conf
	fi

	ensure_server_ca

	#turn on httpd service checking
	set_service httpd ON
}

####################################################

checkRPMS() {
	if ! distro_is_rhel; then
		return
	fi

	echo "Removing all apache related rpms..."
	rpm -e --nodeps mod_auth_pgsql 2> /dev/null
	rpm -e --nodeps mod_python 2> /dev/null
	rpm -e --nodeps mod_auth_mysql 2> /dev/null
	rpm -e --nodeps mod_auth_any 2> /dev/null
	rpm -e --nodeps mod_dav 2> /dev/null
	rpm -e --nodeps mod_ssl 2> /dev/null
	rpm -e --nodeps mod_perl 2> /dev/null
	rpm -e --nodeps mod_fpse 2> /dev/null
	rpm -e --nodeps apache-fp 2> /dev/null
	rpm -e --nodeps apache-fp-devel 2> /dev/null
	rpm -e --nodeps apache-manual 2> /dev/null
	rpm -e --nodeps apacheconf 2> /dev/null
	rpm -e --nodeps apache-devel 2> /dev/null
	rpm -e --nodeps apache 2> /dev/null
	rpm -e --nodeps httpd 2> /dev/null
	rpm -e --nodeps httpd-devel 2> /dev/null
	rpm -e --nodeps httpd-tools 2> /dev/null
	rpm -e --nodeps httpd-manual 2> /dev/null
	rpm -e --nodeps php 2> /dev/null
	echo "All apache related rpms have been removed."
}

####################################################

#addUserGroup mail mail 12 12
addUserGroup() {
	if distro_is_debian; then
		if ! /usr/bin/id ${1} > /dev/null 2>&1; then
			/usr/sbin/adduser --system --group --no-create-home \
			    --disabled-login --force-badname ${1} > /dev/null
		fi
	elif distro_is_rhel; then
		if ! /usr/bin/id ${1} > /dev/null 2>&1; then
			/usr/sbin/useradd -r -s /bin/false ${1}
		fi
	fi
}

####################################################

set64() {
	if [ ! -d /usr/lib64 ]; then
		return
	fi
	if [ ! -e /usr/lib/libssl.so ]; then
		ln -sf /usr/lib64/libssl.so /usr/lib/libssl.so
	fi
	if [ ! -e /usr/lib/libidn.so ]; then
		ln -sf /usr/lib64/libidn.so /usr/lib/libidn.so
	fi
}

####################################################

doApacheCheck() {
	if [ ! -e ${HTTPDCONF}/extra/httpd-includes.conf ]; then
		echo -n "" > ${HTTPDCONF}/extra/httpd-includes.conf
	fi

	if [ ! -e ${HTTPDCONF}/extra/httpd-php-handlers.conf ]; then
		echo -n "" > ${HTTPDCONF}/extra/httpd-php-handlers.conf
	fi

	if [ ! -e ${HTTPDCONF}/extra/httpd-phpmodules.conf ]; then
		echo -n "" > ${HTTPDCONF}/extra/httpd-phpmodules.conf
	fi
}

####################################################

setFDSETSIZE() {
	#this bit is to increase the socket limit
	if [ -e /usr/include/bits/typesizes.h ]; then
		perl -pi -e 's/__FD_SETSIZE.*1024/__FD_SETSIZE 32768/' /usr/include/bits/typesizes.h
	fi

	if [ -e /usr/include/linux/posix_types.h ]; then
		perl -pi -e 's/__FD_SETSIZE.*1024/__FD_SETSIZE 32768/' /usr/include/linux/posix_types.h
	fi

	if [ -e /usr/include/bits/types.h ]; then
		perl -pi -e 's/__FD_SETSIZE.*1024/__FD_SETSIZE 32768/' /usr/include/bits/types.h
	fi

	NUMBER=`cat /proc/sys/fs/file-max`
	if [ ${NUMBER} -lt 131072 ]; then
		echo "131072" > /proc/sys/fs/file-max
	fi
}

####################################################

#tokenize the IP
tokenize_IP() {
	TOKENFILE_APACHE=${HTTPDCONF}/extra/httpd-vhosts.conf
	
	TOKENFILE_OPENLITESPEED=${LSWS_HOME}/conf/httpd-vhosts.conf

	TOKENFILE_NGINX=${NGINXCONF}/nginx.conf
	if [ -e ${TOKENFILE_NGINX} ]; then
		if grep -q -m1 'nginx-vhosts\.conf' ${TOKENFILE_NGINX}; then
			TOKENFILE_NGINX=${NGINXCONF}/nginx-vhosts.conf
		fi
	fi
	TOKENFILE_NGINX_USERDIR=${NGINXCONF}/nginx-userdir.conf

	if [ -d /usr/local/directadmin/data/admin/ips ]; then
		IP="`grep -r -l -m1 '^status=server$' /usr/local/directadmin/data/admin/ips | cut -d/ -f8`"
	fi
	if [ "${IP}" = "" ]; then
		IP="`grep -im1 ${HOSTNAME} /etc/hosts | awk '{print $1}'`"
		if [ "${IP}" = "" ]; then
			echo "Unable to detect your server IP in /etc/hosts. Please enter it: "
			read IP
		fi
	fi
	if [ "${IP}" = "" ]; then
		echo "Unable to detect your server IP. Exiting..."
		do_exit 0
	fi

	if [ "`echo ${IP} | grep -m1 -c ':'`" -gt 0 ]; then
		IP="[${IP}]"
	fi

	echo "Using $IP for your server IP"
	
	LAN_IP=$(${DA_BIN} config-get lan_ip)

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ -e ${TOKENFILE_APACHE} ]; then
			if [ "`grep -m1 -c '|IP|' ${TOKENFILE_APACHE}`" -gt "0" ]; then
				perl -pi -e "s/\|IP\|/${IP}/" ${TOKENFILE_APACHE}
			fi

			if [ "`grep -m1 -c '|LINKEDIP|' ${TOKENFILE_APACHE}`" -gt "0" ]; then
				#|LINKEDIP| and |LINKEDIPSSL|
				#set them or clear them.

				IP_CF=/usr/local/directadmin/data/admin/ips/${IP}
				if [ -s ${IP_CF} ] && [ -s ${DACONF_FILE} ]; then
					if [ "`grep -m1 -c '^linked_ips=' ${IP_CF}`" -gt "0" ]; then
						#2 will tokenize the httpd-vhosts.conf
						/usr/local/directadmin/dataskq --linked-ips=2
					fi
				fi

				#this is a fallback, in case the dataskq did not do it
				perl -pi -e 's/\|LINKEDIP\|//' ${TOKENFILE_APACHE}
				perl -pi -e 's/\|LINKEDIPSSL\|//' ${TOKENFILE_APACHE}
			fi
		fi
	fi
	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		if [ -e ${TOKENFILE_OPENLITESPEED} ]; then
			if [ "`grep -m1 -c '|IP_LISTENER|' ${TOKENFILE_OPENLITESPEED}`" -gt "0" ]; then
				IP_LISTENER=`echo "${IP}" | tr '.:' '-'`
				perl -pi -e "s/\|IP_LISTENER\|/${IP_LISTENER}/g" ${TOKENFILE_OPENLITESPEED}
			fi
			if [ "`grep -m1 -c '|HOSTNAME|' ${TOKENFILE_OPENLITESPEED}`" -gt "0" ]; then
				perl -pi -e "s/\|HOSTNAME\|/${HOSTNAME}/g" ${TOKENFILE_OPENLITESPEED}
			fi
			if [ "`grep -m1 -c '|LINKEDIP_LISTENERS|' ${TOKENFILE_OPENLITESPEED}`" -gt "0" ]; then
				#|LINKEDIP_LISTENERS|
				#set them or clear them.

				IP_CF=/usr/local/directadmin/data/admin/ips/${IP}
				if [ -s ${IP_CF} ] && [ -s ${DACONF_FILE} ]; then
					if [ "`grep -m1 -c '^linked_ips=' ${IP_CF}`" -gt "0" ]; then
						#4 will tokenize the httpd-vhosts.conf
						/usr/local/directadmin/dataskq --linked-ips=4
					fi
				fi

				#this is a fallback, in case the dataskq did not do it
				perl -pi -e 's/\|LINKEDIP_LISTENERS\|//' ${TOKENFILE_OPENLITESPEED}
			fi
		fi
	fi
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ -e ${TOKENFILE_NGINX} ]; then
			if [ "`grep -m1 -c '|IP|' ${TOKENFILE_NGINX}`" -gt "0" ]; then
				if [ "${LAN_IP}" != "" ] && [ "${LAN_IP}" != "${IP}" ]; then
					echo "Using lan_ip=$LAN_IP as a secondary server IP";
					perl -pi -e "s/\|IP\|:\|PORT_80\|;/\|IP\|:\|PORT_80\|;\n\tlisten\t\t${LAN_IP}:\|PORT_80\|;/" ${TOKENFILE_NGINX}
					perl -pi -e "s/\|IP\|:\|PORT_443\| ssl\|SPACE_HTTP2\|;/\|IP\|:\|PORT_443\| ssl\|SPACE_HTTP2\|;\n\tlisten\t\t${LAN_IP}:\|PORT_443\| ssl\|SPACE_HTTP2\|;/" ${TOKENFILE_NGINX}
				fi

				echo "Using $IP for your server IP"
				perl -pi -e "s/\|IP\|/${IP}/" ${TOKENFILE_NGINX}
			fi

			if [ "`grep -m1 -c '|LINKEDIP|' ${TOKENFILE_NGINX}`" -gt "0" ]; then
				#|LINKEDIP| and |LINKEDIPSSL|
				#set them or clear them.

				IP_CF=/usr/local/directadmin/data/admin/ips/${IP}
				if [ -s ${IP_CF} ] && [ -s ${DACONF_FILE} ]; then
					if [ "`grep -m1 -c '^linked_ips=' ${IP_CF}`" -gt "0" ]; then
						#3 will tokenize the nginx-vhosts.conf
						/usr/local/directadmin/dataskq --linked-ips=3
					fi
				fi

				#this is a fallback, in case the dataskq did not do it
				perl -pi -e 's/\|LINKEDIP\|//' ${TOKENFILE_NGINX}
				perl -pi -e 's/\|LINKEDIPSSL\|//' ${TOKENFILE_NGINX}		
			fi
		fi
		if [ -e ${TOKENFILE_NGINX_USERDIR} ]; then
			if [ "`grep -m1 -c '|IP|' ${TOKENFILE_NGINX_USERDIR}`" -gt "0" ]; then
				if [ "${LAN_IP}" != "" ] && [ "${LAN_IP}" != "${IP}" ]; then
					perl -pi -e "s/\|IP\|:\|PORT_80\|;/\|IP\|:\|PORT_80\|;\n\tlisten\t\t${LAN_IP}:\|PORT_80\|;/" ${TOKENFILE_NGINX_USERDIR}
					perl -pi -e "s/\|IP\|:\|PORT_443\| ssl\|SPACE_HTTP2\|;/\|IP\|:\|PORT_443\| ssl\|SPACE_HTTP2\|;\n\tlisten\t\t${LAN_IP}:\|PORT_443\| ssl\|SPACE_HTTP2\|;/" ${TOKENFILE_NGINX_USERDIR}
				fi

				perl -pi -e "s/\|IP\|/${IP}/" ${TOKENFILE_NGINX_USERDIR}
			fi
		fi
	fi
}

#tokenize ports
tokenize_ports() {
	getWebserverPorts
	TOKENFILE_APACHE=${HTTPDCONF}/extra/httpd-vhosts.conf

	TOKENFILE_NGINX=${NGINXCONF}/nginx.conf
	if [ -e ${TOKENFILE_NGINX} ]; then
		if grep -q -m1 'nginx-vhosts\.conf' ${TOKENFILE_NGINX}; then
			TOKENFILE_NGINX=${NGINXCONF}/nginx-vhosts.conf
		fi
	fi
	TOKENFILE_NGINX_USERDIR=${NGINXCONF}/nginx-userdir.conf

	TOKENFILE_OPENLITESPEED=${LSWS_HOME}/conf/httpd-vhosts.conf

	if [ "${WEBSERVER_OPT}" = "openlitespeed" ] && [ -s ${TOKENFILE_OPENLITESPEED} ]; then
		if [ "`grep -m1 -c '|PORT_80|' ${TOKENFILE_OPENLITESPEED}`" -gt "0" ]; then
			perl -pi -e "s/\|PORT_80\|/${PORT_80}/g" ${TOKENFILE_OPENLITESPEED}
		fi
		if [ "`grep -m1 -c '|PORT_443|' ${TOKENFILE_OPENLITESPEED}`" -gt "0" ]; then
			perl -pi -e "s/\|PORT_443\|/${PORT_443}/g" ${TOKENFILE_OPENLITESPEED}
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		if [ -e ${TOKENFILE_APACHE} ]; then
			if [ "`grep -m1 -c '|PORT_80|' ${TOKENFILE_APACHE}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_80\|/${PORT_80}/g" ${TOKENFILE_APACHE}
			else
				perl -pi -e "s/:${PORT_8080}\>/:${PORT_80}\>/" ${TOKENFILE_APACHE}
				perl -pi -e "s/^Listen ${PORT_8080}$/Listen ${PORT_80}/" ${TOKENFILE_APACHE}
			fi
			if [ "`grep -m1 -c '|PORT_443|' ${TOKENFILE_APACHE}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_443\|/${PORT_443}/g" ${TOKENFILE_APACHE}
			else
				perl -pi -e "s/:${PORT_8081}\>/:${PORT_443}\>/" ${TOKENFILE_APACHE}
				perl -pi -e "s/^Listen ${PORT_8081}$/Listen ${PORT_443}/" ${TOKENFILE_APACHE}
			fi

			SSLFILE=${HTTPDCONF}/extra/httpd-ssl.conf
			perl -pi -e "s/\|PORT_443\|/${PORT_443}/g" ${SSLFILE}
			perl -pi -e "s/:${PORT_8081}\>/:${PORT_443}\>/" ${SSLFILE}
			perl -pi -e "s/^Listen ${PORT_8081}$/Listen ${PORT_443}/" ${SSLFILE}

			perl -pi -e "s/\|PORT_80\|/${PORT_80}/g" ${HTTPD_CONF}
			perl -pi -e "s/:${PORT_8080}\>/:${PORT_80}\>/" ${HTTPD_CONF}
			perl -pi -e "s/^Listen ${PORT_8080}$/Listen ${PORT_80}/" ${HTTPD_CONF}
		fi
	fi
	
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		SPACE_HTTP2=" http2"
		HTTP2=$(${DA_BIN} config-get http2)
		if [ "$HTTP2" = "0" ]; then
			SPACE_HTTP2=
		fi

		perl -pi -e "s/\|SPACE_HTTP2\|/${SPACE_HTTP2}/g" ${TOKENFILE_NGINX}
	fi

	if [ "${WEBSERVER_OPT}" = "nginx" ]; then
		if [ -e ${TOKENFILE_NGINX} ]; then
			if [ "`grep -m1 -c '|PORT_80|' ${TOKENFILE_NGINX}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_80\|/${PORT_80}/g" ${TOKENFILE_NGINX}
			fi
			if [ "`grep -m1 -c '|PORT_443|' ${TOKENFILE_NGINX}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_443\|/${PORT_443}/g" ${TOKENFILE_NGINX}
			fi
		fi
		if [ -e ${TOKENFILE_NGINX_USERDIR} ]; then
			if [ "`grep -m1 -c '|PORT_80|' ${TOKENFILE_NGINX_USERDIR}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_80\|/${PORT_80}/g" ${TOKENFILE_NGINX_USERDIR}
			fi
			if [ "`grep -m1 -c '|PORT_443|' ${TOKENFILE_NGINX_USERDIR}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_443\|/${PORT_443}/g" ${TOKENFILE_NGINX_USERDIR}
			fi
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ -e ${TOKENFILE_NGINX} ]; then
			if [ "`grep -m1 -c '|PORT_80|' ${TOKENFILE_NGINX}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_80\|/${PORT_80}/g" ${TOKENFILE_NGINX}
			fi

			if [ "`grep -m1 -c '|PORT_443|' ${TOKENFILE_NGINX}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_443\|/${PORT_443}/g" ${TOKENFILE_NGINX}
			fi

			if [ "`grep -m1 -c '|PORT_8080|' ${TOKENFILE_NGINX}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_8080\|/${PORT_8080}/g" ${TOKENFILE_NGINX}
			fi

			if [ "`grep -m1 -c '|PORT_8081|' ${TOKENFILE_NGINX}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_8081\|/${PORT_8081}/g" ${TOKENFILE_NGINX}
			fi
		fi
		
		if [ -e ${TOKENFILE_NGINX_USERDIR} ]; then
			if [ "`grep -m1 -c '|PORT_80|' ${TOKENFILE_NGINX_USERDIR}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_80\|/${PORT_80}/g" ${TOKENFILE_NGINX_USERDIR}
			fi

			if [ "`grep -m1 -c '|PORT_443|' ${TOKENFILE_NGINX_USERDIR}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_443\|/${PORT_443}/g" ${TOKENFILE_NGINX_USERDIR}
			fi

			if [ "`grep -m1 -c '|PORT_8080|' ${TOKENFILE_NGINX_USERDIR}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_8080\|/${PORT_8080}/g" ${TOKENFILE_NGINX_USERDIR}
			fi

			if [ "`grep -m1 -c '|PORT_8081|' ${TOKENFILE_NGINX_USERDIR}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_8081\|/${PORT_8081}/g" ${TOKENFILE_NGINX_USERDIR}
			fi
		fi

		if [ -e ${TOKENFILE_APACHE} ]; then
			if [ "`grep -m1 -c '|PORT_80|' ${TOKENFILE_APACHE}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_80\|/${PORT_8080}/g" ${TOKENFILE_APACHE}
			else
				perl -pi -e "s/:${PORT_80}\>/:${PORT_8080}\>/" ${TOKENFILE_APACHE}
			fi

			if [ "`grep -m1 -c '|PORT_443|' ${TOKENFILE_APACHE}`" -gt "0" ]; then
				perl -pi -e "s/\|PORT_443\|/${PORT_8081}/g" ${TOKENFILE_APACHE}
			else
				perl -pi -e "s/:${PORT_443}\>/:${PORT_8081}\>/" ${TOKENFILE_APACHE}
			fi

			if [ "`grep -m1 -c "^Listen ${PORT_80}$" ${HTTPD_CONF}`" -gt 0 ]; then
				perl -pi -e "s/^Listen ${PORT_80}$/Listen ${PORT_8080}/" ${HTTPD_CONF}
			else
				perl -pi -e "s/:${PORT_80}\>/:${PORT_8080}\>/" ${HTTPD_CONF}
			fi

			perl -pi -e "s/\|PORT_80\|/${PORT_8080}/g" ${HTTPD_CONF}
			perl -pi -e "s/:${PORT_80}\>/:${PORT_8080}\>/" ${HTTPD_CONF}
			perl -pi -e "s/^Listen ${PORT_80}$/Listen ${PORT_8080}/" ${HTTPD_CONF}
			
			SSLFILE=${HTTPDCONF}/extra/httpd-ssl.conf
			perl -pi -e "s/\|PORT_443\|/${PORT_8081}/g" ${SSLFILE}
			perl -pi -e "s/:${PORT_443}\>/:${PORT_8081}\>/" ${SSLFILE}
			perl -pi -e "s/^Listen ${PORT_443}$/Listen ${PORT_8081}/" ${SSLFILE}
		fi
	fi
}

doMigrateToSystemCurl() {
	find /usr/local/lib/ -name 'libcurl.*' -type f -delete
	remove_file /usr/local/share/man/man1/curl-config.1
	remove_file /usr/local/share/man/man1/curl.1
	remove_file /usr/local/bin/curl
	remove_file /usr/local/bin/curl-config
	remove_file /usr/local/lib/pkgconfig/libcurl.pc
	remove_directory /usr/local/include/curl
	remove_file /usr/local/share/aclocal/libcurl.m4
	if [ -d /usr/local/share/man/man3 ]; then
		find /usr/local/share/man/man3 -name 'curl_*' -type f -delete
		find /usr/local/share/man/man3 -name 'libcurl_*' -type f -delete
		find /usr/local/share/man/man3 -name 'CURL*' -type f -delete
	fi
	ldconfig
	hash -r
	install_rpms curl
	install_debs curl
	echo "Rebuilding PHP to make sure it does not depend on compiled version of cURL"
	doPhp
	writeLog "curl has ben switched to OS version"
	
	cd ${WORKDIR}
	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
}

####################################################

doImageMagick() {
	if [ "${IMAGICK_OPT}" != "yes" ]; then
		do_exit 1 "You cannot install ImageMagick, because you do not have imagick=yes set in php_extensions.conf file."
	fi
	ensureBuildPackages
	safeDownloadWithMove "${WORKDIR}/ImageMagick-${IMAGEMAGICK_VER}.tar.gz" "${IMAGEMAGICK_DOWNLOADURL}"
	cd ${WORKDIR}
	FILE=${WORKDIR}/ImageMagick-${IMAGEMAGICK_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ..."
	tar xzf ${FILE} --no-same-owner
	echo "Done."
	cd ImageMagick-${IMAGEMAGICK_VER}
	echo "Configuring ImageMagick-${IMAGEMAGICK_VER}..."

	"${configure_scripts_active[imagemagick]}"

	echo "Done. Making ImageMagick-${IMAGEMAGICK_VER}..."
	echo "Trying to make imagemagick..."
	if ! make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing ImageMagick-${IMAGEMAGICK_VER}..."
	make install

	echo "Done ImageMagick."
	writeLog "ImageMagick ${IMAGEMAGICK_VER} installed"

	cd ${WORKDIR}
	if [ "${PHP_IMAGICK_OPT}" = "yes" ]; then
		doIMagick
	fi
	/sbin/ldconfig
	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
}

####################################################

doRedis() {
	if [ "${REDIS_OPT}" != "yes" ]; then
		do_exit 1 "You cannot install Redis, because you do not have redis=yes set in options.conf file."
	fi
	ensureBuildPackages
	#Add redis user/group if it doesn't exist
	addUserGroup redis redis

	safeDownloadWithMove "${WORKDIR}/redis-${REDIS_VER}.tar.gz" "${REDIS_DOWNLOADURL}"

	cd ${WORKDIR}
	FILE=${WORKDIR}/redis-${REDIS_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ..."
	tar xzf ${FILE} --no-same-owner
	echo "Done."
	cd redis-${REDIS_VER}

	echo "Making redis-${REDIS_VER}..."
	echo "Trying to make redis..."
	if ! make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing redis-${REDIS_VER}..."
	make install

	echo "Done redis."
	writeLog "Redis ${REDIS_VER} installed"

	cd ${WORKDIR}
	/sbin/ldconfig

	cd ${WORKDIR}

	echo "Enabling redis in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/redis@.service ]; then
		cp -f ${CB_CUST_SYSTEMD}/redis@.service ${SYSTEMDDIR}/redis@.service
	else
		cp -f ${CB_SYSTEMD}/redis@.service ${SYSTEMDDIR}/redis@.service
	fi
	chmod 644 ${SYSTEMDDIR}/redis@.service
	systemctl daemon-reload

	if [ "${SPAMD_OPT}" = "rspamd" ]; then
		echo "Enabling redis-rspamd in systemd..."
		if [ -e ${CB_CUST_SYSTEMD}/redis-rspamd.service ]; then
			cp -f ${CB_CUST_SYSTEMD}/redis-rspamd.service ${SYSTEMDDIR}/redis-rspamd.service
		else
			cp -f ${CB_SYSTEMD}/redis-rspamd.service ${SYSTEMDDIR}/redis-rspamd.service
		fi
		chmod 644 ${SYSTEMDDIR}/redis-rspamd.service
		systemctl daemon-reload
		systemctl enable --now redis-rspamd
		if [ ! -d /etc/rspamd/local.d ]; then
			mkdir -p /etc/rspamd/local.d
			chmod 755 /etc/rspamd/local.d
		fi
		echo 'servers = "/var/lib/rspamd/.redis/redis.sock";' > /etc/rspamd/local.d/redis.conf
		systemctl reload rspamd
	fi

	setupLogrotate redis

	if command -v sysctl >/dev/null; then
		if [ `sysctl vm.overcommit_memory | cut -d= -f2 | awk '{print $1}'` -eq 0 ]; then
			if [ -d /etc/sysctl.d ]; then
				if [ -e /etc/sysctl.d/99-directadmin.conf ]; then
					if grep -m1 -q '^overcommit_memory' /etc/sysctl.d/99-directadmin.conf; then
						echo 'vm.overcommit_memory=1' >> /etc/sysctl.d/99-directadmin.conf
						sysctl -p /etc/sysctl.d/99-directadmin.conf
					fi
				else
					echo 'vm.overcommit_memory=1' > /etc/sysctl.d/99-directadmin.conf
					sysctl -p /etc/sysctl.d/99-directadmin.conf
				fi
			fi
		fi
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
}

####################################################

installXMLRPC() {
	if [ -z $1 ] || [ "$1" = "no" ] || [ ! -x /usr/local/php$1/bin/phpize ]; then
		return
	fi
	install_rpms autoconf
	install_debs autoconf
	safeDownloadWithMove "${WORKDIR}/xmlrpc-${XMLRPC_VER}.tgz" "${XMLRPC_DOWNLOADURL}"
	echo "Installing xmlrpc-${XMLRPC_VER} PHP extension for PHP $1..."

	FILE=${WORKDIR}/xmlrpc-${XMLRPC_VER}.tgz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	#make clean didn't clean everything up
	if [ -d xmlrpc-${XMLRPC_VER} ]; then
		rm -rf xmlrpc-${XMLRPC_VER}
	fi

	tar xzf ${FILE}
	cd xmlrpc-${XMLRPC_VER}

	/usr/local/php$1/bin/phpize
	./configure --with-php-config=/usr/local/php$1/bin/php-config

	echo "Trying to make xmlrpc-${XMLRPC_VER} PHP extension..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	make install

	make clean
	cd ${WORKDIR}
}

####################################################

installIMagick() {
	if [ -z $1 ] || [ "$1" = "no" ] || [ ! -x /usr/local/php$1/bin/phpize ]; then
		return
	fi
	install_rpms autoconf
	install_debs autoconf
	safeDownloadWithMove "${WORKDIR}/imagick-${IMAGICK_VER}.tgz" "${IMAGICK_DOWNLOADURL}"
	echo "Installing imagick-${IMAGICK_VER} PHP extension for PHP $1..."

	FILE=${WORKDIR}/imagick-${IMAGICK_VER}.tgz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	#make clean didn't clean everything up
	if [ -d imagick-${IMAGICK_VER} ]; then
		rm -rf imagick-${IMAGICK_VER}
	fi

	tar xzf ${FILE}
	cd imagick-${IMAGICK_VER}

	/usr/local/php$1/bin/phpize
	./configure --with-php-config=/usr/local/php$1/bin/php-config

	echo "Trying to make imagick-${IMAGICK_VER} PHP extension..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	make install
	make clean
	cd ${WORKDIR}
}

doIMagick() {
	cd ${WORKDIR}
	if [ "${IMAGICK_OPT}" = "no" ]; then
		do_exit 1 "Cannot build imagick, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	if [ ! -e /usr/local/bin/magick ]; then
		doImageMagick
	fi
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		IMAGICK_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		installIMagick ${IMAGICK_INT_SHORTRELEASE} $2
	else
		installIMagick ${PHP1_SHORTRELEASE} ${PHP1_MODE_OPT}
		installIMagick ${PHP2_SHORTRELEASE} ${PHP2_MODE_OPT}
		installIMagick ${PHP3_SHORTRELEASE} ${PHP3_MODE_OPT}
		installIMagick ${PHP4_SHORTRELEASE} ${PHP4_MODE_OPT}
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} imagick
	else
		doExtensions_build ${1} imagick
	fi
	echo "imagick ${IMAGICK_VER} PHP extension has been installed successfully."
	writeLog "imagick ${IMAGICK_VER} installed"

	cd ${WORKDIR}
}

installGeneralSrcExt() {
	if [ -z $3 ] || [ "$3" = "no" ]; then
		return
	fi
	install_rpms autoconf
	install_debs autoconf
	PHP_EXT_NAME=$1
	echo "Installing ${PHP_EXT_NAME} PHP extension for PHP $3..."

	PHP_EXT_SHORTRELEASE=`echo $3 | cut -d'.' -f1,2 | tr -d '.'`

	TMPVAR="PHP${PHP_EXT_SHORTRELEASE}_DOWNLOADURL"
	safeDownloadWithMove "${WORKDIR}/php-${3}.tar.gz" "${!TMPVAR}"

	FILE=${WORKDIR}/php-${3}.tar.gz

	if [ ! -d "php-${3}/ext/${PHP_EXT_NAME}" ]; then
		checkFile ${FILE}
		echo "Extracting ..."
		tar xzf ${FILE} --no-same-owner
		if [ ! -d "php-${3}/ext/${PHP_EXT_NAME}" ]; then
			echo "Unable to found php-${3}/ext/${PHP_EXT_NAME}, skipping..."
			return
		fi
	fi
	cd "php-${3}/ext/${PHP_EXT_NAME}"
	if [ $? -ne 0 ]; then
		do_exit 1 "Failed to change directory to: php-${3}. Exiting..."
	fi

	/usr/local/php${PHP_EXT_SHORTRELEASE}/bin/phpize
	./configure --with-php-config=/usr/local/php${PHP_EXT_SHORTRELEASE}/bin/php-config ${4}

	echo "Trying to make ${PHP_EXT_NAME} PHP extension..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	make install
	make clean
	cd ${WORKDIR}
}

installGeneralExt() {
	if [ -z $3 ] || [ "$3" = "no" ]; then
		return
	fi
	install_rpms autoconf
	install_debs autoconf
	PHP_EXT_NAME=$1
	PHP_EXT_VER=$2

	if [ "${PHP_EXT_NAME}" = "snuffleupagus" ]; then
		FILE_EXT="tar.gz"
	else
		FILE_EXT="tgz"
	fi
	if [ "${PHP_EXT_NAME}" = "snuffleupagus" ]; then
		if [ "${3}" = "53" ] || [ "${3}" = "54" ] || [ "${3}" = "55" ] || [ "${3}" = "56" ]; then
			return
		fi
	fi
	echo "Installing ${PHP_EXT_NAME}-${PHP_EXT_VER} PHP extension for PHP $3..."
	safeDownloadWithMove "${WORKDIR}/${PHP_EXT_NAME}-${PHP_EXT_VER}.${FILE_EXT}" "${WEBPATH}/php_extensions/${PHP_EXT_NAME}/${PHP_EXT_NAME}-${PHP_EXT_VER}.${FILE_EXT}"

	FILE=${WORKDIR}/${PHP_EXT_NAME}-${PHP_EXT_VER}.${FILE_EXT}
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	#make clean didn't clean everything up
	if [ -d ${PHP_EXT_NAME}-${PHP_EXT_VER} ]; then
		rm -rf ${PHP_EXT_NAME}-${PHP_EXT_VER}
	fi

	tar xzf ${FILE}
	if [ "${PHP_EXT_NAME}" = "snuffleupagus" ]; then
		cd ${PHP_EXT_NAME}-${PHP_EXT_VER}/src
	else
		cd ${PHP_EXT_NAME}-${PHP_EXT_VER}
	fi

	/usr/local/php$3/bin/phpize
	APPEND_CONFIG_FLAG=""
	if [ "${PHP_EXT_NAME}" = "redis" ]; then
		if /usr/local/php$3/bin/php$3 -i | grep -m1 'igbinary version' | tail -n1 | grep -m1 -q -o '[0-9.]*' 2>/dev/null; then
			APPEND_CONFIG_FLAG=" --enable-redis-igbinary"
		fi
	fi
	./configure --with-php-config=/usr/local/php$3/bin/php-config${APPEND_CONFIG_FLAG}

	echo "Trying to make ${PHP_EXT_NAME}-${PHP_EXT_VER} PHP extension..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	make install
	make clean
	cd ${WORKDIR}
}

command_php_psr() {
	if [ "${PHP_PHALCON_OPT}" != "yes" ]; then
		do_exit 1 "Cannot build 'psr' PHP extension, because you do not have 'phalcon=yes' set in php_extensions.conf file."
	fi

	local php_version
	for php_version in "${!options_conf_php[@]}"; do
		compile_php_psr_extension "${php_version}"
	done

	doExtensions 0 psr
	echo "psr ${PSR_VER} PHP extension has been installed successfully."
	writeLog "psr ${PSR_VER} installed"
}

php_supports_phalcon4_extension() {
	local php_vv=$1

	[ -z "${php_vv}" ] && return 1
	[ "${php_vv}" = "no" ] && return 1

	[ "${php_vv}" -lt 73 ] && return 1
	[ "${php_vv}" -gt 74 ] && return 1
	return 0
}

php_supports_phalcon5_extension() {
	local php_vv=$1

	[ -z "${php_vv}" ] && return 1
	[ "${php_vv}" = "no" ] && return 1

	[ "${php_vv}" -lt 80 ] && return 1
	[ "${php_vv}" -gt 81 ] && return 1
	return 0
}

compile_php_psr_extension() {
	local php_version=$1    # 8.1

	if [ -z "${php_version}" ] || [ "${php_version}" = "no" ]; then
		return
	fi

	if [ "${php_version//./}" -lt 73 ]; then
		echo "PHP extension psr-${PSR_VER} is not compatible with PHP ${php_version}" 2>&1
		return 1
	fi

	install_rpms gcc make autoconf
	install_debs gcc make autoconf

	echo "compiling psr-${PSR_VER} for PHP ${php_version}..."

	if ! compile_pecl_package psr "${PSR_VER}" "${php_version//./}" "${PSR_DOWNLOADURL}"; then
		echo "failed to compile psr-${PSR_VER} for PHP ${php_version}" 1>&2
		return 1
	fi
}

command_php_phalcon() {
	if [ "${PHP_PHALCON_OPT}" != "yes" ]; then
		echo "cannot build phalcon, because you do not have it set in php_extensions.conf file" 1>&2
		return 1
	fi

	declare -a php_versions=("${!options_conf_php[@]}")
	if [ "$#" -gt 0 ]; then
		if [ -z "${options_conf_php["$1"]}" ]; then
			echo "invalid or not enabled PHP version '$1'" 1>&2
			return 1
		fi
		php_versions=("$1")
	fi

	local ok=0
	local php_version
	for php_version in "${php_versions[@]}"; do
		compile_php_phalcon_extension "${php_version}" && ((ok++))
	done

	if [ "${ok}" -eq 0 ]; then
		echo "phalcon PHP extension installation has failed" 1>&2
		return 1
	fi

	restart_php "${php_versions[@]}"
	echo "phalcon PHP extension has been installed successfully."
	writeLog "phalcon ${versions_txt[phalcon]}/${versions_txt[phalcon5]} installed"
}

compile_php_phalcon_extension() {
	local php_version=$1     # 8.1

	if [ -z "${php_version}" ] || [ "${php_version}" = "no" ]; then
		return
	fi

	install_rpms gcc make autoconf
	install_debs gcc make autoconf

	local phalcon_version
	local phalcon_url
	if php_supports_phalcon5_extension "${php_version//./}"; then
		phalcon_version=${versions_txt[phalcon5]}
		phalcon_url=${PHALCON5_DOWNLOADURL}
	elif php_supports_phalcon4_extension "${php_version//./}"; then
		phalcon_version=${versions_txt[phalcon]}
		phalcon_url=${PHALCON4_DOWNLOADURL}
		compile_php_psr_extension "${php_version}" || return 1
	else
		echo "phalcon 4 and phalcon 5 is not compatible with PHP ${php_version}" 1>&2
		return 1
	fi

	echo "compiling phalcon-${phalcon_version} for PHP ${php_version}..."
	if ! compile_pecl_package phalcon "${phalcon_version}" "${php_version//./}" "${phalcon_url}"; then
		echo "failed to compile phalcon-${phalcon_version} for PHP ${php_version}" 1>&2
		return 1
	fi

	doExtensions_build "${php_version}" phalcon
}

command_php_igbinary() {
	if [ "${PHP_IGBINARY_OPT}" != "yes" ]; then
		echo "cannot build igbinary, because you do not have it set in php_extensions.conf file" 1>&2
		return 1
	fi

	declare -a php_versions=("${!options_conf_php[@]}")
	if [ "$#" -gt 0 ]; then
		if [ -z "${options_conf_php["$1"]}" ]; then
			echo "invalid or not enabled PHP version '$1'" 1>&2
			return 1
		fi
		php_versions=("$1")
	fi

	local ok=0
	local php_version
	for php_version in "${php_versions[@]}"; do
		compile_php_igbinary_extension "${php_version}" && ((ok++))
	done

	if [ "${ok}" -eq 0 ]; then
		echo "igbinary PHP extension installation has failed" 1>&2
		return 1
	fi

	restart_php "${php_versions[@]}"
	echo "igbinary PHP extension has been installed successfully."
	writeLog "igbinary ${versions_txt[igbinary]} installed"
}

compile_php_igbinary_extension() {
	local php_version=$1     # 8.1

	if [ -z "${php_version}" ] || [ "${php_version}" = "no" ]; then
		return
	fi

	if ! php_supports_igbinary_extension "${php_version//./}"; then
		echo "igbinary is not compatible with PHP ${php_version}" 1>&2
		return 1
	fi

	install_rpms gcc make autoconf
	install_debs gcc make autoconf

	echo "compiling igbinary-${IGBINARY_VER} for PHP ${php_version}..."
	if ! compile_pecl_package igbinary "${IGBINARY_VER}" "${php_version//./}" "${IGBINARY_DOWNLOADURL}"; then
		echo "failed to compile igbinary-${IGBINARY_VER} for PHP ${php_version}" 1>&2
		return 1
	fi

	doExtensions_build "${php_version}" igbinary
}

php_supports_igbinary_extension() {
	local php_vv=$1

	[ -z "${php_vv}" ] && return 1
	[ "${php_vv}" = "no" ] && return 1
	[ "${php_vv}" -lt 70 ] && return 1
	return 0
}

doPHPRedis() {
	cd ${WORKDIR}
	INSTALL_EXT_NAME=redis
	INSTALL_EXT_VER=${PHPREDIS_VER}
	if [ "${PHP_REDIS_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ${INSTALL_EXT_NAME}, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		GENERAL_EXT_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
		GENERAL_EXT_INT_VER_VAR=PHP${GENERAL_EXT_INT_SHORTRELEASE}_VER
		GENERAL_EXT_INT_VER=${!GENERAL_EXT_INT_VER_VAR}
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi

	UNSUPPORTED_VERSIONS="53 54 55 56"
	if [ "${FOR_ALL}" = "no" ]; then
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${GENERAL_EXT_INT_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${GENERAL_EXT_INT_SHORTRELEASE} $2
		fi
	else
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${PHP1_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${PHP1_SHORTRELEASE} ${PHP1_MODE_OPT}
		fi
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${PHP2_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${PHP2_SHORTRELEASE} ${PHP2_MODE_OPT}
		fi
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${PHP3_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${PHP3_SHORTRELEASE} ${PHP3_MODE_OPT}
		fi
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${PHP4_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${PHP4_SHORTRELEASE} ${PHP4_MODE_OPT}
		fi
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} ${INSTALL_EXT_NAME}
	else
		doExtensions_build ${GENERAL_EXT_INT_SHORTRELEASE} ${INSTALL_EXT_NAME}
	fi
	echo "${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} PHP extension has been installed successfully."
	writeLog "${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} installed"

	cd ${WORKDIR}
}

doSnuffleupagus() {
	cd ${WORKDIR}
	INSTALL_EXT_NAME=snuffleupagus
	INSTALL_EXT_VER=${SNUFFLEUPAGUS_VER}
	if [ "${PHP_SNUFFLEUPAGUS_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ${INSTALL_EXT_NAME}, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		GENERAL_EXT_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
		GENERAL_EXT_INT_VER_VAR=PHP${GENERAL_EXT_INT_SHORTRELEASE}_VER
		GENERAL_EXT_INT_VER=${!GENERAL_EXT_INT_VER_VAR}
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi

	UNSUPPORTED_VERSIONS="53 54 55 56"
	if [ "${FOR_ALL}" = "no" ]; then
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${GENERAL_EXT_INT_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${GENERAL_EXT_INT_SHORTRELEASE} $2
		fi
	else
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${PHP1_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${PHP1_SHORTRELEASE} ${PHP1_MODE_OPT}
		fi
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${PHP2_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${PHP2_SHORTRELEASE} ${PHP2_MODE_OPT}
		fi
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${PHP3_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${PHP3_SHORTRELEASE} ${PHP3_MODE_OPT}
		fi
		if ! echo "${UNSUPPORTED_VERSIONS}" | grep -m1 -q "${PHP4_SHORTRELEASE}"; then
			installGeneralExt ${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} ${PHP4_SHORTRELEASE} ${PHP4_MODE_OPT}
		fi
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} ${INSTALL_EXT_NAME}
	else
		doExtensions_build ${GENERAL_EXT_INT_SHORTRELEASE} ${INSTALL_EXT_NAME}
	fi
	echo "${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} PHP extension has been installed successfully."
	writeLog "${INSTALL_EXT_NAME} ${INSTALL_EXT_VER} installed"

	cd ${WORKDIR}
}

doImap() {
	cd ${WORKDIR}
	safeDownloadWithMove "${WORKDIR}/imap-${IMAP_VER}.tar.gz" "${IMAP_DOWNLOADURL}"
	if [ ! -s imap-${IMAP_VER}.tar.gz ]; then
		echo "Cannot find imap-${IMAP_VER}.tar.gz for extraction";
		exit 1
	fi
	tar xvzf imap-${IMAP_VER}.tar.gz
	cd imap-${IMAP_VER}

	install_rpms pam-devel
	install_debs libpam0g-dev

	patch -p1 < ${WORKDIR}/patches/1006_openssl1.1_autoverify.patch

	make lr5 EXTRACFLAGS=-fPIC
	mkdir -p /usr/local/uw-imap/lib
	mkdir -p /usr/local/uw-imap/include
	cp -f c-client/*.c /usr/local/uw-imap/lib/
	cp -f c-client/*.h /usr/local/uw-imap/include/
	cp -f c-client/c-client.a /usr/local/uw-imap/lib/libc-client.a
	echo "IMAP ${IMAP_VER} has been installed successfully."
	writeLog "IMAP ${IMAP_VER} installed"
	cd ${WORKDIR}
}

doPHPGmp() {
	cd ${WORKDIR}

	INSTALL_EXT_NAME=gmp
	if [ "${PHP_GMP_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ${INSTALL_EXT_NAME}, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	install_rpms gmp-devel
	install_debs libgmp-dev
	if [ -e /usr/include/x86_64-linux-gnu/gmp.h ] && [ ! -e /usr/include/gmp.h ]; then
		ln -s /usr/include/x86_64-linux-gnu/gmp.h /usr/include/gmp.h
	elif [ -e /usr/include/aarch64-linux-gnu/gmp.h ] && [ ! -e /usr/include/gmp.h ]; then
		ln -s /usr/include/aarch64-linux-gnu/gmp.h /usr/include/gmp.h
	fi
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		GENERAL_EXT_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
		GENERAL_EXT_INT_VER_VAR=PHP${GENERAL_EXT_INT_SHORTRELEASE}_VER
		GENERAL_EXT_INT_VER=${!GENERAL_EXT_INT_VER_VAR}
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi
	EXTRA_CONFIGURATION_FLAGS=""
	if [ "${FOR_ALL}" = "no" ]; then
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${GENERAL_EXT_INT_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	else
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP1_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP2_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP3_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP4_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} ${INSTALL_EXT_NAME}
	else
		doExtensions_build ${GENERAL_EXT_INT_SHORTRELEASE} ${INSTALL_EXT_NAME}
	fi
	echo "${INSTALL_EXT_NAME} PHP extension has been installed successfully."
	writeLog "${INSTALL_EXT_NAME} installed"

	cd ${WORKDIR}
}

doPHPReadline() {
	cd ${WORKDIR}

	INSTALL_EXT_NAME=readline
	if [ "${PHP_READLINE_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ${INSTALL_EXT_NAME}, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	install_debs libreadline-dev libedit-dev
	install_rpms readline-devel libedit-devel
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		GENERAL_EXT_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
		GENERAL_EXT_INT_VER_VAR=PHP${GENERAL_EXT_INT_SHORTRELEASE}_VER
		GENERAL_EXT_INT_VER=${!GENERAL_EXT_INT_VER_VAR}
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi
	EXTRA_CONFIGURATION_FLAGS=""
	if [ "${FOR_ALL}" = "no" ]; then
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${GENERAL_EXT_INT_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	else
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP1_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP2_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP3_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP4_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} ${INSTALL_EXT_NAME}
	else
		doExtensions_build ${GENERAL_EXT_INT_SHORTRELEASE} ${INSTALL_EXT_NAME}
	fi
	echo "${INSTALL_EXT_NAME} PHP extension has been installed successfully."
	writeLog "${INSTALL_EXT_NAME} installed"

	cd ${WORKDIR}
}

doPHPLDAP() {
	cd ${WORKDIR}

	INSTALL_EXT_NAME=ldap   
	if [ "${PHP_LDAP_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ${INSTALL_EXT_NAME}, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	install_rpms openldap-devel
	install_debs libldap2-dev
	if [ -e /usr/include/x86_64-linux-gnu/ldap.h ] && [ ! -e /usr/include/ldap.h ]; then
		ln -s /usr/include/x86_64-linux-gnu/ldap.h /usr/include/ldap.h
	fi
	if [ -e /usr/include/aarch64-linux-gnu/gmp.h ] && [ ! -e /usr/include/ldap.h ]; then
		ln -s /usr/include/aarch64-linux-gnu/gmp.h /usr/include/ldap.h
	fi
	if [ -e /usr/lib64/libldap.so ] && [ ! -e /usr/lib/libldap.so ]; then
		ln -s /usr/lib64/libldap.so /usr/lib/libldap.so
	fi
	if [ -e /usr/lib64/libldap_r.so ] && [ ! -e /usr/lib/libldap_r.so ]; then
		ln -s /usr/lib64/libldap_r.so /usr/lib/libldap_r.so
	fi
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		GENERAL_EXT_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
		GENERAL_EXT_INT_VER_VAR=PHP${GENERAL_EXT_INT_SHORTRELEASE}_VER
		GENERAL_EXT_INT_VER=${!GENERAL_EXT_INT_VER_VAR}
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi
	EXTRA_CONFIGURATION_FLAGS=""
	if [ "${FOR_ALL}" = "no" ]; then
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${GENERAL_EXT_INT_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	else
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP1_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP2_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP3_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP4_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} ${INSTALL_EXT_NAME}
	else
		doExtensions_build ${GENERAL_EXT_INT_SHORTRELEASE} ${INSTALL_EXT_NAME}
	fi
	echo "${INSTALL_EXT_NAME} PHP extension has been installed successfully."
	writeLog "${INSTALL_EXT_NAME} installed"

	cd ${WORKDIR}
}

doPHPBz2() {
	cd ${WORKDIR}
	install_rpms bzip2-devel
	install_debs libbz2-dev
	INSTALL_EXT_NAME=bz2
	if [ "${PHP_BZ2_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ${INSTALL_EXT_NAME}, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		GENERAL_EXT_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
		GENERAL_EXT_INT_VER_VAR=PHP${GENERAL_EXT_INT_SHORTRELEASE}_VER
		GENERAL_EXT_INT_VER=${!GENERAL_EXT_INT_VER_VAR}
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi
	if [ "${FOR_ALL}" = "no" ]; then
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${GENERAL_EXT_INT_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	else
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP1_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP2_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP3_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP4_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} ${INSTALL_EXT_NAME}
	else
		doExtensions_build ${GENERAL_EXT_INT_SHORTRELEASE} ${INSTALL_EXT_NAME}
	fi
	echo "${INSTALL_EXT_NAME} PHP extension has been installed successfully."
	writeLog "${INSTALL_EXT_NAME} installed"

	cd ${WORKDIR}
}

doPHPXmlrpc() {
	cd ${WORKDIR}
	INSTALL_EXT_NAME=xmlrpc
	if [ "${PHP_XMLRPC_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ${INSTALL_EXT_NAME}, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		GENERAL_EXT_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
		GENERAL_EXT_INT_VER_VAR=PHP${GENERAL_EXT_INT_SHORTRELEASE}_VER
		GENERAL_EXT_INT_VER=${!GENERAL_EXT_INT_VER_VAR}
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi
	EXTRA_CONFIGURATION_FLAGS=""
	SUPPORTED_VERSIONS="53 54 55 56 70 71 72 73 74"
	if [ "${FOR_ALL}" = "no" ]; then
		if echo "${SUPPORTED_VERSIONS}" | grep -m1 -q "${GENERAL_EXT_INT_SHORTRELEASE}"; then
			installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${GENERAL_EXT_INT_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		else
			installXMLRPC ${GENERAL_EXT_INT_SHORTRELEASE} $2
		fi
	else
		if echo "${SUPPORTED_VERSIONS}" | grep -m1 -q "${PHP1_SHORTRELEASE}"; then
			installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP1_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		else
			installXMLRPC ${PHP1_SHORTRELEASE} ${PHP1_MODE_OPT}
		fi
		if echo "${SUPPORTED_VERSIONS}" | grep -m1 -q "${PHP2_SHORTRELEASE}"; then
			installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP2_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		else
			installXMLRPC ${PHP2_SHORTRELEASE} ${PHP1_MODE_OPT}
		fi
		if echo "${SUPPORTED_VERSIONS}" | grep -m1 -q "${PHP3_SHORTRELEASE}"; then
			installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP3_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		else
			installXMLRPC ${PHP3_SHORTRELEASE} ${PHP1_MODE_OPT}
		fi
		if echo "${SUPPORTED_VERSIONS}" | grep -m1 -q "${PHP4_SHORTRELEASE}"; then
			installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP4_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		else
			installXMLRPC ${PHP4_SHORTRELEASE} ${PHP1_MODE_OPT}
		fi
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} ${INSTALL_EXT_NAME}
	else
		doExtensions_build ${GENERAL_EXT_INT_SHORTRELEASE} ${INSTALL_EXT_NAME}
	fi
	echo "${INSTALL_EXT_NAME} PHP extension has been installed successfully."
	writeLog "${INSTALL_EXT_NAME} installed"

	cd ${WORKDIR}
}

doPHPImap() {
	cd ${WORKDIR}
	if [ ! -s /usr/local/uw-imap/lib/libc-client.a ]; then
		doImap
	fi
	INSTALL_EXT_NAME=imap
	if [ "${PHP_IMAP_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ${INSTALL_EXT_NAME}, because you do not have it set in php_extensions.conf file."
	fi
	ensureBuildPackages
	FOR_ALL="no"
	if [ -z $1 ] || [ $1 = "d" ] || [ -z $2 ]; then
		FOR_ALL="yes"
	fi

	if [ "${FOR_ALL}" = "no" ]; then
		GENERAL_EXT_INT_SHORTRELEASE="`echo $1 | tr -d '.'`"
		GENERAL_EXT_INT_VER_VAR=PHP${GENERAL_EXT_INT_SHORTRELEASE}_VER
		GENERAL_EXT_INT_VER=${!GENERAL_EXT_INT_VER_VAR}
	fi

	SKIP_RESTART=1
	if [ "$3" != "1" ]; then
		SKIP_RESTART=0
	fi
	EXTRA_CONFIGURATION_FLAGS="--with-imap=/usr/local/uw-imap --with-imap-ssl"
	if [ "${FOR_ALL}" = "no" ]; then
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${GENERAL_EXT_INT_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	else
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP1_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP2_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP3_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
		installGeneralSrcExt ${INSTALL_EXT_NAME} "" ${PHP4_RELEASE_VER} "${EXTRA_CONFIGURATION_FLAGS}"
	fi

	if [ "${FOR_ALL}" = "yes" ]; then
		doExtensions ${SKIP_RESTART} ${INSTALL_EXT_NAME}
	else
		doExtensions_build ${GENERAL_EXT_INT_SHORTRELEASE} ${INSTALL_EXT_NAME}
	fi
	echo "${INSTALL_EXT_NAME} PHP extension has been installed successfully."
	writeLog "${INSTALL_EXT_NAME} installed"

	cd ${WORKDIR}
}

doExtensionsSetup() {
	ensureBuildPackages
	install_rpms autoconf
	install_debs autoconf
	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		#Skip executing CL commands like "cagefsctl --force update" on every component update
		EXEC_CL_COMMANDS_ONCE=true
	fi

	[ "${PHP_IMAP_OPT}"          = "yes" ] && doPHPImap
	[ "${PHP_BZ2_OPT}"           = "yes" ] && doPHPBz2
	[ "${PHP_XMLRPC_OPT}"        = "yes" ] && doPHPXmlrpc
	[ "${PHP_GMP_OPT}"           = "yes" ] && doPHPGmp
	[ "${PHP_LDAP_OPT}"          = "yes" ] && doPHPLDAP
	[ "${PHP_PHALCON_OPT}"       = "yes" ] && command_php_phalcon
	[ "${PHP_IGBINARY_OPT}"      = "yes" ] && command_php_igbinary
	[ "${PHP_IMAGICK_OPT}"       = "yes" ] && doIMagick
	[ "${PHP_IONCUBE_OPT}"       = "yes" ] && doIoncube
	[ "${PHP_SNUFFLEUPAGUS_OPT}" = "yes" ] && doSnuffleupagus
	[ "${PHP_REDIS_OPT}"         = "yes" ] && doPHPRedis
	[ "${PHP_OPCACHE_OPT}"       = "yes" ] && doOpcache
	[ "${PHP_ZEND_OPT}"          = "yes" ] && doZend
	[ "${PHP_SUHOSIN_OPT}"       = "yes" ] && doSuhosin
	[ "${PHP_READLINE_OPT}"      = "yes" ] && doPHPReadline
	[ "${PHP_HTSCANNER_OPT}"     = "yes" ] && php_htscanner2

	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		cagefsctl_update
	fi
}

####################################################

doComposer() {
	download_with_cache "${CB_CACHE_DIR}/composer.phar.${COMPOSER_VER}" "https://getcomposer.org/download/${COMPOSER_VER}/composer.phar" || return 1
	install_file "${CB_CACHE_DIR}/composer.phar.${COMPOSER_VER}"  /usr/local/bin/composer 755 root:root || return 1

	if [ -d /etc/cagefs/conf.d ] && [ ! -s /etc/cagefs/conf.d/composer.cfg ]; then
		echo '[composer]' > /etc/cagefs/conf.d/composer.cfg 
		echo 'comment=Composer' >> /etc/cagefs/conf.d/composer.cfg 
		echo 'paths=/usr/local/bin/composer' >> /etc/cagefs/conf.d/composer.cfg 
	fi

	echo "Composer ${COMPOSER_VER} Installed."
	writeLog "composer ${COMPOSER_VER} installed"

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
}

####################################################

doMajordomo() {
	ensureBuildPackages
	cd ${WORKDIR}

	SOURCEPATH="${WORKDIR}/majordomo-1.94.5"

	mkdir -p "${SOURCEPATH}"
	safeDownloadWithMove "${WORKDIR}/majordomo-1.94.5-patched.tar.gz" "${WEBPATH_SERVICES}/all/majordomo-1.94.5-patched.tar.gz"

	tar xzf majordomo-1.94.5-patched.tar.gz
	if [ ! -e ${SOURCEPATH}/Makefile ]; then
		do_exit 1 "The source path for majordomo does not exist."
	fi

	mkdir -p /etc/virtual/majordomo

	MDGID=`id -g daemon`

	if distro_is_debian; then
		/usr/sbin/groupadd nobody 2>/dev/null
		/usr/sbin/useradd -d /etc/virtual/majordomo -g $MDGID -s /bin/false majordomo 2> /dev/null
	else
		/usr/sbin/useradd -d /etc/virtual/majordomo -g $MDGID majordomo -s /bin/false -n -r 2> /dev/null
	fi

	addToAccess majordomo
	addToAccess nobody
	MDUID=`id -u majordomo`

	perl -pi -e "s/PERL = .*/PERL = \/usr\/bin\/perl/" ${SOURCEPATH}/Makefile
	perl -pi -e "s/W_HOME = .*/W_HOME = \/etc\/virtual\/majordomo/" ${SOURCEPATH}/Makefile

	#Perl and Bash weren't getting along. MDUID wasn't showing up so I did it this way.
	perl -pi -e "s/W_USER = .*/W_USER = ${MDUID}/" ${SOURCEPATH}/Makefile
	perl -pi -e "s/W_GROUP = .*/W_GROUP = ${MDGID}/" ${SOURCEPATH}/Makefile
	perl -pi -e "s/TMPDIR = .*/TMPDIR = \/tmp/" ${SOURCEPATH}/Makefile

	#fix REALLY-TO value in digests file
	perl -pi -e "s/\$ARGV\[0\];/\$ARGV\[0\].\${whereami};/" ${SOURCEPATH}/digest
	perl -pi -e "s#/usr/test/majordomo#/etc/virtual/majordomo#" ${SOURCEPATH}/sample.cf

	cd "${SOURCEPATH}"

	make wrapper
	make install
	make install-wrapper

	perl -pi -e 's#/usr/test/majordomo#/etc/virtual/majordomo#' /etc/virtual/majordomo/majordomo.cf

	cd /etc/virtual/majordomo
	patch -fp0 < "${WORKDIR}/patches/majordomo.patch"

	#just to put up back where we were.. likely not needed.
	cd ${WORKDIR}
	rm -f "${WORKDIR}/majordomo-1.94.5-patched.tar.gz"
	rm -rf "${SOURCEPATH}"

	chmod 750 /etc/virtual/majordomo
}

####################################################

doSysbk() {
	echo "Installing sysbk..."
	cd ${WORKDIR}

	safeDownloadWithMove "${WORKDIR}/sysbk.tar.gz" "${WEBPATH_SERVICES}/sysbk.tar.gz"

	tar xzf sysbk.tar.gz -C /usr/local

	KEY=/root/.ssh/id_dsa
	if [ ! -e $KEY ]; then
		/usr/bin/ssh-keygen -t rsa -b 2048 -N '' -q -f $KEY
	fi

	cd ${WORKDIR}
	rm -f "${WORKDIR}/sysbk.tar.gz"
}

####################################################

csf_conf_ensure_has_port() {
	local proto=$1  # UDP_IN
	local port=$2   # 143

	if ! grep -q "^${proto} = .*[,\"]${port}[,\"]" /etc/csf/csf.conf; then
		sed -i "s|^${proto} = \"|${proto} = \"${port},|g" /etc/csf/csf.conf
		return 1
	fi
}

csf_conf_ensure_flag() {
	local flag=$1   # RESTRICT_SYSLOG
	local val=$2    # 3

	if ! grep -q "^${flag} = \"${val}\"" /etc/csf/csf.conf; then
		sed -i "s|^${flag} = \"[^\"]*\"|${flag} = \"${val}\"|g" /etc/csf/csf.conf
		return 1
	fi
}

update_csf_conf() {
	if [ "${CSF_OPT}" != "yes" ]; then
		return
	fi

	if [ ! -f /etc/csf/csf.conf ] || ! command -v csf > /dev/null; then
		return 1
	fi

	local ipset_flag=1
	if command -v systemd-detect-virt > /dev/null && systemd-detect-virt | grep -q -E 'lxc|openvz'; then
		ipset_flag=0
	fi

	local needs_restart=''
	csf_conf_ensure_flag 'LF_IPSET' "${ipset_flag}" || needs_restart=yes
	# Block SMTP by default
	csf_conf_ensure_flag 'SMTP_BLOCK'      1 || needs_restart=yes
	csf_conf_ensure_flag 'RESTRICT_SYSLOG' 3 || needs_restart=yes
	# Disable testing mode in CSF
	csf_conf_ensure_flag 'TESTING'         0 || needs_restart=yes

	# Add IMAP outbound ports for imapsync
	csf_conf_ensure_has_port 'TCP_OUT'  '143'         || needs_restart=yes
	csf_conf_ensure_has_port 'TCP6_OUT' '143'         || needs_restart=yes
	# Enable QUIC ports
	csf_conf_ensure_has_port 'UDP_IN'   '443'         || needs_restart=yes
	csf_conf_ensure_has_port 'UDP6_IN'  '443'         || needs_restart=yes
	csf_conf_ensure_has_port 'UDP_OUT'  '443'         || needs_restart=yes
	csf_conf_ensure_has_port 'UDP6_OUT' '443'         || needs_restart=yes
	# Enable rspamd
	csf_conf_ensure_has_port 'UDP_OUT'  '11335'       || needs_restart=yes
	csf_conf_ensure_has_port 'UDP6_OUT' '11335'       || needs_restart=yes
	# Add FTP passive port range
	csf_conf_ensure_has_port 'TCP_IN'   '35000:35999' || needs_restart=yes
	csf_conf_ensure_has_port 'TCP6_IN'  '35000:35999' || needs_restart=yes

	#Allow all TCP/UDP outbound connections from root
	if ! grep -q 'out|u=0' /etc/csf/csf.allow; then
		needs_restart=yes
		csf -a "tcp|out|u=0" "Added by DirectAdmin"
		csf -a "udp|out|u=0" "Added by DirectAdmin"
	fi

	if [ -z "${needs_restart}" ]; then
		echo "Restarting CSF..."
		csf -r > /dev/null
	fi
}

command_csf_conf() {
	if [ "${CSF_OPT}" != "yes" ]; then
		echo "CSF is not enabled in the 'options.conf' file" 1>&2
		return 1
	fi

	if ! update_csf_conf; then
		echo "Failed to update CSF configuration" 1>&2
		return 1
	else
		echo "CSF configuration has beed updated"
	fi
}

command_csf() {
	if [ "${CSF_OPT}" != "yes" ]; then
		echo "CSF is not enabled in the 'options.conf' file" 1>&2
		return 1
	fi

	install_rpms gcc perl-libwww-perl iptables ipset
	install_debs gcc libwww-perl      iptables ipset

	echo "Installing CSF..."
	(
		local tmp_dir
		if ! tmp_dir=$(mktemp --directory --tmpdir="${CB_TMP_DIR}" --suffix=".csf"); then
			echo "${FUNCNAME[0]}: failed to create temp dir for extracting '${cached_file}'" 1>&2
			return 1
		fi
		trap 'rm -rf "${tar_file}" "${tmp_dir}"' EXIT

		# We do not cache CSF tarballs because they are NOT immutable
		local tar_file="${CB_TMP_DIR}/csf.tgz"
		safe_download "${tar_file}" "https://download.configserver.com/csf.tgz" || return 1

		if ! tar xzf "${tar_file}" --strip-components=1 -C "${tmp_dir}"; then
			echo "${FUNCNAME[0]}: failed to extract '${cached_file}' into '${tmp_dir}'" 1>&2
			return 1
		fi

		# Catch any perl errors
		if ! "${tmp_dir}/csftest.pl" | tail -n 1 | grep -q 'RESULT: csf should function on this server'; then
			echo "${FUNCNAME[0]}: preliminary test failed, CSF is missing some modules" 1>&2
			return 1
		fi
		cd "${tmp_dir}" && ./install.sh > /dev/null
	) || return 1

	if [ ! -f /etc/csf/csf.conf ]; then
		echo "${FUNCNAME[0]}: post install check failed, missing CSF config file '/etc/csf/csf.conf'" 1>&2
		return 1
	fi
	if ! command -v csf > /dev/null; then
		echo "${FUNCNAME[0]}: post install checks failed, csf command is not available" 1>&2
		return 1
	fi

	#disable BFM notices if CSF is installed.
	if ! grep -q '^hide_brute_force_notifications=' "${DACONF_FILE}"; then
		${DA_BIN} config-set hide_brute_force_notifications 1
	fi

	if ! update_csf_conf; then
		echo "Failed to update CSF configuration" 1>&2
		return 1
	fi
	echo "CSF installation has finished."
}

####################################################

doNamedConf() {
	if [ -e /etc/sysconfig/named ]; then
		/usr/bin/perl -pi -e 's/^ROOTDIR=.*/ROOTDIR=/' /etc/sysconfig/named
	fi

	SERVICE_NAME=named
	if [ -s ${DACONF_FILE} ] && [ -x ${DA_BIN} ]; then
		NAMED_CONF=`${DA_BIN} c | grep ^namedconfig= | cut -d= -f2`
		NAMED_OVERRIDE=`${DA_BIN} c | grep ^named_service_override= | cut -d= -f2`
		if [ "${NAMED_OVERRIDE}" != "" ]; then
			SERVICE_NAME=${NAMED_OVERRIDE}
		fi
	fi

	if [ ! -s $NAMED_CONF ]; then
		echo "Cannot find $NAMED_CONF to check";
		return
	fi

	NAMED_OPTIONS_CONF=$NAMED_CONF
	HAVE_OPTIONS_AREA=`grep -c '^options {' ${NAMED_OPTIONS_CONF}`

	for i in `grep -E '^[[:space:]]*include ' ${NAMED_CONF} | cut -d\" -f2`; do
	{
		if [ "$i" = "" ] || [ ! -s "$i" ]; then
			continue;
		fi
		
		if grep -m1 -q allow-transfer ${i}; then
			#echo "Skipping allow-transfer chcek on ${i}. allow-transfer already present.";
			return	
		fi	

		if [ "${HAVE_OPTIONS_AREA}" -eq 0 ]; then
			HAVE_OPTIONS_AREA=`grep -c '^options {' $i`
			if [ "${HAVE_OPTIONS_AREA}" -eq 0 ]; then
				continue;
			fi
			NAMED_OPTIONS_CONF=$i
		fi
	};
	done;

	if [ "${HAVE_OPTIONS_AREA}" -eq 0 ]; then
		echo "Could not find options section in the $NAMED_CONF or any of it's include files";
		return
	fi

	if ! grep -m1 -q allow-transfer ${NAMED_OPTIONS_CONF}; then
		perl -pi -e 's|options \{|options \{\n\tallow-transfer \{ none; \};|g' ${NAMED_OPTIONS_CONF}
		echo "Added 'allow-transfer { none; };' to ${NAMED_OPTIONS_CONF}"
		echo "action=${SERVICE_NAME}&value=reload" >> /usr/local/directadmin/data/task.queue
	fi
	if grep -m1 -q 'listen-on[[:space:]]*port[[:space:]]*53[[:space:]]*{[[:space:]]*127.0.0.1;[[:space:]]*};' ${NAMED_OPTIONS_CONF}; then
		perl -pi -e 's|listen-on[[:space:]]*port[[:space:]]*53[[:space:]]*{[[:space:]]*127.0.0.1;[[:space:]]*};|listen-on port 53 { any; };|g' ${NAMED_OPTIONS_CONF}
		echo "action=${SERVICE_NAME}&value=reload" >> /usr/local/directadmin/data/task.queue
	fi
	if grep -m1 -q 'recursion[[:space:]]*yes;' ${NAMED_OPTIONS_CONF}; then
		perl -pi -e 's|recursion[[:space:]]*yes;|recursion no;|g' ${NAMED_OPTIONS_CONF}
		echo "action=${SERVICE_NAME}&value=reload" >> /usr/local/directadmin/data/task.queue
	fi
	if grep -m1 -q 'listen-on-v6[[:space:]]*port[[:space:]]*53[[:space:]]*{[[:space:]]*::1;[[:space:]]*};' ${NAMED_OPTIONS_CONF}; then
		perl -pi -e 's|listen-on-v6[[:space:]]*port[[:space:]]*53[[:space:]]*{[[:space:]]*::1;[[:space:]]*};|listen-on-v6 port 53 { any; };|g' ${NAMED_OPTIONS_CONF}
		echo "action=${SERVICE_NAME}&value=reload" >> /usr/local/directadmin/data/task.queue
	fi
	if grep -m1 -q 'allow-query[[:space:]]*{[[:space:]]*localhost;[[:space:]]*};' ${NAMED_OPTIONS_CONF}; then
		perl -pi -e 's|allow-query[[:space:]]*{[[:space:]]*localhost;[[:space:]]*};|allow-query     { any; };|g' ${NAMED_OPTIONS_CONF}
		echo "action=${SERVICE_NAME}&value=reload" >> /usr/local/directadmin/data/task.queue
	fi
}

command_bind() {
	reinstall_debs bind9
	reinstall_rpms bind

	local service_name=named
	local service_override=""
	if [ -f /lib/systemd/system/bind9.service ]; then
		service_name=bind9
		service_override=bind9
	fi

	if [ "$(${DA_BIN} config-get named_service_override)" != "${service_override}" ]; then
		${DA_BIN} config-set named_service_override "${service_override}"
	fi

	# Delete all local service files we always the ones provided by the
	# system packages
	if [ -f /etc/systemd/system/named.service ] && [ ! -L /etc/systemd/system/named.service ]; then
		rm -f /etc/systemd/system/named.service
	fi
	if [ -f /etc/systemd/system/bind9.service ] && [ ! -L /etc/systemd/system/bind9.service ]; then
		rm -f /etc/systemd/system/bind9.service
	fi

	doNamedConf
	systemctl daemon-reload
	# Ensure symlinks points to system service files, not manual ones we
	# might have just removed.
	systemctl reenable "${service_name}.service"
	systemctl restart "${service_name}.service"
	set_service named ON
}

####################################################

doWP() {
	cd ${WORKDIR}
	safeDownloadWithMove "${WORKDIR}/wp-cli.${WP_VER}" "${WP_DOWNLOADURL}"
	if [ -s ${WORKDIR}/wp-cli.${WP_VER} ]; then
		mv -f ${WORKDIR}/wp-cli.${WP_VER} /usr/local/bin/wp
		chmod 755 /usr/local/bin/wp
	else
		rm -f ${WORKDIR}/wp-cli.${WP_VER}
	fi

	if [ -d /etc/cagefs/conf.d ] && [ ! -s /etc/cagefs/conf.d/wp.cfg ]; then
		echo '[wp-cli]' > /etc/cagefs/conf.d/wp.cfg 
		echo 'comment=wp-cli' >> /etc/cagefs/conf.d/wp.cfg 
		echo 'paths=/usr/local/bin/wp' >> /etc/cagefs/conf.d/wp.cfg 
	fi

	echo "WP-CLI ${WP_VER} Installed."
	writeLog "WP_CLI ${WP_VER} installed"

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
}

####################################################

doImapsync() {
	install_rpms perl-IO-Tee perl-Mail-IMAPClient perl-Sys-MemInfo perl-Readonly perl-Encode-IMAPUTF7 perl-File-Copy-Recursive perl-Unicode-String perl-Regexp-Common perl-File-Tail perl-IO-Socket-INET6 perl-File-Copy-Recursive perl-App-cpanminus perl-Dist-CheckConflicts perl-HTML-Parser perl-libwww-perl perl-Module-Implementation perl-Module-ScanDeps perl-Package-Stash perl-Package-Stash-XS perl-Regexp-Common perl-Sys-MemInfo perl-Test-Fatal perl-Test-Mock-Guard perl-Test-Requires perl-Test-Deep perl-File-Tail perl-Test-NoWarnings perl-Test-Simple perl-Test-Warn perl-Sub-Uplevel
	install_debs libauthen-ntlm-perl libcgi-pm-perl libcrypt-openssl-rsa-perl libdata-uniqid-perl libencode-imaputf7-perl libfile-copy-recursive-perl libfile-tail-perl libio-socket-inet6-perl libio-socket-ssl-perl libio-tee-perl libhtml-parser-perl libjson-webtoken-perl libmail-imapclient-perl libparse-recdescent-perl libmodule-scandeps-perl libreadonly-perl libregexp-common-perl libsys-meminfo-perl libterm-readkey-perl libtest-mockobject-perl libtest-pod-perl libunicode-string-perl liburi-perl libwww-perl libtest-nowarnings-perl libtest-deep-perl libtest-warn-perl libtest-requires-perl libtest-modern-perl libtest-mock-guard-perl libpar-packer-perl libdist-checkconflicts-perl cpanminus

	if rhel_version_is 7; then
		install_rpms perl-Digest-HMAC perl-TermReadKey
		cpanm Encode::IMAPUTF7
	fi

	safeDownloadWithMove "${WORKDIR}/imapsync-${IMAPSYNC_VER}.tar.gz" "${IMAPSYNC_DOWNLOADURL}"

	cd ${WORKDIR}
	FILE=${WORKDIR}/imapsync-${IMAPSYNC_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ..."
	tar xzf ${FILE} --no-same-owner
	echo "Done."
	cd imapsync-imapsync-${IMAPSYNC_VER}
	echo "Configuring imapsync-${IMAPSYNC_VER}..."

	chmod +x imapsync

	echo "Installing imapsync-${IMAPSYNC_VER}..."
	cp -p imapsync /usr/local/bin/imapsync
	if [ -d /etc/cagefs/conf.d ] && [ ! -s /etc/cagefs/conf.d/imapsync.cfg ]; then
		echo '[imapsync]' > /etc/cagefs/conf.d/imapsync.cfg 
		echo 'comment=imapsync' >> /etc/cagefs/conf.d/imapsync.cfg 
		echo 'paths=/usr/local/bin/imapsync' >> /etc/cagefs/conf.d/imapsync.cfg 
	fi

	update_csf_conf

	echo "imapsync ${IMAPSYNC_VER} installed"
	writeLog "imapsync ${IMAPSYNC_VER} installed"

	cd ${WORKDIR}

	/sbin/ldconfig
	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
}

####################################################

doLego() {
	cd ${WORKDIR}
	safeDownloadWithMove "${WORKDIR}/${LEGO_FILENAME}" "${LEGO_DOWNLOADURL}"

	tar xzf ${LEGO_FILENAME} -C /usr/local/bin/ --no-same-owner 'lego'

	chmod 700 /usr/local/bin/lego

	DNSPROVIDERS_JSON=/usr/local/directadmin/data/admin/dnsproviders.json
	DNSPROVIDERS_VER=${versions_txt["dnsproviders"]}
	safeDownloadWithMove "${WORKDIR}/dnsproviders.json" "${WEBPATH}/lego/dnsproviders-${DNSPROVIDERS_VER}.json"
	if [ -d /usr/local/directadmin/data/admin ]; then
		mv -f dnsproviders.json ${DNSPROVIDERS_JSON}
		chmod 600 ${DNSPROVIDERS_JSON}
		chown diradmin:diradmin ${DNSPROVIDERS_JSON}
	fi

	echo "Lego ${LEGO_VER} Installed."
	writeLog "Lego ${LEGO_VER} installed"
}

####################################################

doWebalizer() {
	if [ "${WEBALIZER_OPT}" != "yes" ]; then
		setVal webalizer 0 ${DACONF_FILE}
		do_exit 1 "You cannot install webalizer, because you do not have it set in options.conf file."
	fi
	ensureBuildPackages
	install_rpms gd-devel
	install_debs libgd-dev

	PREFIX=/usr
	LIBPATH=/usr/lib
	INCPATH=/usr/include

	if [ -e ${PREFIX}/bin/webalizer ]; then
		echo "The webalizer binary exists, aborting.  Delete ${PREFIX}/bin/webalizer if you wish to compile."
		return
	fi

	cd ${WORKDIR}
	safeDownloadWithMove "${WORKDIR}/webalizer-${WEBALIZER_VER}-src.tgz" "${WEBALIZER_DOWNLOADURL}"
	tar xzf webalizer-${WEBALIZER_VER}-src.tgz --no-same-owner
	cd webalizer-${WEBALIZER_VER}

	export LD_LIBRARY_PATH=${LIBPATH}
	./configure --prefix=${PREFIX} --with-png=${LIBPATH} --with-gdlib=${LIBPATH} --with-gd=${INCPATH} --enable-dns --with-dblib --with-db --with-z-inc --with-zlib
	echo "Trying to make webalizer..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	make install
	
	writeLog "webalizer ${WEBALIZER_VER} installed"
	
	if [ "${AWSTATS_OPT}" = "no" ]; then
		setVal awstats 0 ${DACONF_FILE}
	else
		setVal awstats 1 ${DACONF_FILE}
	fi

	doRestartDA

	if [ -e /etc/webalizer.conf ]; then
		mv -f /etc/webalizer.conf /etc/webalizer.conf.moved 2> /dev/null > /dev/null
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
}

####################################################

doawstats() {
	if [ "${AWSTATS_OPT}" != "yes" ]; then
		setVal awstats 0 ${DACONF_FILE}
		do_exit 1 "You cannot install awstats, because you do not have it set in options.conf file."
	fi

	TARGZ=awstats-${AWSTATS_VER}.tar.gz
	TARFILE=${WORKDIR}/${TARGZ}
	USR=/usr/local
	REALPATH=${USR}/awstats-${AWSTATS_VER}
	ALIASPATH=${USR}/awstats

	safeDownloadWithMove "${WORKDIR}/${TARGZ}" "${AWSTATS_DOWNLOADURL}"

	#Extract the file
	tar xzf ${TARFILE} --no-same-owner -C ${USR}

	if [ ! -e ${REALPATH} ]; then
		do_exit 1 "Directory ${REALPATH} does not exist"
	fi

	#link it from a fake path:
	/bin/rm -f ${ALIASPATH}
	/bin/ln -sf ${REALPATH} ${ALIASPATH}
	cd ${REALPATH}
	chown -R root:root ${REALPATH}
	chmod -R 755 ${REALPATH}

	#setup the directadmin.conf
	setVal awstats 1 ${DACONF_FILE}
	if [ "${WEBALIZER_OPT}" = "no" ]; then
		setVal webalizer 0 ${DACONF_FILE}
	else
		setVal webalizer 1 ${DACONF_FILE}
	fi

	doRestartDA
	cd ${WORKDIR}
	echo "AWstats ${AWSTATS_VER} installation is done."
	writeLog "Awstats ${AWSTATS_VER} installed"
}

####################################################
doNginxUnit_module() {
	ensureBuildPackages
	if [ ! -d unit-${UNIT_VER} ]; then
		safeDownloadWithMove "${WORKDIR}/unit-${UNIT_VER}.tar.gz" "${UNIT_DOWNLOADURL}"
		cd ${WORKDIR}
		FILE=${WORKDIR}/unit-${UNIT_VER}.tar.gz

		checkFile ${FILE}

		echo "Extracting ${FILE}..."
		tar xzf ${FILE} --no-same-owner
	fi

	cd unit-${UNIT_VER}

	if [ ! -s Makefile ]; then
		#configure
		echo "Configuring unit-${UNIT_VER}"
		"${configure_scripts_active[unit]}"

		if [ $? -ne 0 ]; then
			printf "\n*** There was an error while trying to configure Nginx. Check the %s file\n" "${configure_scripts_active[unit]}"
			do_exit 1
		fi
		echo "Done Configuration."
	fi
	
	UNIT_COMPONENT="$1"
	UNIT_COMPONENT_VER="$2"
	UNIT_COMPONENT_ADDITIONAL_FLAGS=""

	if [ "${UNIT_COMPONENT}" = "php" ]; then
		UNIT_COMPONENT_VER_SHORT=`echo "${UNIT_COMPONENT_VER}" | tr -d '.'`
		UNIT_PHP_CONFIG="/usr/local/php${UNIT_COMPONENT_VER_SHORT}/bin/php-config${UNIT_COMPONENT_VER_SHORT}"
		if [ ! -e "${UNIT_PHP_CONFIG}" ]; then
			UNIT_PHP_CONFIG="/usr/local/php${UNIT_COMPONENT_VER_SHORT}/bin/php-config"
		fi
		UNIT_COMPONENT_ADDITIONAL_FLAGS="--module=${UNIT_COMPONENT}${UNIT_COMPONENT_VER} --config=${UNIT_PHP_CONFIG} --lib-path=/usr/local/php${UNIT_COMPONENT_VER_SHORT}/lib"
	elif [ "${UNIT_COMPONENT}" = "python" ]; then
		UNIT_COMPONENT_ADDITIONAL_FLAGS="--module=python${UNIT_COMPONENT_VER} --config=/usr/bin/python3-config"
	elif [ "${UNIT_COMPONENT}" = "perl" ]; then
		UNIT_COMPONENT_ADDITIONAL_FLAGS="--module=${UNIT_COMPONENT}5 --${UNIT_COMPONENT}=${UNIT_COMPONENT}"
	elif [ "${UNIT_COMPONENT}" = "ruby" ]; then
		UNIT_COMPONENT_ADDITIONAL_FLAGS="--module=${UNIT_COMPONENT}${UNIT_COMPONENT_VER} --${UNIT_COMPONENT}=${UNIT_COMPONENT}"
	elif [ "${UNIT_COMPONENT}" = "java" ]; then
		JAVA_LIB_PATH=${3}/jre/lib
		if [ -d "${JAVA_LIB_PATH}/amd64" ]; then
			JAVA_LIB_PATH=${JAVA_LIB_PATH}/amd64
		elif [ ! -d ${JAVA_LIB_PATH} ]; then
			JAVA_LIB_PATH=${3}/lib
		fi
		UNIT_COMPONENT_ADDITIONAL_FLAGS="--module=${UNIT_COMPONENT}${UNIT_COMPONENT_VER} --home=${3} --lib-path=${JAVA_LIB_PATH} --jars=/usr/share/unit-jsc-common/"
	fi
	./configure ${UNIT_COMPONENT} ${UNIT_COMPONENT_ADDITIONAL_FLAGS}
	if [ "${UNIT_COMPONENT}" = "nodejs" ]; then
		if rhel_version_is 7; then
			#C++11 is needed for libmodsecurity
			install_rpms centos-release-scl
			install_rpms devtoolset-9
			scl enable devtoolset-9 "make node-install"
		else
			make node-install
		fi
	elif [ "${UNIT_COMPONENT}" = "java" ]; then
		make ${UNIT_COMPONENT}${UNIT_COMPONENT_VER}-install
	elif [ "${UNIT_COMPONENT}" = "perl" ]; then
		make perl5-install
	else
		make ${UNIT_COMPONENT}${UNIT_COMPONENT_VER} 
		if [ -s build/${UNIT_COMPONENT}${UNIT_COMPONENT_VER}.unit.so ]; then
			MODULES_DIR=`/usr/sbin/unitd --version 2>&1 | grep -o 'modules=[^ ]*'|cut -d= -f2`
			cp -pf build/${UNIT_COMPONENT}${UNIT_COMPONENT_VER}.unit.so ${MODULES_DIR}/${UNIT_COMPONENT}${UNIT_COMPONENT_VER}.unit.so
		fi
	fi

	cd ${WORKDIR}
}

doNginxUnit_modules() {
	if [ -d /usr/lib/unit/modules ] && [ "${UNIT_OPT}" = "yes" ]; then
		ensureBuildPackages
		#cleanup all the modules
		rm -f /usr/lib/unit/modules/*

		#Install Nginx Unit extensions for all releases of PHP
		if [ -x /usr/local/php${PHP1_SHORTRELEASE}/bin/php ]; then
			if /usr/local/php${PHP1_SHORTRELEASE}/bin/php -i | grep -m1 -q 'enable-embed'; then
				doNginxUnit_module php ${PHP1_RELEASE_OPT}
			fi
		fi
		if [ "${PHP2_RELEASE_OPT}" != "no" ] && [ -x /usr/local/php${PHP2_SHORTRELEASE}/bin/php ]; then
			if /usr/local/php${PHP2_SHORTRELEASE}/bin/php -i | grep -m1 -q 'enable-embed'; then
				doNginxUnit_module php ${PHP2_RELEASE_OPT}
			fi
		fi
		if [ "${PHP3_RELEASE_OPT}" != "no" ] && [ -x /usr/local/php${PHP3_SHORTRELEASE}/bin/php ]; then
			if /usr/local/php${PHP3_SHORTRELEASE}/bin/php -i | grep -m1 -q 'enable-embed'; then
				doNginxUnit_module php ${PHP3_RELEASE_OPT}
			fi
		fi
		if [ "${PHP4_RELEASE_OPT}" != "no" ] && [ -x /usr/local/php${PHP4_SHORTRELEASE}/bin/php ]; then
			if /usr/local/php${PHP4_SHORTRELEASE}/bin/php -i | grep -m1 -q 'enable-embed'; then
				doNginxUnit_module php ${PHP4_RELEASE_OPT}
			fi
		fi

		#Install missing language files, if any
		install_debs hg-fast-export libperl-dev python3-dev python3-pip
		install_rpms mercurial perl-devel perl-libs

		if [ -x /usr/bin/perl ] || [ -x /usr/local/bin/perl ]; then
			doNginxUnit_module perl
		fi

		if [ -x /usr/bin/which ]; then
			JAVA_DIRECTORY=$(dirname $(dirname $(readlink -f $(which javac 2>/dev/null) 2>/dev/null) 2>/dev/null) 2>/dev/null)
			if [ -z "${JAVA_DIRECTORY}" ]; then
				if debian_version_is 9; then
					install_debs openjdk-8-jdk
				elif debian_version_is 10; then
					install_debs openjdk-11-jdk
				elif rhel_version_is 7; then
					install_rpms java-11-openjdk-devel
				else
					install_debs openjdk-17-jdk
					install_rpms java-17-openjdk-devel
				fi
			fi
			if [ -e /usr/lib/jvm/java-17-openjdk ]; then
				doNginxUnit_module java "17" "/usr/lib/jvm/java-17-openjdk"
			elif [ -e /usr/lib/jvm/java-17-openjdk-amd64 ]; then
				doNginxUnit_module java "17" "/usr/lib/jvm/java-17-openjdk-amd64"
			elif [ -e /usr/lib/jvm/java-11-openjdk ]; then
				doNginxUnit_module java "11" "/usr/lib/jvm/java-11-openjdk"
			elif [ -e /usr/lib/jvm/java-11-openjdk-amd64 ]; then
				doNginxUnit_module java "11" "/usr/lib/jvm/java-11-openjdk-amd64"
			fi
			if [ -e /usr/lib/jvm/java-1.8.0-openjdk ]; then
				doNginxUnit_module java "1.8" "/usr/lib/jvm/java-1.8.0-openjdk"
			elif [ -e /usr/lib/jvm/java-1.8.0-openjdk-amd64 ]; then
				doNginxUnit_module java "1.8" "/usr/lib/jvm/java-1.8.0-openjdk-amd64"
			fi
			if [ -e /usr/lib/jvm/java-1.7.0-openjdk-amd64 ]; then
				doNginxUnit_module java "7" "/usr/lib/jvm/java-1.7.0-openjdk-amd64"
			fi
		fi
		install_debs python3-dev
		install_rpms python3-devel
		if [ -x /usr/bin/python3-config ]; then
			PYTHON_VERSION=`python3 --version | awk '{print $2}' | cut -d. -f1,2`
			if [ -z "${PYTHON_VERSION}" ]; then
				PYTHON_VERSION=3
			fi
			doNginxUnit_module python ${PYTHON_VERSION}
		fi
		if ! rhel_version_is 7; then
			install_debs ruby-dev ruby-rack
			install_rpms ruby-devel rubygem-rack
			if ls -ld /usr/include/ruby*/ 2>/dev/null || [ -d /usr/lib64/ruby ]; then
				RUBY_VERSION=`ruby -v | awk '{print $2}' | cut -d. -f1,2`
				if [ -z "${RUBY_VERSION}" ]; then
					RUBY_VERSION=2
				fi
				doNginxUnit_module ruby ${RUBY_VERSION}
			fi
		fi

		if [ ! -x /usr/bin/npm ] && [ ! -x /usr/local/bin/npm ]; then
			install_debs nodejs
			install_rpms nodejs
		fi
		#If npm is detected - install unit module
		if [ -x /usr/bin/npm ] || [ -x /usr/local/bin/npm ]; then
			if [ ! -x /usr/bin/node-gyp ] && [ ! -x /usr/local/bin/node-gyp ]; then
				npm install -g node-gyp
			fi
			doNginxUnit_module nodejs
		fi
		if [ -d /usr/local/lib/node_modules ] && [ ! -d /usr/lib/node_modules ]; then
			ln -s /usr/local/lib/node_modules /usr/lib/node_modules 2>/dev/null
		fi
		echo "Nginx Unit language modules have been installed."
	fi
}

doNginxUnit() {
	if [ "${UNIT_OPT}" != "yes" ]; then
		do_exit 1 "You cannot install Nginx Unit, because you do not have it set in options.conf file."
	fi
	ensureBuildPackages
	install_debs libssl-dev
	install_rpms openssl-devel

	safeDownloadWithMove "${WORKDIR}/unit-${UNIT_VER}.tar.gz" "${UNIT_DOWNLOADURL}"

	#Add nginx_unit user/group if it doesn't exist after installation
	addUserGroup nginx_unit nginx_unit
	addToAccess nginx_unit

	cd ${WORKDIR}
	FILE=${WORKDIR}/unit-${UNIT_VER}.tar.gz

	checkFile ${FILE}

	echo "Extracting ${FILE}..."
	tar xzf ${FILE} --no-same-owner

	cd unit-${UNIT_VER}

	if [ -s src/nxt_process.c ]; then
		echo "Patching unit for per-user process grouping"
		patch -p0 < ${WORKDIR}/patches/unit_cgroup.patch
	fi

	#configure
	echo "Configuring unit-${UNIT_VER}"
	"${configure_scripts_active[unit]}"

	if [ $? -ne 0 ]; then
		printf "\n*** There was an error while trying to configure Nginx. Check the %s file\n" "${configure_scripts_active[unit]}"
		do_exit 1
	fi
	echo "Done Configuration."

	echo "Trying to make Nginx Unit..."
	if ! C_INCLUDE_PATH=/usr/kerberos/include make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi

	echo "Installing Nginx Unit..."

	make install
	make libunit-install

	cd ${WORKDIR}

	#fresh install, add to System Backup
	if [ ! -s ${SYSTEMDDIR}/unit.service ]; then
		add_to_system_backup dirs /var/lib/unit
	fi
	
	echo "Enabling Nginx Unit in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/unit.service ]; then
		cp -f ${CB_CUST_SYSTEMD}/unit.service ${SYSTEMDDIR}/unit.service
	else
		cp -f ${CB_SYSTEMD}/unit.service ${SYSTEMDDIR}/unit.service
	fi
	chmod 644 ${SYSTEMDDIR}/unit.service
	systemctl daemon-reload
	systemctl enable unit.service

	setupLogrotate unit

	if [ ! -d /var/log/unit ]; then
		mkdir -p /var/log/unit
	fi

	chmod 700 /var/log/unit
	chown root:root /var/log/unit

	if [ ! -d /usr/lib/unit/modules ]; then
		mkdir -p /usr/lib/unit/modules
	fi
	set_service unit ON

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "Restarting Nginx Unit."

	control_service unit stop >/dev/null 2>&1

	doNginxUnit_modules
	control_service unit start

	writeLog "Nginx Unit ${UNIT_VER} installed"
}

####################################################

doPhpConf() {
#	if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
#		return
#	fi

	if [ "${HAVE_FPM_CGI}" = "yes" ]; then
		for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
			set_service php-fpm${php_shortrelease} OFF
		done
	else
		for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
			set_service php-fpm${php_shortrelease} delete
		done
	fi

	fpmChecks

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		doApacheHostConf

		if [ -e ${WORKDIR}/custom/ap2/conf/extra/httpd-php-handlers.conf ]; then
			cp -f ${WORKDIR}/custom/ap2/conf/extra/httpd-php-handlers.conf ${PHP_HANDLERS_HTTPD}
		else
			# Writing data to httpd-php-handlers.conf
			echo -n "" > ${PHP_HANDLERS_HTTPD}

			echo '<FilesMatch "\.(inc|php[0-9]*|phtml|phps)$">' >> ${PHP_HANDLERS_HTTPD}

			if [ "${PHP1_MODE_OPT}" = "lsphp" ]; then
				echo "AddHandler application/x-httpd-lsphp .inc .php .php5 .php${PHP1_SHORTRELEASE} .phtml" >> ${PHP_HANDLERS_HTTPD}
			fi

			if [ "${PHP1_MODE_OPT}" = "lsphp" ]; then
				echo "AddHandler application/x-httpd-php-source .phps" >> ${PHP_HANDLERS_HTTPD}
			fi

			echo '</FilesMatch>' >> ${PHP_HANDLERS_HTTPD}

			echo "AddType text/html .php" >> ${PHP_HANDLERS_HTTPD}
		fi
	fi

	if [ "${HAVE_FCGID}" = "yes" ]; then
		if [ "${PHP1_MODE_OPT}" = "fastcgi" ]; then
			doSetupFcgidSh ${PHP1_SHORTRELEASE}
		fi
		if [ "${PHP2_MODE_OPT}" = "fastcgi" ] && [ "${PHP2_RELEASE_OPT}" != "no" ]; then
			doSetupFcgidSh ${PHP2_SHORTRELEASE}
		fi
		if [ "${PHP3_MODE_OPT}" = "fastcgi" ] && [ "${PHP3_RELEASE_OPT}" != "no" ]; then
			doSetupFcgidSh ${PHP3_SHORTRELEASE}
		fi
		if [ "${PHP4_MODE_OPT}" = "fastcgi" ] && [ "${PHP4_RELEASE_OPT}" != "no" ]; then
			doSetupFcgidSh ${PHP4_SHORTRELEASE}
		fi
		 
	fi

	for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
		declare -g "HAVE_FPM${php_shortrelease}=no"
	done

	if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
		systemctl restart php-fpm${PHP1_SHORTRELEASE}.service
		systemctl enable php-fpm${PHP1_SHORTRELEASE}.service

		set_service php-fpm${PHP1_SHORTRELEASE} ON
		declare -g "HAVE_FPM${PHP1_SHORTRELEASE}=yes"
	fi
	if [ "${PHP2_MODE_OPT}" = "php-fpm" ] && [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		systemctl restart php-fpm${PHP2_SHORTRELEASE}.service
		systemctl enable php-fpm${PHP2_SHORTRELEASE}.service

		set_service php-fpm${PHP2_SHORTRELEASE} ON
		declare -g "HAVE_FPM${PHP2_SHORTRELEASE}=yes"
	fi
	if [ "${PHP3_MODE_OPT}" = "php-fpm" ] && [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		systemctl restart php-fpm${PHP3_SHORTRELEASE}.service
		systemctl enable php-fpm${PHP3_SHORTRELEASE}.service

		set_service php-fpm${PHP3_SHORTRELEASE} ON
		declare -g "HAVE_FPM${PHP3_SHORTRELEASE}=yes"
	fi
	if [ "${PHP4_MODE_OPT}" = "php-fpm" ] && [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		systemctl restart php-fpm${PHP4_SHORTRELEASE}.service
		systemctl enable php-fpm${PHP4_SHORTRELEASE}.service

		set_service php-fpm${PHP4_SHORTRELEASE} ON
		declare -g "HAVE_FPM${PHP4_SHORTRELEASE}=yes"
	fi

	for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
		EVAL_FPM_VAR=HAVE_FPM${php_shortrelease}
		HAVE_SHORTRELEASE="${!EVAL_FPM_VAR}"
		if [ "${HAVE_SHORTRELEASE}" = "no" ]; then
			systemctl stop php-fpm${php_shortrelease}.service 2> /dev/null
			systemctl disable php-fpm${php_shortrelease}.service 2> /dev/null
			if [ -e ${SYSTEMDDIR}/php-fpm${php_shortrelease}.service ]; then
				rm -f ${SYSTEMDDIR}/php-fpm${php_shortrelease}.service
			fi
			systemctl daemon-reload
			set_service php-fpm${php_shortrelease} delete
		fi
	done

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "" > /etc/httpd/conf/extra/httpd-suphp.conf
	fi

	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		OPENLITESPEED_EXTPROCESSORS=${LSWS_HOME}/conf/httpd-extprocessors.conf
		echo -n '' > ${OPENLITESPEED_EXTPROCESSORS}
		if [ "${PHP1_MODE_OPT}" = "lsphp" ]; then
			perl -p -e "s#\|PHP_SHORTRELEASE\|#${PHP1_SHORTRELEASE}#g" ${WORKDIR}/${OPENLITESPEED_WEBAPPS_EXTPROCESSOR_TEMPLATE} >> ${OPENLITESPEED_EXTPROCESSORS}
			echo '' >> ${OPENLITESPEED_EXTPROCESSORS}
			perl -p -e "s#\|PHP_SHORTRELEASE\|#${PHP1_SHORTRELEASE}#g" ${WORKDIR}/${OPENLITESPEED_EXTPROCESSORS_TEMPLATE} >> ${OPENLITESPEED_EXTPROCESSORS}
			echo '' >> ${OPENLITESPEED_EXTPROCESSORS}
			#CloudLinux PHP selector support needs /usr/local/bin/lsphp as the path
			perl -pi -e "s#/usr/local/php${PHP1_SHORTRELEASE}/bin/lsphp#/usr/local/bin/lsphp#g" ${OPENLITESPEED_EXTPROCESSORS}
		fi
		if [ "${PHP2_MODE_OPT}" = "lsphp" ] && [ "${PHP2_RELEASE_OPT}" != "no" ]; then
			perl -p -e "s#\|PHP_SHORTRELEASE\|#${PHP2_SHORTRELEASE}#g" ${WORKDIR}/${OPENLITESPEED_EXTPROCESSORS_TEMPLATE} >> ${OPENLITESPEED_EXTPROCESSORS}
			echo '' >> ${OPENLITESPEED_EXTPROCESSORS}
		fi
		if [ "${PHP3_MODE_OPT}" = "lsphp" ] && [ "${PHP3_RELEASE_OPT}" != "no" ]; then
			perl -p -e "s#\|PHP_SHORTRELEASE\|#${PHP3_SHORTRELEASE}#g" ${WORKDIR}/${OPENLITESPEED_EXTPROCESSORS_TEMPLATE} >> ${OPENLITESPEED_EXTPROCESSORS}
			echo '' >> ${OPENLITESPEED_EXTPROCESSORS}
		fi
		if [ "${PHP4_MODE_OPT}" = "lsphp" ] && [ "${PHP4_RELEASE_OPT}" != "no" ]; then
			perl -p -e "s#\|PHP_SHORTRELEASE\|#${PHP4_SHORTRELEASE}#g" ${WORKDIR}/${OPENLITESPEED_EXTPROCESSORS_TEMPLATE} >> ${OPENLITESPEED_EXTPROCESSORS}
			echo '' >> ${OPENLITESPEED_EXTPROCESSORS}
		fi
		
		OPENLITESPEED_SCRIPTHANDLER=${LSWS_HOME}/conf/httpd-scripthandler.conf
		echo 'scriptHandler{' > ${OPENLITESPEED_SCRIPTHANDLER}
		echo "add lsapi:lsphp${PHP1_SHORTRELEASE} php" >> ${OPENLITESPEED_SCRIPTHANDLER}
		echo 'add lsapi:lsphpwebapps lsphpwebapps' >> ${OPENLITESPEED_SCRIPTHANDLER}
		echo '}' >> ${OPENLITESPEED_SCRIPTHANDLER}
	fi

	if [ "${SECURE_PHP_OPT}" = "yes" ]; then
		secure_php
	fi
}

####################################################
add_alias_redirect() {
	AF=$1
	A=$2
	P=$3

	HTTP=http://
	if [ "${REDIRECT_HOST_HTTPS_OPT}" = "yes" ]; then
		HTTP=https://
	fi

	HOST_ALIAS=no
	if [ "${USE_HOSTNAME_FOR_ALIAS_OPT}" = "yes" ]; then
		HOST_ALIAS=yes
	fi
	
	IS_WELL_KNOWN=no
	if [ "${P}" = ".well-known/acme-challenge" ]; then
		IS_WELL_KNOWN=yes
	fi

	if [ "${HOST_ALIAS}" = "yes" ] && [ "${IS_WELL_KNOWN}" = "no" ]; then
		echo "RewriteCond %{HTTP_HOST} !^${REDIRECT_HOST_OPT}\$" >> ${AF}

		echo "RewriteCond %{REQUEST_URI} ^/${A}/ [OR]" >> ${AF}
		echo "RewriteCond %{REQUEST_URI} ^/${A}\$" >> ${AF}

		echo "RewriteRule ^/${A}(.*) ${HTTP}${REDIRECT_HOST_OPT}/${P}\$1" >> ${AF}

		echo "" >> ${AF}
	fi

	#For let's encrypt challenges
	if [ "${IS_WELL_KNOWN}" = "yes" ]; then
		LETSENCRYPT=$(${DA_BIN} config-get letsencrypt)
		if [ "${LETSENCRYPT}" = "1" ]; then
			echo "Alias /${A} /var/www/html/${P}" >> ${AF}
		fi
		return;
	fi
	
	# "! -e /var/www/html/${A}" is used to add Alias'es for the RewriteRules that don't have /var/www/html/ALIAS
	if [ "${HOST_ALIAS}" = "no" ] || [ ! -e /var/www/html/${A} ]; then
		echo "Alias /${A} /var/www/html/${P}" >> ${AF}
	fi
}

do_rewrite_httpd_alias() {
	if [ -e ${WORKDIR}/custom/ap2/conf/extra/httpd-alias.conf ]; then
		cp -pf ${WORKDIR}/custom/ap2/conf/extra/httpd-alias.conf /etc/httpd/conf/extra/httpd-alias.conf
	else
		HA=/etc/httpd/conf/extra/httpd-alias.conf

		echo -n '' > ${HA}

		if [ "${USE_HOSTNAME_FOR_ALIAS_OPT}" = "yes" ]; then
			echo "RewriteEngine On" >> ${HA}
		fi

		#For let's encrypt challenges
		LETSENCRYPT=$(${DA_BIN} config-get letsencrypt)
		if [ "${LETSENCRYPT}" = "1" ]; then
			add_alias_redirect ${HA} .well-known/acme-challenge .well-known/acme-challenge
		fi
		add_alias_redirect ${HA} config redirect.php

		if [ "${SQUIRRELMAIL_OPT}" = "yes" ]; then
			add_alias_redirect ${HA} squirrelmail squirrelmail
		fi

		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			add_alias_redirect ${HA} roundcube roundcube
		fi

		WEBMAILLINK=`get_webmail_link`
		if [ -e /var/www/html/${WEBMAILLINK} ]; then
			add_alias_redirect ${HA} webmail ${WEBMAILLINK}
		fi

		if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
			add_alias_redirect ${HA} phpMyAdmin phpMyAdmin
			add_alias_redirect ${HA} phpmyadmin phpMyAdmin
			add_alias_redirect ${HA} pma phpMyAdmin
		fi

		if [ -s "${WEBAPPS_LIST}" ]; then
			#https://forum.directadmin.com/showthread.php?t=48203&p=247343#post247343
			echo "Adding custom webapps from ${WEBAPPS_LIST}"

			cat ${WEBAPPS_LIST} | while read l; do
				app=`echo "$l" | cut -d= -f1`
				app_path=`echo "$l" | cut -d= -f2`

				if [ "${app}" = "" ] || [ "${app_path}" = "" ]; then
					echo "${boldon}Check your ${WEBAPPS_LIST}.  A name or path is blank.${boldoff}"
					echo "name=$app"
					echo "path=$app_path"
					continue
				fi

				if [ ! -e /var/www/html/${app_path} ]; then
					echo "${boldon}Cannot find path /var/www/html/${app_path} for alias ${app}${boldoff}"
					continue
				fi

				add_alias_redirect ${HA} ${app} ${app_path}
				echo "Added ${app} pointing to ${app_path}"
			done
		fi
	fi
}

add_nginx_alias_redirect() {
	#A fake P real
	F=$1
	A=$2
	P=$3

	#Locations with regex have higher priority for URL-rewrites/aliases
	printf "\tlocation ~ ^/${A} {\n" >> ${F}
	printf "\t\trewrite ^/* /${P} last;\n" >> ${F}
	printf "\t}\n" >> ${F}
}

add_nginx_alias() {
	F=$1
	A=$2

	#Locations with regex (~ ^/alias) have higher priority for URL-rewrites/aliases
	if [ "${WEBSERVER_OPT}" = "nginx" ]; then
		printf "\tlocation ^~ /${A} {\n" >> ${F}
		printf "\t\troot /var/www/html/;\n" >> ${F}
		printf "\t\tindex index.php index.html index.htm;\n" >> ${F}
		printf "\t\tlocation ~ ^/${A}/(.+\.php)\$ {\n" >> ${F}
		printf "\t\t\tinclude /etc/nginx/webapps_settings.conf;\n" >> ${F}
		printf "\t\t}\n" >> ${F}
		#protect RoundCube folders
		if [ "${A}" = "roundcube" ]; then
			printf "\t\tlocation ~ /${A}/(bin|SQL|config|logs|temp)/ {\n" >> ${F}
			printf "\t\t\tdeny all;\n" >> ${F}
			printf "\t\t}\n" >> ${F}
		elif [ "${A}" = "phpMyAdmin" ]; then
			printf "\t\tlocation ~ /${A}/log/ {\n" >> ${F}
			printf "\t\t\tdeny all;\n" >> ${F}
			printf "\t\t}\n" >> ${F}
		fi
		printf "\t\tlocation ~* ^/${A}/(.*(\.htaccess|\.htpasswd|\.user\.ini|\.env|\.git))\$ {\n" >> ${F}
		printf "\t\t\tdeny all;\n" >> ${F}
		printf "\t\t}\n" >> ${F}
		printf "\t\tlocation ~* ^/${A}/(.+\\.(jpg|jpeg|gif|css|png|js|ico|html|webp|xml|txt))\$ {\n" >> ${F}
		printf "\t\t\troot /var/www/html/;\n" >> ${F}
		printf "\t\t}\n" >> ${F}
		printf "\t}\n" >> ${F}
	elif [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		getWebserverPorts
		printf "\tlocation ^~ /${A} {\n" >> ${F}
		printf "\t\troot /var/www/html/;\n" >> ${F}
		printf "\t\tindex index.php index.html index.htm;\n" >> ${F}
		printf "\t\tlocation ~ ^/${A}/ {\n" >> ${F}
		printf "\t\t\taccess_log off;\n" >> ${F}
		printf "\t\tset \$my_server_addr \$server_addr;\n" >> ${F}
		printf "\t\tif (\$server_addr ~ ^[0-9a-fA-F:]+$) { set \$my_server_addr [\$server_addr]; }\n" >> ${F}
		printf "\t\t\tproxy_pass http://\$my_server_addr:${PORT_8080};\n" >> ${F}
		printf "\t\t\tproxy_set_header X-Client-IP      \$remote_addr;\n" >> ${F}
		printf "\t\t\tproxy_set_header X-Accel-Internal /$A/nginx_static_files;\n" >> ${F}
		printf "\t\t\tproxy_set_header Host\t     \$host;\n" >> ${F}
		printf "\t\t\tproxy_set_header X-Forwarded-For  \$proxy_add_x_forwarded_for;\n" >> ${F}
		printf "\t\t\tproxy_hide_header Upgrade;\n" >> ${F}
		printf "\t\t}\n" >> ${F}
		printf "\t\tlocation ~ ^/${A}/nginx_static_files/ {\n" >> ${F}
		printf "\t\t\taccess_log  /var/log/nginx/access_log_proxy;\n" >> ${F}
		printf "\t\t\talias       /var/www/html/;\n" >> ${F}
		printf "\t\t\tinternal;\n" >> ${F}
		printf "\t\t}\n" >> ${F}

		printf "\t}\n" >> ${F}
	fi
}

do_rewrite_nginx_webapps() {
	if [ -e ${WORKDIR}/custom/nginx/conf/webapps.conf ] && [ "${WEBSERVER_OPT}" = "nginx" ]; then
		cp -pf ${WORKDIR}/custom/nginx/conf/webapps.conf /etc/nginx/webapps.conf
	elif [ -e ${WORKDIR}/custom/nginx_reverse/conf/webapps.conf ] && [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		cp -pf ${WORKDIR}/custom/nginx_reverse/conf/webapps.conf /etc/nginx/webapps.conf
	else
		NW=/etc/nginx/webapps.conf

		: > ${NW}
		#block .htaccess and .user.ini
		printf '\tlocation ~ /(\\.htaccess|\\.htpasswd|\\.user\\.ini|\\.env|\\.git) {\n' >> ${NW}
		printf '\t\tdeny all;\n' >> ${NW}
		printf '\t}\n' >> ${NW}
	
		#For let's encrypt challenges
		LETSENCRYPT=$(${DA_BIN} config-get letsencrypt)
		if [ "${LETSENCRYPT}" = "1" ]; then
			add_nginx_alias ${NW} .well-known/acme-challenge
		fi
        
		if [ "${SQUIRRELMAIL_OPT}" = "yes" ]; then
			add_nginx_alias ${NW} squirrelmail
		fi

		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			add_nginx_alias ${NW} roundcube
		fi

		if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
			add_nginx_alias ${NW} phpMyAdmin
			add_nginx_alias_redirect ${NW} phpmyadmin phpMyAdmin
			add_nginx_alias_redirect ${NW} pma phpMyAdmin
		fi

		WEBMAILLINK=`get_webmail_link`
		if [ -e /var/www/html/${WEBMAILLINK} ]; then
			if [ "${WEBMAILLINK}" = "webmail" ]; then
				add_nginx_alias ${NW} webmail
			else
				add_nginx_alias_redirect ${NW} webmail ${WEBMAILLINK}
			fi
		fi

		if [ "${HTTP_METHODS_OPT}" != "ALL" ]; then
			NGINX_HTTP_METHODS="`echo ${HTTP_METHODS_OPT} | tr ':' '|'`"
			printf "\tif (\$request_method !~ ^(${NGINX_HTTP_METHODS})\$ ) {\n" >> ${NW}
			printf '\t\treturn 444;\n' >> ${NW}
			printf '\t}\n' >> ${NW}
		fi
	fi

	WAHC=webapps.hostname.conf
	if [ -e ${WORKDIR}/custom/nginx/conf/${WAHC} ] && [ "${WEBSERVER_OPT}" = "nginx" ]; then
		cp -pf ${WORKDIR}/custom/nginx/conf/${WAHC} /etc/nginx/${WAHC}
	elif [ -e ${WORKDIR}/custom/nginx_reverse/conf/${WAHC} ] && [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		cp -pf ${WORKDIR}/custom/nginx_reverse/conf/${WAHC} /etc/nginx/${WAHC}
	else
		#In nginx-vhosts.conf we don't need to have "real" alias specified, because they already exist when acessing http://IP or http://hostname
		NW_HOSTNAME=/etc/nginx/${WAHC}
		: > ${NW_HOSTNAME}

		#block .htaccess and .user.ini
		printf '\tlocation ~ /(\\.htaccess|\\.htpasswd|\\.user\\.ini|\\.env|\\.git) {\n' >> ${NW_HOSTNAME}
		printf '\t\tdeny all;\n' >> ${NW_HOSTNAME}
		printf '\t}\n' >> ${NW_HOSTNAME}
		
		#protect other places
		printf '\tlocation ~ /(roundcube|webmail)/(bin|SQL|config|logs|temp)/ {\n' >> ${NW_HOSTNAME}
		printf '\t\tdeny all;\n' >> ${NW_HOSTNAME}
		printf '\t}\n' >> ${NW_HOSTNAME}
		
		printf '\tlocation ~ /phpMyAdmin/log/ {\n' >> ${NW_HOSTNAME}
		printf '\t\tdeny all;\n' >> ${NW_HOSTNAME}
		printf '\t}\n' >> ${NW_HOSTNAME}

		if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
			add_nginx_alias_redirect ${NW_HOSTNAME} phpmyadmin phpMyAdmin
			add_nginx_alias_redirect ${NW_HOSTNAME} pma phpMyAdmin
		fi

		WEBMAILLINK=`get_webmail_link`
		if [ ! -e /var/www/html/${WEBMAILLINK} ] && [ "${WEBMAILLINK}" != "webmail" ]; then
			add_nginx_alias_redirect ${NW_HOSTNAME} webmail ${WEBMAILLINK}
		fi

		if [ -s "${WEBAPPS_LIST}" ]; then
			#https://forum.directadmin.com/showthread.php?t=48203&p=247343#post247343
			echo "Adding custom webapps from ${WEBAPPS_LIST}"

			cat ${WEBAPPS_LIST} | while read l; do
				app=`echo "$l" | cut -d= -f1`
				app_path=`echo "$l" | cut -d= -f2`

				if [ "${app}" = "" ] || [ "${app_path}" = "" ]; then
					echo "${boldon}Check your ${WEBAPPS_LIST}.  A name or path is blank.${boldoff}"
					echo "name=$app"
					echo "path=$app_path"
					continue
				fi

				if [ ! -e /var/www/html/${app_path} ]; then
					echo "${boldon}Cannot find path /var/www/html/${app_path} for alias ${app}${boldoff}"
					continue
				fi

				if [ -e /var/www/html/${app} ] && [ "${app}" = "${app_path}" ]; then
					add_nginx_alias ${NW} ${app}
				else
					add_nginx_alias_redirect ${NW} ${app} ${app_path}
				fi
				echo "Added ${app} pointing to ${app_path}"
			done
		fi

		if [ "${HTTP_METHODS_OPT}" != "ALL" ]; then
			NGINX_HTTP_METHODS="`echo ${HTTP_METHODS_OPT} | tr ':' '|'`"
			printf "\tif (\$request_method !~ ^(${NGINX_HTTP_METHODS})\$ ) {\n" >> ${NW_HOSTNAME}
			printf '\t\treturn 444;\n' >> ${NW_HOSTNAME}
			printf '\t}\n' >> ${NW_HOSTNAME}
		fi
	fi

	cp -pf /etc/nginx/webapps.conf /etc/nginx/webapps.ssl.conf
	getWebserverPorts
	perl -pi -e "s|:${PORT_8080}|:${PORT_8081}|" /etc/nginx/webapps.ssl.conf
	perl -pi -e 's|http:|https:|' /etc/nginx/webapps.ssl.conf

	if [ "${HAVE_FPM_CGI}" = "yes" ]; then
		#update the webapps_settings.conf
		#swap "fastcgi_pass unix:/usr/local/php54/sockets/webapps.sock;" if needed
		#might be a better way to do this, other checks. Close enough for now.

		PHP_REPLACE_STRING="`grep -m1 '^fastcgi_pass unix:/usr/local/php../sockets/webapps.sock;' /etc/nginx/webapps_settings.conf | cut -d/ -f4`"
		if [ "${PHP_REPLACE_STRING}" = "" ]; then
			PHP_REPLACE_STRING=php54
		fi
		if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
			perl -pi -e "s#${PHP_REPLACE_STRING}#php${PHP1_SHORTRELEASE}#" /etc/nginx/webapps_settings.conf
		fi
	fi
}

####################################################

create_httpd_nginx() {
	CONF_FILE=${HTTPDCONF}/extra/httpd-nginx.conf
	echo -n '' > ${CONF_FILE}

	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ ! -e /usr/lib/apache/mod_aclr2.so ]; then
			doModAclr2
		elif [ -s ${STRINGS} ]; then
			if ! ${STRINGS} /usr/lib/apache/mod_aclr2.so | grep -q -m1 'memmove'; then
				doModAclr2
			fi
		fi
		echo 'LoadModule aclr_module	/usr/lib/apache/mod_aclr2.so' >> ${CONF_FILE}
		echo 'AccelRedirectSet On' >> ${CONF_FILE}
		echo 'AccelRedirectSize 1k' >> ${CONF_FILE}
		echo 'RemoteIPHeader X-Client-IP' >> ${CONF_FILE}
		echo 'RemoteIPInternalProxy 127.0.0.1' >> ${CONF_FILE}
		doCheckIPV6
		if [ "${IPV6}" = "1" ]; then
			echo 'RemoteIPInternalProxy ::1' >> ${CONF_FILE}
		fi
		echo 'RemoteIPInternalProxyList /usr/local/directadmin/data/admin/ip.list' >> ${CONF_FILE}
	fi
}

ensure_dhparam() {
	DHF=$1
	MD5="6377960551b81b27240486a0e2680ef8"
	if [ -s ${DHF} ]; then
		FMD5=`md5sum ${DHF} | cut -d\  -f1`
	else
		FMD5=""
	fi
	if [ "${MD5}" != "${FMD5}" ]; then
		safeDownloadWithMove "${DHF}" "${WEBPATH}/dhe/ffdhe4096.pem"
	fi
	if [ ! -s ${DHF} ]; then
		echo "Creating dhparam in ${DHF}"
		/usr/bin/openssl dhparam -out ${DHF} 4096
	fi
}

set_apache_mpm() {
	if ! grep -m1 -q '/usr/lib/apache/mod_mpm_' ${PHPMODULES}; then
		if [ "${APACHE_MPM_OPT}" = "auto" ] || [ "${APACHE_MPM_OPT}" = "event" ]; then
			set_LoadModule mpm_event_module mod_mpm_event.so
		elif [ "${APACHE_MPM_OPT}" = "worker" ]; then
			set_LoadModule mpm_worker_module mod_mpm_worker.so
		else
			set_LoadModule mpm_prefork_module mod_mpm_prefork.so
		fi
	else
		if [ "${APACHE_MPM_OPT}" = "auto" ]; then
			MPM_NAME=event
		else
			MPM_NAME=${APACHE_MPM_OPT}
		fi
		if ! grep -m1 -q "mpm_${MPM_NAME}_module" ${PHPMODULES}; then
			if grep -m1 -q 'LoadModule mpm_[a-z]*_module /usr/lib/apache/mod_mpm_[a-z]*.so' ${PHPMODULES}; then
				perl -pi -e "s#LoadModule mpm_[a-z]*_module /usr/lib/apache/mod_mpm_[a-z]*.so#LoadModule mpm_${MPM_NAME}_module /usr/lib/apache/mod_mpm_${MPM_NAME}.so#" ${PHPMODULES}
			fi
		fi
	fi
}

rewrite_phpmodules() {
		echo -n "" > ${PHPMODULES}

		HTTP2=$(${DA_BIN} config-get http2)
		if [ "${HTTP2}" = "1" ] && [ "${APACHE_MPM_OPT}" != "prefork" ] && [ -d /etc/httpd/conf/extra ]; then
			if ! grep -m1 -q 'ProtocolsHonorOrder' ${PHPMODULES}; then
				echo 'ProtocolsHonorOrder On' >> ${PHPMODULES}
				echo 'Protocols h2 h2c http/1.1' >> ${PHPMODULES}
			fi
		fi

		if [ "${PHP1_MODE_OPT}" = "lsphp" ]; then
			if ! grep -m1 -q '^Mutex ' ${PHPMODULES}; then
				echo "Mutex posixsem" >> ${PHPMODULES}
			fi
		fi

		if [ "${MODSECURITY_OPT}" = "yes" ]; then
			if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ]; then
				if grep -m1 -q "^LoadModule security2_module" /etc/httpd/conf/httpd.conf; then
					perl -pi -e 's|^LoadModule security2_module|#LoadModule security2_module|' /etc/httpd/conf/httpd.conf
				fi
				echo "Include /etc/httpd/conf/extra/httpd-modsecurity.conf" >> ${PHPMODULES}
				cp -pf ${MODSECURITY_APACHE_INCLUDE} /etc/httpd/conf/extra/httpd-modsecurity.conf
				if [ -e /usr/lib/libxml2.so ] && [ ! -e /usr/local/lib/libxml2.so ]; then
					perl -pi -e 's|LoadFile /usr/local/lib/libxml2.so|LoadFile /usr/lib/libxml2.so|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
				elif [ -e /usr/lib64/libxml2.so ] && [ ! -e /usr/local/lib/libxml2.so ]; then
					perl -pi -e 's|LoadFile /usr/local/lib/libxml2.so|LoadFile /usr/lib64/libxml2.so|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
				elif [ -e /usr/lib/x86_64-linux-gnu/libxml2.so ] && [ ! -e /usr/local/lib/libxml2.so ]; then
					perl -pi -e 's|LoadFile /usr/local/lib/libxml2.so|LoadFile /usr/lib/x86_64-linux-gnu/libxml2.so|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
				elif [ -e /usr/lib/aarch64-linux-gnu/libxml2.so ] && [ ! -e /usr/local/lib/libxml2.so ]; then
					perl -pi -e 's|LoadFile /usr/local/lib/libxml2.so|LoadFile /usr/lib/aarch64-linux-gnu/libxml2.so|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
				fi
				if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
					perl -pi -e 's|^Load|#Load|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
				fi
				doModSecurityRules norestart
			elif [ -s /etc/httpd/conf/extra/httpd-modsecurity.conf ]; then
				if grep -m1 -q '^LoadModule security2_module' /etc/httpd/conf/extra/httpd-modsecurity.conf; then
					perl -pi -e 's|^Load|#Load|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
				fi
			fi
		elif [ -s /etc/httpd/conf/extra/httpd-modsecurity.conf ]; then
			if grep -m1 -q '^LoadModule security2_module' /etc/httpd/conf/extra/httpd-modsecurity.conf; then
				perl -pi -e 's|^Load|#Load|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
			fi
		fi

		if [ "${HTSCANNER_OPT}" = "yes" ]; then
			if [ "${HAVE_FCGID}" = "yes" ] || [ "${HAVE_FPM_CGI}" = "yes" ]; then
				set_LoadModule htscanner_module mod_htscanner2.so
			fi
		fi

		set_apache_mpm

		if [ "${HAVE_FCGID}" = "yes" ]; then
			if ! grep -m1 -c 'fcgid_module' ${PHPMODULES}; then
				set_LoadModule fcgid_module mod_fcgid.so
			fi
			if ! grep -m1 -c 'httpd-fcgid.conf' ${PHPMODULES}; then
				echo "Include /etc/httpd/conf/extra/httpd-fcgid.conf" >> ${PHPMODULES}
			fi
		fi
}

doImportCipherSuites() {
	SSL_CONFIGURATION_OPT_UP="`echo ${SSL_CONFIGURATION_OPT} | tr '[a-z]' '[A-Z]'`"

	#older boxes might not support intermediate or modern.  Rewriting with either may kill those services.
	#must have OpenSSL 1.0.1 or higher for intermedaite+
	if [ "${SSL_CONFIGURATION_OPT_UP}" = "INTERMEDIATE" ] || [ "${SSL_CONFIGURATION_OPT_UP}" = "MODERN" ]; then
		OV=`openssl_version`
		if [ "${OV}" != "" ] && [ "`version_cmp ${OV} 1.0.1 'doImportCipherSuites check for openssl 1.0.1 ver check'`" -lt 0 ]; then
			echo "${boldon}*** ssl_configuration=${SSL_CONFIGURATION_OPT_UP} will try to use TLSv1.2, which your OpenSSL version ${OV} does not support.${boldoff}"
			echo "${boldon}Dropping this write down to ssl_configuration=old. You may want to make this permanent: './build set ssl_configuration old' or update your OS${boldoff}"
			SSL_CONFIGURATION_OPT_UP=OLD
		fi
	fi

	#MODERN is not there, as it's the default (empty) in service configuration
	INTERMEDIATE_CIPHERSUITE="ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256"
	OLD_CIPHERSUITE="ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA"
}

doSslConfigurationWebserver() {
	doImportCipherSuites
	#Do cleanup of old files in configure/ap2/conf/extra/ direcotry
	if [ -e configure/ap2/conf/extra/httpd-ssl-protocol.old.conf ]; then
		rm -f configure/ap2/conf/extra/httpd-ssl-protocol.old.conf
	fi
	if [ -e configure/ap2/conf/extra/httpd-ssl-protocol.intermediate.conf ]; then
		rm -f configure/ap2/conf/extra/httpd-ssl-protocol.intermediate.conf
	fi
	if [ -e configure/ap2/conf/extra/httpd-ssl-protocol.modern.conf ]; then
		rm -f configure/ap2/conf/extra/httpd-ssl-protocol.modern.conf
	fi

	case "${SSL_CONFIGURATION_OPT_UP}" in
	MODERN)
		APACHE_SSL_PROTOCOLS="SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1 -TLSv1.2"
		APACHE_SSL_CIPHERSUITE=""
		NGINX_SSL_PROTOCOLS="ssl_protocols TLSv1.3;"
		NGINX_SSL_CIPHERSUITE="ssl_ciphers DEFAULT;"
		OLS_SSL_PROTOCOLS="sslProtocol 16"
		OLS_SSL_CIPHERSUITE=""
		;;
	INTERMEDIATE)
		APACHE_SSL_PROTOCOLS="SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1"
		APACHE_SSL_CIPHERSUITE="SSLCipherSuite ${INTERMEDIATE_CIPHERSUITE}"
		NGINX_SSL_PROTOCOLS="ssl_protocols TLSv1.2 TLSv1.3;"
		NGINX_SSL_CIPHERSUITE="ssl_ciphers ${INTERMEDIATE_CIPHERSUITE};"
		OLS_SSL_PROTOCOLS="sslProtocol 24"
		OLS_SSL_CIPHERSUITE="ciphers ${INTERMEDIATE_CIPHERSUITE}"
		;;
	OLD)
		APACHE_SSL_PROTOCOLS="SSLProtocol all -SSLv3"
		APACHE_SSL_CIPHERSUITE="SSLCipherSuite ${OLD_CIPHERSUITE}"
		NGINX_SSL_PROTOCOLS="ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;"
		NGINX_SSL_CIPHERSUITE="ssl_ciphers ${OLD_CIPHERSUITE};"
		OLS_SSL_PROTOCOLS="sslProtocol 30"
		OLS_SSL_CIPHERSUITE="ciphers ${OLD_CIPHERSUITE}"
		;;
	esac

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ ! -e ${WORKDIR}/custom/ap2/conf/extra/httpd-ssl.conf ]; then
			perl -pi -e "s|^SSLProtocol.*|${APACHE_SSL_PROTOCOLS}|g" /etc/httpd/conf/extra/httpd-ssl.conf
			perl -pi -e "s|^SSLCipherSuite.*|${APACHE_SSL_CIPHERSUITE}|g" /etc/httpd/conf/extra/httpd-ssl.conf
			if [ -s /etc/httpd/conf/ssl.crt/server.crt.combined ]; then
				perl -pi -e 's|/etc/httpd/conf/ssl\.crt/server\.crt$|/etc/httpd/conf/ssl.crt/server.crt.combined|g' /etc/httpd/conf/extra/httpd-ssl.conf
				perl -pi -e 's|^SSLCACertificateFile|#SSLCACertificateFile|g' /etc/httpd/conf/extra/httpd-ssl.conf
				perl -pi -e 's|/etc/httpd/conf/ssl\.crt/server\.crt$|/etc/httpd/conf/ssl.crt/server.crt.combined|g' /etc/httpd/conf/extra/httpd-vhosts.conf
				perl -pi -e 's|    SSLCACertificateFile|    #SSLCACertificateFile|g' /etc/httpd/conf/extra/httpd-vhosts.conf
			fi
			if ! grep -m1 -q 'SSLOpenSSLConfCmd' /etc/httpd/conf/extra/httpd-ssl.conf; then
				# Needs OpenSSL 1.0.2 or higher
				OV=`openssl_version`
				if [ "${OV}" != "" ] && [ "`version_cmp ${OV} 1.0.2 'apache SSLOpenSSLConfCmd support for openssl 1.0.2 ver check'`" -ge 0 ]; then
					echo 'SSLOpenSSLConfCmd DHParameters "/etc/httpd/conf/ssl.crt/dhparams.pem"' >> /etc/httpd/conf/extra/httpd-ssl.conf
				fi
			fi
		fi
		if [ "${WEBSERVER_OPT}" = "nginx_apache" ] && [ ! -e ${WORKDIR}/custom/nginx_reverse/conf/nginx-defaults.conf ]; then
			perl -pi -e "s|^ssl_protocols.*|${NGINX_SSL_PROTOCOLS}|g" /etc/nginx/nginx-defaults.conf
			perl -pi -e "s|^ssl_ciphers.*|${NGINX_SSL_CIPHERSUITE}|g" /etc/nginx/nginx-defaults.conf
			perl -pi -e "s|^proxy_ssl_protocols.*|proxy_${NGINX_SSL_PROTOCOLS}|g" /etc/nginx/nginx-defaults.conf
			perl -pi -e "s|^proxy_ssl_ciphers.*|proxy_${NGINX_SSL_CIPHERSUITE}|g" /etc/nginx/nginx-defaults.conf
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "nginx" ] && [ ! -e ${WORKDIR}/custom/nginx/conf/nginx-defaults.conf ]; then
		perl -pi -e "s|^ssl_protocols.*|${NGINX_SSL_PROTOCOLS}|g" /etc/nginx/nginx-defaults.conf
		perl -pi -e "s|^ssl_ciphers.*|${NGINX_SSL_CIPHERSUITE}|g" /etc/nginx/nginx-defaults.conf
	fi

	if [ "${WEBSERVER_OPT}" = "openlitespeed" ] && [ ! -e ${WORKDIR}/openlitespeed/conf/httpd-vhosts.conf ]; then
		perl -pi -e "s|    sslProtocol.*|    ${OLS_SSL_PROTOCOLS}|g" /usr/local/lsws/conf/httpd-vhosts.conf
		perl -pi -e "s|    ciphers.*|    ${OLS_SSL_CIPHERSUITE}|g" /usr/local/lsws/conf/httpd-vhosts.conf
	fi
}

doSslConfigurationFtp() {
	doImportCipherSuites

	case "${SSL_CONFIGURATION_OPT_UP}" in
	MODERN)
		PROFTPD_SSL_PROTOCOLS="TLSProtocol ALL -TLSv1 -TLSv1.1 -TLSv1.2"
		PROFTPD_SSL_CIPHERSUITE=""
		PUREFTPD_SSL_CIPHERSUITE=""
	;;
	INTERMEDIATE)
		PROFTPD_SSL_PROTOCOLS="TLSProtocol ALL -TLSv1 -TLSv1.1"
		PROFTPD_SSL_CIPHERSUITE="TLSCipherSuite ${INTERMEDIATE_CIPHERSUITE}"
		PUREFTPD_SSL_CIPHERSUITE="TLSCipherSuite HIGH"
	;;
	OLD)
		PROFTPD_SSL_PROTOCOLS="TLSProtocol ALL"
		PROFTPD_SSL_CIPHERSUITE="TLSCipherSuite ${OLD_CIPHERSUITE}"
		PUREFTPD_SSL_CIPHERSUITE="TLSCipherSuite HIGH:MEDIUM:+TLSv1"
	;;
	esac

	if [ "${FTPD_OPT}" = "proftpd" ] && [ ! -e ${WORKDIR}/custom/proftpd/conf/proftpd.conf ]; then
		perl -pi -e "s|TLSCipherSuite .*|${PROFTPD_SSL_CIPHERSUITE}|g" /etc/proftpd.conf
		perl -pi -e "s|TLSProtocol .*|${PROFTPD_SSL_PROTOCOLS}|g" /etc/proftpd.conf
		if openssl x509 -in /etc/exim.cert -text -noout | grep -i 'Public Key Algorithm' | grep -q 'ecPub'; then
			perl -pi -e 's|TLSRSACertificateFile|TLSECCertificateFile|g' /etc/proftpd.conf
			perl -pi -e 's|TLSRSACertificateKeyFile|TLSECCertificateKeyFile|g' /etc/proftpd.conf
		else
			perl -pi -e 's|TLSECCertificateFile|TLSRSACertificateFile|g' /etc/proftpd.conf
			perl -pi -e 's|TLSECCertificateKeyFile|TLSRSACertificateKeyFile|g' /etc/proftpd.conf
		fi
	elif [ "${FTPD_OPT}" = "pureftpd" ] && [ ! -e ${WORKDIR}/custom/pureftpd/pure-ftpd.conf ] && [ -s /etc/pure-ftpd.conf ]; then
		perl -pi -e "s|^TLSCipherSuite.*|${PUREFTPD_SSL_CIPHERSUITE}|g" /etc/pure-ftpd.conf
	fi
}

doSslConfigurationEmail() {
	doImportCipherSuites

	case "${SSL_CONFIGURATION_OPT_UP}" in
	MODERN)
		DOVECOT_SSL_PROTOCOLS="ssl_min_protocol = TLSv1.3"
		DOVECOT_SSL_CIPHERSUITE=""
		EXIM_SSL_PROTOCOLS="openssl_options = +no_sslv2 +no_sslv3 +no_tlsv1 +no_tlsv1_1 +no_tlsv1_2 +cipher_server_preference"
		EXIM_SSL_CIPHERSUITE=""
	;;
	INTERMEDIATE)
		DOVECOT_SSL_PROTOCOLS="ssl_min_protocol = TLSv1.2"
		DOVECOT_SSL_CIPHERSUITE="ssl_cipher_list = ${INTERMEDIATE_CIPHERSUITE}"
		EXIM_SSL_PROTOCOLS="openssl_options = +no_sslv2 +no_sslv3 +no_tlsv1 +no_tlsv1_1 +cipher_server_preference"
		EXIM_SSL_CIPHERSUITE="tls_require_ciphers = ${INTERMEDIATE_CIPHERSUITE}"
	;;
	OLD)
		DOVECOT_SSL_PROTOCOLS="ssl_min_protocol = TLSv1"
		DOVECOT_SSL_CIPHERSUITE="ssl_cipher_list = ${OLD_CIPHERSUITE}"
		EXIM_SSL_PROTOCOLS="openssl_options = +no_sslv2 +no_sslv3 +cipher_server_preference"
		EXIM_SSL_CIPHERSUITE="tls_require_ciphers = ${OLD_CIPHERSUITE}"
	;;
	esac

	if [ "${DOVECOT_OPT}" = "yes" ] && [ "${DOVECOT_CONF_OPT}" = "yes" ] && [ ! -e ${WORKDIR}/custom/dovecot/conf/ssl.conf ] && [ -s /etc/dovecot/conf/ssl.conf ]; then
		perl -pi -e "s|^ssl_min_protocol.*|${DOVECOT_SSL_PROTOCOLS}|g" /etc/dovecot/conf/ssl.conf
		perl -pi -e "s|^ssl_cipher_list.*|${DOVECOT_SSL_CIPHERSUITE}|g" /etc/dovecot/conf/ssl.conf
		if [ "${SSL_CONFIGURATION_OPT}" = "old" ] && ! grep -m1 -q 'ssl_prefer_server_ciphers' /etc/dovecot/conf/ssl.conf; then
			echo 'ssl_prefer_server_ciphers = yes' >> /etc/dovecot/conf/ssl.conf
		fi
	fi
	if [ "${EXIM_OPT}" = "yes" ] && [ "${EXIMCONF_OPT}" = "yes" ] && [ -s /etc/exim.variables.conf.default ]; then
		perl -pi -e "s|^openssl_options.*|${EXIM_SSL_PROTOCOLS}|g" /etc/exim.variables.conf.default
		perl -pi -e "s|^tls_require_ciphers.*|${EXIM_SSL_CIPHERSUITE}|g" /etc/exim.variables.conf.default
	fi
}

doRewriteCLPhpHandler() {
	if [ -d /etc/container ] && [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		echo "Configuring /etc/container/php.handler..."
		sed -i "/application\/x-httpd-php/d" /etc/container/php.handler
		{
			[ "${PHP1_MODE_OPT}" = "lsphp" ] && echo "application/x-httpd-php /usr/local/bin/lsphp"
			local php_release php_short
			for php_release in "${!options_conf_php[@]}"; do
				if [ "${options_conf_php[${php_release}]}" != "lsphp" ]; then
					continue
				fi
				php_short=${php_release//./}
				echo "application/x-httpd-php${php_short} /opt/alt/php.perdir/php${php_short}/bin/lsphp"
			done
		} >> /etc/container/php.handler
	fi
}

tokenize_UnitExtProcessor(){
	# Setting up extprocessor for OLS proxy
	UnitPort=$(${DA_BIN} config-get unit_port)
	perl -pi -e "s/\|UNIT_PORT\|/${UnitPort}/g" ${LSWS_HOME}/conf/httpd-unit-extprocessor.conf
}


doRewriteConfs() {
	cd ${WORKDIR}
	#Global for all webservers
	if [ ! -d ${WWWDIR} ]; then
		mkdir -p ${WWWDIR}
		if [ "${WEBSERVER_OPT}" = "nginx" ]; then
			chown webapps:nginx /var/www
		else
			chown webapps:apache /var/www
		fi
		chmod 551 /var/www
	fi
	if [ ! -e ${WWWDIR}/index.html ] && [ ! -e ${WWWDIR}/index.htm ] && [ ! -e ${WWWDIR}/index.php ]; then
		echo "<html>webserver is functioning normally</html>" > ${WWWDIR}/index.html
	fi
	if [ "${UNIT_OPT}" = "yes" ] && [ -e /var/run/unit/control.sock ]; then
		"${DA_BIN}" taskq --run 'action=rewrite&value=nginx_unit'
	fi
	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		setupLogrotate apache
		ADMNHTTP=/usr/local/directadmin/data/users/admin/httpd.conf
		if [ ! -e ${ADMNHTTP} ] && [ -d /usr/local/directadmin/data/users/admin ]; then
			echo -n "" > ${ADMNHTTP}
			chown diradmin:admin ${ADMNHTTP}
			chmod 640 ${ADMNHTTP}
		fi	
		if [ ! -d /var/log/httpd/domains ]; then
			mkdir -p /var/log/httpd/domains
		fi
		chmod 710 /var/log/httpd
		chmod 710 /var/log/httpd/domains
		chown apache:root /var/log/httpd
		chown apache:root /var/log/httpd/domains

		if [ -e /var/www/build ]; then
			ln -sf /var/www/build /etc/httpd/build
		fi
		if [ ! -e httpd-${APACHE2_VER}.tar.gz ]; then
			safeDownloadWithMove "${WORKDIR}/httpd-${APACHE2_VER}.tar.gz" "${APACHE2_DOWNLOADURL}"
		fi
		if [ ! -e httpd-${APACHE2_VER}.tar.gz ]; then
			echo "File httpd-${APACHE2_VER}.tar.gz does not exist. Cannot rewrite configs"
		else
			tar xzf httpd-${APACHE2_VER}.tar.gz --no-same-owner
		fi

		if [ ! -d httpd-${APACHE2_VER} ]; then
			echo "Directory httpd-${APACHE2_VER} does not exist. Cannot rewrite configs"
		fi

		if [ ! -e /etc/mime.types ] && [ -e ${WORKDIR}/httpd-${APACHE2_VER}/docs/conf/mime.types ]; then
			cp ${WORKDIR}/httpd-${APACHE2_VER}/docs/conf/mime.types /etc/mime.types
		fi

		#copy the new configs
		cp -rf ${APCONFDIR} ${HTTPDDIR}
		cp -f ${APCONFDIR}/httpd.conf ${HTTPD_CONF}
		cp -f ${APCONFDIR}/extra/httpd-mpm.conf ${HTTPDCONF}/extra/httpd-mpm.conf

		perl -pi -e 's/^DefaultType/#DefaultType/' ${HTTPD_CONF}

		HDC=httpd-directories-old.conf

		ln -sf $HDC ${HTTPDCONF}/extra/httpd-directories.conf

		doApacheHostConf
		doPasswdServerStatus

		if [ "${APCUSTOMCONFDIR}" != "0" ]; then
			cp -rf ${APCUSTOMCONFDIR} ${HTTPDDIR}
		fi

		chmod 710 ${HTTPDDIR}/conf

		if [ "${HTTP_METHODS_OPT}" != "ALL" ]; then
			APACHE_HTTP_METHODS="`echo ${HTTP_METHODS_OPT} | tr ':' ' '`"
		else
			APACHE_HTTP_METHODS="reset"
		fi
		perl -pi -e "s#\|HTTP_METHODS\|#${APACHE_HTTP_METHODS}#g" ${HTTPDCONF}/extra/httpd-directories-old.conf
		perl -pi -e "s#\|HTTP_METHODS\|#${APACHE_HTTP_METHODS}#g" ${HTTPDCONF}/extra/httpd-directories-new.conf
		
		#swap the |WEBAPPS_PHP_RELEASE| token.
		if [ "${PHP1_MODE_OPT}" = "php-fpm" ] || [ "${PHP2_MODE_OPT}" = "php-fpm" ] || [ "${PHP3_MODE_OPT}" = "php-fpm" ] || [ "${PHP4_MODE_OPT}" = "php-fpm" ]; then
			PHPV=""
			if [ "${PHP1_MODE_OPT}" = "php-fpm" ]; then
				PHPV=`perl -e "print ${PHP1_RELEASE_OPT} * 10"`
			elif [ "${PHP2_RELEASE_OPT}" != "no" ]; then
				PHPV=`perl -e "print ${PHP2_RELEASE_OPT} * 10"`
			elif [ "${PHP3_RELEASE_OPT}" != "no" ]; then
				PHPV=`perl -e "print ${PHP3_RELEASE_OPT} * 10"`
			elif [ "${PHP4_RELEASE_OPT}" != "no" ]; then
				PHPV=`perl -e "print ${PHP4_RELEASE_OPT} * 10"`
			fi

			if [ "${PHPV}" != "" ]; then
				perl -pi -e "s/\|WEBAPPS_PHP_RELEASE\|/${PHPV}/" ${HTTPDCONF}/extra/${HDC}
			fi
		fi

		ensure_server_ca

		doRewriteCLPhpHandler

		do_rewrite_httpd_alias

		#rewrite ips.conf
		"${DA_BIN}" taskq --run 'action=rewrite&value=ips'

		#tokenize the IP and ports
		tokenize_IP
		tokenize_ports

		doVhosts

		if [ "${MODSECURITY_OPT}" = "yes" ]; then
			echo -n '' > /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
			echo '<IfModule mod_security3.c>' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
			echo 'modsecurity on' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
			echo 'modsecurity_rules_file /etc/nginx/nginx-modsecurity.conf' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
			create_global_modsecurity_rules
			echo 'modsecurity_rules_file /usr/local/directadmin/data/admin/modsecurity_rules' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
			echo '</IfModule>' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
			cp -pf ${MODSECURITY_APACHE_INCLUDE} /etc/httpd/conf/extra/httpd-modsecurity.conf
		else
			echo -n '' > /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
		fi

		if [ ! -d /etc/httpd/conf/ssl.key ] || [ ! -d /etc/httpd/conf/ssl.crt ]; then
			cd ${WORKDIR}
			mkdir -p /etc/httpd/conf/ssl.key
			mkdir -p /etc/httpd/conf/ssl.crt

			create_da_conf_certs || return 1
			install_file /usr/local/directadmin/conf/cacert.pem.combined  ${HTTPDCONF}/ssl.crt/server.crt 600 root:root || return 1
			install_file /usr/local/directadmin/conf/cakey.pem            ${HTTPDCONF}/ssl.key/server.key 600 root:root || return 1
			cd ${WORKDIR}
		fi

		doApacheCheck

		rm -rf ${WORKDIR}/httpd-${APACHE2_VER}

		cd ${WORKDIR}
		
		echo -n "" > ${HTTPDCONF}/extra/httpd-nginx.conf
		
		rewrite_phpmodules

		if [ "${HAVE_FCGID}" = "yes" ]; then
			if [ ! -d /usr/local/safe-bin ]; then
				mkdir -p /usr/local/safe-bin
				chmod 511 /usr/local/safe-bin
				chown apache:apache /usr/local/safe-bin
			fi

			for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
				EVAL_CHECK_VAR=HAVE_FCGID${php_shortrelease}
				if [ "${!EVAL_CHECK_VAR}" = "yes" ]; then
					doSetupFcgidSh ${php_shortrelease}
				fi
			done
		fi

		WEBMAILLINK=`get_webmail_link`
		perl -pi -e "s#Alias /webmail \"/var/www/html/roundcube/\"#Alias /webmail \"/var/www/html/${WEBMAILLINK}/\"#" /etc/httpd/conf/extra/httpd-alias.conf

		doPhpConf
		if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
			doModLsapi 0
		fi

		# Disable UserDir access if userdir_access=no is set in the options.conf file
		if [ "${USERDIR_ACCESS_OPT}" = "no" ]; then
			perl -pi -e 's#UserDir public_html#UserDir disabled#' /etc/httpd/conf/extra/httpd-vhosts.conf
			
			#~username is enabled by default for litespeed, so explicitly turn it off.
			if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
				perl -pi -e 's#^\#Include conf/extra/httpd-userdir.conf#Include conf/extra/httpd-userdir.conf#' ${HTTPD_CONF}
			fi
		else
			perl -pi -e 's#UserDir disabled#UserDir public_html#' /etc/httpd/conf/extra/httpd-vhosts.conf
			
			if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
				perl -pi -e 's#^Include conf/extra/httpd-userdir.conf#\#Include conf/extra/httpd-userdir.conf#' ${HTTPD_CONF}
			fi
		fi

		create_httpd_nginx

		doModSecurityAdj
		doSslConfigurationWebserver
		fpmChecks
		dovecotChecks

		#Rewriting httpd configuration
		if [ "${WEBSERVER_OPT}" != "nginx_apache" ]; then
			"${DA_BIN}" taskq --run 'action=rewrite&value=httpd'
		fi

		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			echo "Restarting apache."
			control_service httpd restart
		elif [ "${WEBSERVER_OPT}" = "litespeed" ]; then
			#Add CloudFlare to allow list
			if grep -m1 -q '<allow>ALL</allow>' /usr/local/lsws/conf/httpd_config.xml; then
				perl -pi -e 's|<allow>ALL</allow>|<allow>ALL, 173.245.48.0/20T, 103.21.244.0/22T, 103.22.200.0/22T, 103.31.4.0/22T, 141.101.64.0/18T, 108.162.192.0/18T, 190.93.240.0/20T, 188.114.96.0/20T, 197.234.240.0/22T, 198.41.128.0/17T, 162.158.0.0/15T, 104.16.0.0/13T, 104.24.0.0/14T, 172.64.0.0/13T, 131.0.72.0/22T, 2400:cb00::/32T, 2606:4700::/32T, 2803:f800::/32T, 2405:b500::/32T, 2405:8100::/32T, 2a06:98c0::/29T, 2c0f:f248::/32T</allow>|g' /usr/local/lsws/conf/httpd_config.xml
			fi
			if ! grep -m1 -q '<useIpInProxyHeader>' /usr/local/lsws/conf/httpd_config.xml; then
				perl -pi -e 's|<showVersionNumber>0</showVersionNumber>|<showVersionNumber>0</showVersionNumber>\n  <useIpInProxyHeader>2</useIpInProxyHeader>|g' /usr/local/lsws/conf/httpd_config.xml 
			fi
			if ! grep -m1 -q '<cgroups>' /usr/local/lsws/conf/httpd_config.xml; then 
				perl -pi -e 's|</CGIRLimit>|  <cgroups>2</cgroups>\n    </CGIRLimit>|g' /usr/local/lsws/conf/httpd_config.xml
			fi
			echo "Restarting litespeed."
			control_service litespeed reload
			#Reload detached lsphp processes
			touch /usr/local/lsws/admin/tmp/.lsphp_restart.txt
		fi
	fi
	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		if [ ! -d /var/log/httpd/domains ]; then
		mkdir -p /var/log/httpd/domains
		fi
		chmod 710 /var/log/httpd
		chmod 710 /var/log/httpd/domains
		chown apache:root /var/log/httpd
		chown apache:root /var/log/httpd/domains
		setupLogrotate apache
		#copy the new configs if needed
		if [ "`grep -m1 -c 'include' ${LSWS_HOME}/conf/directadmin-vhosts.conf`" = "0" ] || [ ! -e ${LSWS_HOME}/conf/directadmin-vhosts.conf ]; then
			cp -rf ${OPENLITESPEEDCONFDIR} ${LSWS_HOME}

			if [ "${OPENLITESPEEDCUSTOMCONFDIR}" != "0" ]; then
				cp -rf ${OPENLITESPEEDCUSTOMCONFDIR} ${LSWS_HOME}
			fi
		fi
		#copy the new configs
		cp -rf ${OPENLITESPEEDCONFDIR}/* ${LSWS_HOME}/conf

		dovecotChecks
		do_rewrite_openlitespeed_webapps
		ensure_server_ca

		#rewrite ips.conf
		"${DA_BIN}" taskq --run 'action=rewrite&value=openlitespeed'
		"${DA_BIN}" taskq --run 'action=rewrite&value=ips'

		doVhosts

		if [ ! -s ${LSWS_HOME}/ssl.key/server.key ] || [ ! -s ${LSWS_HOME}/ssl.crt/server.crt.combined ]; then
			cd ${WORKDIR}
			mkdir -p ${LSWS_HOME}/ssl.key
			mkdir -p ${LSWS_HOME}/ssl.crt
			
			#install the cert/key
			create_da_conf_certs || return 1
			install_file /usr/local/directadmin/conf/cacert.pem.combined ${LSWS_HOME}/ssl.crt/server.crt.combined 600 root:root || return 1
			install_file /usr/local/directadmin/conf/cakey.pem           ${LSWS_HOME}/ssl.key/server.key          600 root:root || return 1

			cd ${WORKDIR}
		fi

		if [ ! -e ${LSWS_HOME}/directadmin-ips.conf ]; then
			touch ${LSWS_HOME}/directadmin-ips.conf
		fi

		if [ ! -e ${LSWS_HOME}/conf/httpd-includes.conf ]; then
			touch ${LSWS_HOME}/conf/httpd-includes.conf
		fi

		if [ "${MODSECURITY_OPT}" = "yes" ]; then
			echo -n '' > ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
			echo 'module mod_security {' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
			echo 'modsecurity on' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
			echo 'modsecurity_rules_file /usr/local/lsws/conf/httpd-modsecurity.conf' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
			create_global_modsecurity_rules
			echo 'modsecurity_rules_file /usr/local/directadmin/data/admin/modsecurity_rules' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
			echo '}' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
			cp -pf ${MODSECURITY_OPENLITESPEED_INCLUDE} ${LSWS_HOME}/conf/httpd-modsecurity.conf
		else
			echo -n '' > ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
		fi

		if [ "${OPENLITESPEEDCUSTOMCONFDIR}" != "0" ]; then
			cp -rf ${OPENLITESPEEDCUSTOMCONFDIR}/* ${LSWS_HOME}/conf
		fi

		tokenize_IP
		tokenize_ports
		tokenize_UnitExtProcessor
		
		doPhpConf

		if [ "${CLOUDLINUX_OPT}" = "yes" ] && [ "${CAGEFS_OPT}" = "yes" ]; then
			OLS_ENABLELVE=2
		elif [ "${CLOUDLINUX_OPT}" = "yes" ]; then
			OLS_ENABLELVE=1
		else
			OLS_ENABLELVE=0
		fi

		if ! grep -m1 -q "^enableLVE.*=${OLS_ENABLELVE}" ${LSWS_HOME}/conf/httpd-defaults.conf; then
			perl -pi -e "s|^enableLVE.*|enableLVE                        ${OLS_ENABLELVE}|g" ${LSWS_HOME}/conf/httpd-defaults.conf
		fi

		doModSecurityAdj
		doSslConfigurationWebserver

		echo "Restarting openlitespeed."
		control_service litespeed stop >/dev/null 2>&1
		control_service litespeed start
		#Reload detached lsphp processes
		touch /usr/local/lsws/admin/tmp/.lsphp_restart.txt
	fi
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		ADMNNGINX=/usr/local/directadmin/data/users/admin/nginx.conf
		if [ ! -e ${ADMNNGINX} ] && [ -d /usr/local/directadmin/data/users/admin ]; then
			echo -n "" > ${ADMNNGINX}
			chown diradmin:admin ${ADMNNGINX}
			chmod 640 ${ADMNNGINX}
		fi

		setupLogrotate nginx
		#copy the new configs
		if [ ! -d ${NGINXCONF} ]; then
			mkdir -p ${NGINXCONF}
		fi
		cp -rf ${NGINXCONFDIR}/* ${NGINXCONF}
		if [ ! -d ${NGINXCONF}/templates ]; then
			mkdir -p ${NGINXCONF}/templates
		fi
		cp -rf ${NGINXTEMPLATESDIR}/* ${NGINXCONF}/templates

		for php_shortrelease in `echo ${PHP1_SHORTRELEASE_SET}`; do
			perl -pi -e "s|/usr/local/php${php_shortrelease}/sockets/webapps.sock|/usr/local/php${PHP1_SHORTRELEASE}/sockets/webapps.sock|" ${NGINXCONF}/nginx.conf
		done

		if [ ! -s ${NGINXCONF}/ssl.key/server.key ] || [ ! -s ${NGINXCONF}/ssl.crt/server.crt ]; then
			cd ${WORKDIR}
			mkdir -p ${NGINXCONF}/ssl.key
			mkdir -p ${NGINXCONF}/ssl.crt
			
			#install the cert/key
			create_da_conf_certs || return 1
			install_file /usr/local/directadmin/conf/cacert.pem.combined ${NGINXCONF}/ssl.crt/server.crt 600 root:root || return 1
			install_file /usr/local/directadmin/conf/cakey.pem           ${NGINXCONF}/ssl.key/server.key 600 root:root || return 1
			cd ${WORKDIR}
		fi

		do_rewrite_nginx_webapps
		ensure_server_ca

		if [ "${MODSECURITY_OPT}" = "yes" ]; then
			doModSecurityRules norestart
		fi

		#rewrite ips.conf
		"${DA_BIN}" taskq --run 'action=rewrite&value=ips'

		doVhosts

		if [ ! -e ${NGINXCONF}/directadmin-settings.conf ]; then
			touch ${NGINXCONF}/directadmin-settings.conf
		fi

		if [ ! -e ${NGINXCONF}/directadmin-ips.conf ]; then
			touch ${NGINXCONF}/directadmin-ips.conf
		fi

		if [ ! -e ${NGINXCONF}/nginx-includes.conf ]; then
			touch ${NGINXCONF}/nginx-includes.conf
		fi

		if [ "${MODSECURITY_OPT}" = "yes" ]; then
			echo -n '' > /etc/nginx/nginx-modsecurity-enable.conf
			echo 'modsecurity on;' >> /etc/nginx/nginx-modsecurity-enable.conf
			echo 'modsecurity_rules_file /etc/nginx/nginx-modsecurity.conf;' >> /etc/nginx/nginx-modsecurity-enable.conf
			create_global_modsecurity_rules
			echo 'modsecurity_rules_file /usr/local/directadmin/data/admin/modsecurity_rules;' >> /etc/nginx/nginx-modsecurity-enable.conf
			if [ "${WEBSERVER_OPT}" = "nginx" ]; then
				cp -pf ${MODSECURITY_NGINX_INCLUDE} /etc/nginx/nginx-modsecurity.conf
			elif [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
				cp -pf ${MODSECURITY_NGINX_REVERSE_INCLUDE} /etc/nginx/nginx-modsecurity.conf
			fi
		else
			echo -n '' > ${NGINXCONF}/nginx-modsecurity-enable.conf
		fi

		doSslConfigurationWebserver
		if [ "${NGINXCUSTOMCONFDIR}" != "0" ]; then
			cp -rf ${NGINXCUSTOMCONFDIR}/* ${NGINXCONF}/
		fi
		if [ "${NGINXCUSTOMEMPLATESDIR}" != "0" ]; then
			cp -rf ${NGINXCUSTOMEMPLATESDIR}/* ${NGINXCONF}/templates/
		fi

		chmod 710 ${NGINXCONF}

		doCheckIPV6
		if [ "${IPV6}" = "0" ]; then
			perl -pi -e 's| listen       \[::1\]:| #listen       \[::1\]:|' ${NGINXCONF}/nginx-vhosts.conf
			perl -pi -e 's| listen       \[::1\]:| #listen       \[::1\]:|' ${NGINXCONF}/nginx.conf
		else
			perl -pi -e 's| #listen       \[::1\]:| listen       \[::1\]:|' ${NGINXCONF}/nginx-vhosts.conf
			perl -pi -e 's| #listen       \[::1\]:| listen       \[::1\]:|' ${NGINXCONF}/nginx.conf
		fi

		tokenize_IP
		tokenize_ports

		# Disable UserDir access if userdir_access=no is set in the options.conf file
		if [ "${USERDIR_ACCESS_OPT}" = "no" ]; then
			perl -pi -e 's| include /etc/nginx/nginx-userdir.conf;| #include /etc/nginx/nginx-userdir.conf;|' /etc/nginx/nginx-vhosts.conf
		else
			perl -pi -e 's| #include /etc/nginx/nginx-userdir.conf;| include /etc/nginx/nginx-userdir.conf;|' /etc/nginx/nginx-vhosts.conf
		fi
		if [ ! -d /var/log/nginx/domains ]; then
			mkdir -p /var/log/nginx/domains
		fi

		chmod 710 /var/log/nginx
		chown nginx:root /var/log/nginx

		doPhpConf

		doModSecurityAdj

		"${DA_BIN}" taskq --run 'action=rewrite&value=nginx'

		echo "Restarting nginx."
		control_service nginx stop >/dev/null 2>&1
		control_service nginx start
	fi

	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		setVal nginx 0 ${DACONF_FILE}
		setVal nginx_proxy 1 ${DACONF_FILE}
	fi

	ensure_webapps_tmp

	doRestartDA
}

####################################################

dospamassassinCron() {
	CRONFILE=/etc/cron.${SA_UPDATE_OPT}/sa-update

	#remove bits which may exist.
	rm -f /etc/cron.daily/sa-update
	rm -f /etc/cron.weekly/sa-update
	rm -f /etc/cron.monthly/sa-update
            
	if [ "${SA_UPDATE_OPT}" != "no" ]; then
		echo "Installing sa-update cronjob..."
		if [ ! -d /etc/cron.${SA_UPDATE_OPT} ]; then
			do_exit 1 "You cannot run cronjob, because you do not have /etc/cron.${SA_UPDATE_OPT} directory."
		fi

		cp -f ${SA_UPDATE_FILE} ${CRONFILE}
		chmod 755 ${CRONFILE}
	else
		echo "${boldon}It's recommended to have sa_update set to daily in the options.conf file to get SpamAssassin rules updated every day.${boldoff}"
	fi
}

####################################################

doCron() {
	if [ "${CRON_OPT}" != "yes" ]; then
		do_exit 1 "You cannot run cronjob, because you do not have it set in options.conf file."
	fi

	if [ "${NOTIFICATIONS_OPT}" = "yes" ]; then
		echo "Cronjob is set for ${EMAIL_OPT}:"
	fi
	echo "Cronjob frequency: ${CRON_FREQUENCY_OPT}"
	echo "Automatic notifications: ${NOTIFICATIONS_OPT}"
	echo "Automatic updates: ${UPDATES_OPT}"
	if [ "${SPAMD_OPT}" = "spamassassin" ]; then
		dospamassassinCron
		echo "Automatic SpamAssassin rule updates: ${SA_UPDATE_OPT}"
	fi
}

####################################################

command_cron_execute() {
	BOLD_OPT=no
	boldon=""
	boldoff=""

	local output
	output=$(doVersions 1 | grep -F 'update is available.')
	if [ -z "${output}" ]; then
		return
	fi
	if [ "${NOTIFICATIONS_OPT}" = "yes" ]; then
		local subject count
		count=$(wc -l <<< "${output}")
		subject="${count} updates available for ${HOSTNAME}"
		if [ "${UPDATES_OPT}" = "yes" ]; then
			subject="${count} updates running for ${HOSTNAME}"
		fi
		if command -v s-nail > /dev/null; then
			s-nail -s "${subject}" "${EMAIL_OPT}" <<< "${output}"
		else
			mail -s "${subject}" "${EMAIL_OPT}" <<< "${output}"
		fi
	fi
	if [ "${UPDATES_OPT}" = "yes" ]; then
		local DA_CRON=true
		exec_with_lock doVersions 0
	elif [ "${WEBAPPS_UPDATES_OPT}" = "yes" ]; then
		doVersions 2
	fi
}

####################################################

doApache2() {
	if [ "${WEBSERVER_OPT}" != "apache" ] && [ "${WEBSERVER_OPT}" != "litespeed" ] && [ "${WEBSERVER_OPT}" != "openlitespeed" ] && [ "${WEBSERVER_OPT}" != "nginx_apache" ]; then
		do_exit 1 "You cannot install Apache, because you do not have it set in options.conf file."
	fi

	ensureBuildPackages
	install_debs libssl-dev    zlib1g-dev libsystemd-dev libexpat1-dev libnghttp2-dev   libpcre3-dev
	install_rpms openssl-devel zlib-devel systemd-devel  expat-devel   libnghttp2-devel pcre-devel
	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		install_rpms liblve-devel
	fi

	addWebappsUser
	addUserGroup apache apache
	addToAccess apache
	if grep -m1 -q '^nginx:' /etc/group; then
		usermod -a -G nginx apache 2>/dev/null
	fi

	#die die die!!
	if [ -s /usr/sbin/apache2 ]; then
		chmod 0 /usr/sbin/apache2
		pkill -x -9 apache2 2> /dev/null
	fi
	if [ -s /usr/lib/apache2/mpm-prefork/apache2 ]; then
		chmod 0 /usr/lib/apache2/mpm-prefork/apache2
		pkill -x -9 apache2 2> /dev/null
	fi

	download_with_cache "${CB_CACHE_DIR}/httpd-${APACHE2_VER}.tar.gz"     "${APACHE2_DOWNLOADURL}"  || return 1
	download_with_cache "${CB_CACHE_DIR}/apr-${APR_VER}.tar.gz"           "${APR_DOWNLOADURL}"      || return 1
	download_with_cache "${CB_CACHE_DIR}/apr-util-${APR_UTIL_VER}.tar.gz" "${APR_UTIL_DOWNLOADURL}" || return 1

	set64

	backupHttp

	echo "Extracting httpd-${APACHE2_VER}.tar.gz..."
	[ -d "${WORKDIR}/httpd-${APACHE2_VER}" ] && rm -rf "${WORKDIR}/httpd-${APACHE2_VER}"
	tar xzf "${CB_CACHE_DIR}/httpd-${APACHE2_VER}.tar.gz" -C "${WORKDIR}" --no-same-owner

	echo "Extracting apr-${APR_VER}.tar.gz..."
	mkdir -p "${WORKDIR}/httpd-${APACHE2_VER}/srclib/apr"
	tar xzf "${CB_CACHE_DIR}/apr-${APR_VER}.tar.gz" -C "${WORKDIR}/httpd-${APACHE2_VER}/srclib/apr" --strip-components=1 --no-same-owner

	echo "Extracting apr-util-${APR_UTIL_VER}.tar.gz..."
	mkdir -p "${WORKDIR}/httpd-${APACHE2_VER}/srclib/apr-util"
	tar xzf "${CB_CACHE_DIR}/apr-util-${APR_UTIL_VER}.tar.gz" -C "${WORKDIR}/httpd-${APACHE2_VER}/srclib/apr-util" --strip-components=1 --no-same-owner

	if [ "$HARDEN_SYMLINKS_PATCH_OPT" = "yes" ]; then
		echo "Patching apache for hardened symlinks patch..."
		patch -d "${WORKDIR}/httpd-${APACHE2_VER}" -p0 < ${WORKDIR}/patches/harden-symlinks-2.4.patch
	fi


	# A fix for apache not showing proxied IP address
	perl -pi -e 's#RSRC_CONF | EXEC_ON_READ#RSRC_CONF#g' "${WORKDIR}/httpd-${APACHE2_VER}/modules/metadata/mod_remoteip.c"

	#For ModSecurity
	echo "Patching srclib/apr-util/dbm/sdbm/sdbm_private.h..."
	patch -d "${WORKDIR}/httpd-${APACHE2_VER}/srclib/apr-util" -p0 < ${WORKDIR}/patches/sdbm_private.patch

	echo "Patching apache to suexec safedir path..."
	patch -d "${WORKDIR}/httpd-${APACHE2_VER}" -p1 < ${WORKDIR}/patches/suexec-safe.patch

	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		patch -d "${WORKDIR}/httpd-${APACHE2_VER}" -p1 < ${WORKDIR}/patches/cloudlinux/apr-2.4-httpd.1.patch
		patch -d "${WORKDIR}/httpd-${APACHE2_VER}" -p1 < ${WORKDIR}/patches/cloudlinux/suexec.patch
	fi

	echo "Patching suexec for per-user process grouping"
	patch -d "${WORKDIR}/httpd-${APACHE2_VER}" -p0 < ${WORKDIR}/patches/fastcgi_children_cgroup.patch

	echo "Patching apache to allow SuexecUserGroup in Directory context..."
	patch -d "${WORKDIR}/httpd-${APACHE2_VER}" -p1 < ${WORKDIR}/patches/mod_suexec_directory.patch

	# TODO check if we can drop these hacks
	echo "increasing FD_SETSIZE  .."
	if [ -e /usr/include/bits/typesizes.h ]; then
		perl -pi -e 's/__FD_SETSIZE.*1024/__FD_SETSIZE 32768/' /usr/include/bits/typesizes.h
	fi
	if [ -e /usr/include/linux/posix_types.h ]; then
		perl -pi -e 's/__FD_SETSIZE.*1024/__FD_SETSIZE 32768/' /usr/include/linux/posix_types.h
	fi
	if [ -e /usr/include/bits/types.h ]; then
		perl -pi -e 's/__FD_SETSIZE.*1024/__FD_SETSIZE 32768/' /usr/include/bits/types.h
	fi
	if [ -e "${WORKDIR}/httpd-${APACHE2_VER}/srclib/apr/include/apr.hnw" ]; then
		perl -pi -e 's/FD_SETSIZE.*1024/FD_SETSIZE 32768/' "${WORKDIR}/httpd-${APACHE2_VER}/srclib/apr/include/apr.hnw"
	fi
	if [ -e "${WORKDIR}/httpd-${APACHE2_VER}/srclib/apr/poll/unix/select.c" ]; then
		perl -pi -e 's/FD_SETSIZE.*1024/FD_SETSIZE 32768/' "${WORKDIR}/httpd-${APACHE2_VER}/srclib/apr/poll/unix/select.c"
	fi

	cd "${WORKDIR}/httpd-${APACHE2_VER}"
	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		#configure
		echo "Configuring httpd-${APACHE2_VER}"
		install_debs autoconf automake
		install_rpms autoconf automake
		rm -f configure
		autoreconf --force
		if ! grep -m1 -q 'apr_configure_args="--with-devrandom ' configure; then
			perl -pi -e 's|apr_configure_args="|apr_configure_args="--with-devrandom |g' configure
		fi
		if [ ! -e /usr/local/include/pcre.h ] && grep -m1 -q 'with-pcre=/usr/local' "${configure_scripts_active[apache]}"; then
			perl -pi -e 's|with-pcre=/usr/local|with-pcre=/usr|g' "${configure_scripts_active[apache]}"
		fi
		if ! CFLAGS="-I/usr/local/include" LDFLAGS="-L/usr/local/lib" "${configure_scripts_active[apache]}"; then
			printf "\n*** There was an error while trying to configure Apache 2. Check the %s file\n" "${configure_scripts_active[apache]}"
			do_exit 1
		fi
		echo "Done Configuration."
		echo "Trying to make Apache 2..."
		if ! C_INCLUDE_PATH=/usr/kerberos/include make -j ${CPU_CORES}; then
			do_exit 1 "*** The make has failed. Exiting..."
		fi
	fi

	checkRPMS

	#setup the directadmin.conf
	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		setVal cloud_cache 1 ${DACONF_FILE}
		"${DA_BIN}" taskq --run 'action=cache&value=showallusers'
	else
		setVal cloud_cache 0 ${DACONF_FILE}
	fi

	setVal nginx 0 ${DACONF_FILE}
	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		setVal nginx_proxy 1 ${DACONF_FILE}
		setVal litespeed 0 ${DACONF_FILE}
		setVal openlitespeed 0 ${DACONF_FILE}
		set_service litespeed delete
		pkill -x litespeed >/dev/null 2>&1
		pkill -x -9 litespeed >/dev/null 2>&1
		doRestartDA
	elif [ "${WEBSERVER_OPT}" = "apache" ]; then
		setVal nginx_proxy 0 ${DACONF_FILE}
		setVal litespeed 0 ${DACONF_FILE}
		setVal openlitespeed 0 ${DACONF_FILE}
		pkill -x nginx >/dev/null 2>&1
		pkill -x litespeed >/dev/null 2>&1
		doRestartDA
		set_service nginx delete
		set_service litespeed delete
		pkill -x -9 nginx >/dev/null 2>&1
		pkill -x -9 litespeed >/dev/null 2>&1
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			set_service httpd ON

			rm -f /usr/sbin/apxs

			echo "Installing Apache..."
			make install
	fi
	if [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		set_service httpd delete
		set_service nginx delete
	fi

	cd ${WORKDIR}

	restoreHttp

	#fix for downgrades to let $1$ passwords version of apr-utils (1.4.1) work, if 1.5.1 was installed previously.
	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ "${APR_UTIL_VER}" = "1.4.1" ]; then
			APR_51_LIB=${HTTPDDIR}/lib/libaprutil-1.so.0.5.1
			APR_41_LIB=${HTTPDDIR}/lib/libaprutil-1.so.0.4.1
			APR_LIB_LINK=${HTTPDDIR}/lib/libaprutil-1.so.0
			if [ -e "${APR_51_LIB}" ] && [ -e "${APR_41_LIB}" ]; then
				rm -f ${APR_LIB_LINK}
				rm -f ${APR_51_LIB}
				ln -s libaprutil-1.so.0.4.1 ${APR_LIB_LINK}
			fi
		fi
		#ensure /usr/sbin/apxs
		if [ ! -s /usr/sbin/apxs ] && [ -s /usr/bin/apxs ]; then
			ln -s /usr/bin/apxs /usr/sbin/apxs
		fi
				
		#fresh install, add to System Backup
		if [ ! -s ${SYSTEMDDIR}/httpd.service ]; then
			add_to_system_backup dirs /etc/httpd
		fi
			
		echo "Enabling httpd in systemd..."
		if [ -e ${CB_CUST_SYSTEMD}/httpd.service ]; then
			cp -f ${CB_CUST_SYSTEMD}/httpd.service ${SYSTEMDDIR}/httpd.service
		else
			cp -f ${CB_SYSTEMD}/httpd.service ${SYSTEMDDIR}/httpd.service
		fi
		chmod 644 ${SYSTEMDDIR}/httpd.service
		DISABLE_PRIVATETMP=false
		if [ "${CLAMAV_OPT}" = "yes" ]; then
			if [ "${SUHOSIN_PHP_UPLOADSCAN_OPT}" = "yes" ] || [ "${MODSECURITY_UPLOADSCAN_OPT}" = "yes" ]; then
				DISABLE_PRIVATETMP=true
			fi
		fi
		if [ -e /proc/1/environ ]; then
			if cat /proc/1/environ | tr '\0' '\n' | grep -q ^container=lxc; then
				DISABLE_PRIVATETMP=true
			fi
		fi
		if ${DISABLE_PRIVATETMP}; then
			echo "Upload scan option detected in options.conf. Disabling PrivateTmp feature in httpd.service for ClamAV to be able to scan files in /tmp."
			perl -pi -e 's#PrivateTmp\=true#PrivateTmp=false#' ${SYSTEMDDIR}/httpd.service
		fi
		systemctl daemon-reload
		systemctl enable httpd.service
	fi

	#Disable nginx & litespeed when switching to apache
	if [ "${WEBSERVER_OPT}" = "apache" ]; then
		if [ -e ${SYSTEMDDIR}/nginx.service ]; then
			systemctl disable nginx.service 2> /dev/null
			rm -f ${SYSTEMDDIR}/nginx.service
			systemctl daemon-reload
		fi
		if [ -e ${SYSTEMDDIR}/litespeed.service ]; then
			systemctl disable lshttpd.service 2> /dev/null
			systemctl disable litespeed.service 2> /dev/null
			systemctl disable lsws.service 2> /dev/null
			rm -f ${SYSTEMDDIR}/lshttpd.service
			rm -f ${SYSTEMDDIR}/lsws.service
			rm -f ${SYSTEMDDIR}/litespeed.service
			rm -f ${SYSTEMDDIR}/openlitespeed.service
			systemctl daemon-reload
		fi
	fi

	doRewriteConfs

	if [ ! -d /usr/local/safe-bin ]; then
		mkdir -p /usr/local/safe-bin
		chmod 511 /usr/local/safe-bin
		chown apache:apache /usr/local/safe-bin
	fi

	# Make sure apr is linked correctly
	if [ -e /usr/bin/apr-1-config ]; then
		ln -sf /usr/bin/apr-1-config /usr/bin/apr-config
	fi

	if [ "${MODSECURITY_OPT}" = "yes" ] && [ ! -e /usr/lib/apache/mod_security2.so ] && [ "${WEBSERVER_OPT}" = "apache" ]; then
		doModSecurity
	fi
	
	if [ "${HTSCANNER_OPT}" = "yes" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ]  || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			if [ "${HAVE_FCGID}" = "yes" ] || [ "${HAVE_FPM_CGI}" = "yes" ]; then
				doModHtscanner
			fi
		fi
	fi

	if [ "${HAVE_FCGID}" = "yes" ]; then
		doModFCGID
	fi

	doModProctitle 0
	doModHostingLimits 0
	doModLsapi 0 || return 1

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	ldconfig

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		echo "Restarting apache."
		control_service httpd stop
		pkill -x -9 httpd >/dev/null 2>&1
		control_service httpd start
	fi

	writeLog "Apache ${APACHE2_VER} installed"
}

####################################################

doRemoveUnit() {
	if [ "${UNIT_OPT}" = "yes" ]; then
		do_exit 1 "You cannot remove Nginx Unit, because you have it set in options.conf file."
	fi

	if [ ! -e /usr/sbin/unitd ]; then
		do_exit 1 "/usr/sbin/unitd does not exist, cannot remove..."
	fi

	echo "Disabling unit in services.status..."
	set_service unit delete

	control_service unit stop

	echo "Disabling unit in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/unit.service ]; then
		systemctl disable unit.service
		rm -f ${SYSTEMDDIR}/unit.service
		systemctl daemon-reload
	fi

	if [ -e /etc/logrotate.d/unit ]; then
		echo "Removing logrotate: /etc/logrotate.d/unit..."
		rm -f /etc/logrotate.d/unit
	fi

	if [ -d /var/log/unit ]; then
		echo "Removing unit logs: /var/log/unit..."
		rm -rf /var/log/unit
	fi

	if [ -d /var/lib/unit ]; then
		echo "Removing /var/lib/unit..."
		rm -rf /var/lib/unit
	fi

	if [ -d /usr/lib/unit ]; then
		echo "Removing /usr/lib/unit..."
		rm -rf /usr/lib/unit
	fi

	if [ -e /usr/sbin/unitd ]; then
		echo "Removing /usr/sbin/unitd..."
		rm -f /usr/sbin/unitd
	fi

	if [ -e /usr/share/man/man8/unitd.8 ]; then
		echo "Removing /usr/share/man/man8/unitd.8..."
		rm -f /usr/share/man/man8/unitd.8
	fi

	ldconfig

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "Unit has been successfully removed"
	writeLog "Unit removed"
}

####################################################

doRemoveApache2() {
	if [ "${WEBSERVER_OPT}" = "apache" ] && [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		do_exit 1 "You cannot remove Apache, because you have it set in options.conf file."
	fi

	if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		do_exit 1 "You cannot remove Apache, because you have LiteSpeed set in options.conf file, which depends on Apache configuration files."
	fi

	if [ ! -e /usr/sbin/httpd ]; then
		do_exit 1 "/usr/sbin/httpd does not exist, cannot remove..."
	fi

	echo "Disabling httpd in services.status..."
	set_service httpd delete

	control_service httpd stop

	echo "Disabling httpd in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/httpd.service ]; then
		systemctl disable httpd.service
		rm -f ${SYSTEMDDIR}/httpd.service
		systemctl daemon-reload
	fi

	if [ -e /etc/logrotate.d/apache ]; then
		echo "Removing logrotate: /etc/logrotate.d/apache..."
		rm -f /etc/logrotate.d/apache
	fi

	if [ -d /var/log/httpd ]; then
		echo "Removing httpd logs: /var/log/httpd..."
		rm -rf /var/log/httpd
	fi

	if [ -d /var/www/icons ]; then
		echo "Removing /var/www/icons..."
		rm -rf /var/www/icons
	fi

	if [ -d /var/www/cgi-bin ]; then
		echo "Removing /var/www/cgi-bin..."
		rm -rf /var/www/cgi-bin
	fi

	if [ -d /var/www/error ]; then
		echo "Removing /var/www/error..."
		rm -rf /var/www/error
	fi

	if [ -d /var/www/manual ]; then
		echo "Removing /var/www/manual..."
		rm -rf /var/www/manual
	fi

	if [ -d /usr/lib/apache ]; then
		echo "Removing /usr/lib/apache..."
		rm -rf /usr/lib/apache
	fi

	if [ -d /usr/include/apache ]; then
		echo "Removing /usr/include/apache..."
		rm -rf /usr/include/apache
	fi

	echo "Removing httpd configuration files: /etc/httpd/..."
	rm -rf /etc/httpd

	echo "Removing /usr/sbin/apachectl..."
	rm -f /usr/sbin/apachectl
	echo "Removing /usr/sbin/htcacheclean..."
	rm -f /usr/sbin/htcacheclean
	echo "Removing /usr/sbin/httpd..."
	rm -f /usr/sbin/httpd
	echo "Removing /usr/sbin/rotatelogs..."
	rm -f /usr/sbin/rotatelogs
	echo "Removing /usr/sbin/suexec..."
	rm -f /usr/sbin/suexec
	echo "Removing /usr/sbin/apxs..."
	rm -f /usr/sbin/apxs
	echo "Removing /usr/bin/ab..."
	rm -f /usr/bin/ab
	echo "Removing /usr/bin/htdbm..."
	rm -f /usr/bin/htdbm
	echo "Removing /usr/bin/htdigest..."
	rm -f /usr/bin/htdigest
	echo "Removing /usr/bin/htpasswd..."
	rm -f /usr/bin/htpasswd
	echo "Removing /usr/bin/logresolve..."
	rm -f /usr/bin/logresolve

	ldconfig

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "Apache has been successfully removed"
	writeLog "Apache removed"
}

####################################################
doLiteSpeedLicense() {
	if [ "${LITESPEED_SERIALNO_OPT}" = "trial" ]; then
		echo "LiteSpeed serial number not found. Using a trial key."
		if [ ! -e ${LITESPEED_TRIAL_KEY} ]; then
			safeDownloadWithMove "${LSWS_HOME}/conf/trial.key" https://license.litespeedtech.com/da/trial.key
		fi
		if [ ! -e ${LITESPEED_TRIAL_KEY} ] && [ ! -s ${LSWS_HOME}/conf/trial.key ]; then
			do_exit 1 "LiteSpeed trial key ${LITESPEED_TRIAL_KEY} is also not found. Exiting."
		else
			if [ ! -e ${LSWS_HOME}/conf/trial.key ]; then
				cp -f ${LITESPEED_TRIAL_KEY} ${LSWS_HOME}/conf/trial.key
			fi
		fi
	else
		echo "Writing LiteSpeed serial number ${LITESPEED_SERIALNO_OPT} to ${LSWS_HOME}/conf/serial.no..."
		echo "${LITESPEED_SERIALNO_OPT}" > ${LSWS_HOME}/conf/serial.no
	fi

	if [ -e ${LSWS_HOME}/conf/serial.no ]; then
		echo "Contacting licensing server ..."

		echo ""
		if [ -e ${LSWS_HOME}/conf/license.key ]; then
			mv -f ${LSWS_HOME}/conf/license.key ${LSWS_HOME}/conf/license.key.backup
		fi
		if [ -e ${LSWS_HOME}/conf/trial.key ]; then
			rm -f ${LSWS_HOME}/conf/trial.key
		fi
		${LSWS_HOME}/bin/lshttpd -r

		if [ $? -eq 0 ]; then
			echo "[OK] License key received."
			${LSWS_HOME}/bin/lshttpd -t
			if [ $? -eq 0 ]; then
				echo "The license key is correct."
			else
				echo "The license key received does not work."
			fi
		fi
	fi

	if [ "${1}" != "0" ]; then
		echo "Restarting litespeed."
		control_service litespeed reload
	fi
}

####################################################

doLiteSpeed() {
	if [ "${WEBSERVER_OPT}" != "litespeed" ]; then
		do_exit 1 "You cannot install LiteSpeed, because you do not have it set in options.conf file."
	fi

	if rhel_version_is 9; then
		install_rpms libxcrypt-compat
	fi

	if [ -e /usr/local/lsws/bin/lshttpd ]; then
		EXPIRED=`/usr/local/lsws/bin/lshttpd -V | grep -m1 -c expired`
		if [ ${EXPIRED} -gt 0 ]; then
			echo "Cannot install LiteSpeed, because the license is expired."
			return
		fi
	fi

	doApache2

	if [ ! -d /var/www/html ]; then
		mkdir -p /var/www/html
	fi

	set64

	addUserGroup apache apache
	addToAccess apache

	chown apache:apache /var/www
	chmod 551 /var/www

	local file="lsws-${LITESPEED_VER}-ent-x86_64-linux.tar.gz"
	if is_arm64; then
		file="lsws-${LITESPEED_VER}-ent-aarch64-linux.tar.gz"
	fi
	download_with_cache "${CB_CACHE_DIR}/${file}" "https://www.litespeedtech.com/packages/${LITESPEED_VER//.*}.0/${file}" || return 1

	echo "Extracting: ${CB_CACHE_DIR}/${file}"
	tar xzf "${CB_CACHE_DIR}/${file}" -C "${WORKDIR}" --no-same-owner || return 1

	cd "${WORKDIR}/lsws-${LITESPEED_VER}"

	if [ ! -d "${LSWS_HOME}" ]; then
		mkdir -p "${LSWS_HOME}"
		chown -R apache:apache ${LSWS_HOME}
		mkdir -p "${LSWS_HOME}/conf"
		chown -R apache:apache ${LSWS_HOME}/conf
	elif [ -d /usr/local/lsws/autoupdate ]; then
		rm -rf /usr/local/lsws/autoupdate
	fi

	#configure
	echo "Installing LiteSpeed ${LITESPEED_VER}..."

	rm -rf ./add-ons/cpanel/lsws_whm_plugin
	. ./functions.sh
	init
	export LSWS_HOME=${LSWS_HOME}
	export LSINSTALL_DIR=`pwd`
	export PHP_SUEXEC=2
	export AP_PORT_OFFSET=0
	export ADMIN_USER=admin
	export ADMIN_PASS="`random_pass`"
	if [ -e /usr/local/directadmin/data/users/admin/user.conf ]; then
		export ADMIN_EMAIL=`grep -m1 '^email=' /usr/local/directadmin/data/users/admin/user.conf | cut -d= -f2`
	fi
	if [ -e /usr/local/lsws/bin/lshttpd ]; then
		export INSTALL_TYPE="upgrade"
	else
		export INSTALL_TYPE="reinstall"
	fi
	export PHP_SUFFIX=php
	export SETUP_PHP=0
	export ADMIN_PORT=7080
	export DEFAULT_PORT=80
	export HOST_PANEL="directadmin"
	export WS_USER=apache
	export WS_GROUP=apache
	export DIR_OWN="apache:apache"
	export CONF_OWN="apache:apache"

	echo ""
	echo "Installing LiteSpeed web server, please wait... "
	echo ""

	if [ ! -s ${LSWS_HOME}/admin/conf/htpasswd ]; then
		ADMIN_PHP=${LSINSTALL_DIR}/admin/fcgi-bin/admin_php5
		if [ ! -e ${ADMIN_PHP} ]; then
			ADMIN_PHP=${LSINSTALL_DIR}/admin/fcgi-bin/admin_php
		fi
		ENCRYPT_PASS=`${ADMIN_PHP} -q ${LSINSTALL_DIR}/admin/misc/htpasswd.php "${ADMIN_PASS}"`
		echo "${ADMIN_USER}:${ENCRYPT_PASS}" > "${LSINSTALL_DIR}/admin/conf/htpasswd"
		SHOWPASSWORD=1
	else
		SHOWPASSWORD=0
	fi

	if [ -e /usr/local/lsws/bin/lshttpd ]; then
		readCurrentConfig
	fi

	configRuby
	buildApConfigFiles
	if [ ! -s ${LSWS_HOME}/admin/conf/htpasswd ]; then
		admin_login
	fi
	doRewriteConfs
	installation

	echo ""
	$LSWS_HOME/admin/misc/rc-inst.sh

	doLiteSpeedLicense 0

	setVal nginx_proxy 0 ${DACONF_FILE}
	setVal nginx 0 ${DACONF_FILE}
	setVal litespeed 1 ${DACONF_FILE}
	setVal openlitespeed 0 ${DACONF_FILE}
	pkill -x httpd >/dev/null 2>&1
	pkill -x nginx >/dev/null 2>&1
	doRestartDA
	set_service httpd delete
	set_service nginx delete
	pkill -x -9 httpd >/dev/null 2>&1
	pkill -x -9 nginx >/dev/null 2>&1

	echo "Enabling litespeed in systemd..."
	rm -f /etc/systemd/system/lshttpd.service
	rm -f /etc/systemd/system/lsws.service
	rm -f /etc/systemd/system/multi-user.target.wants/lshttpd.service
	rm -f /etc/systemd/system/multi-user.target.wants/lsws.service
	install_custom_file systemd/litespeed.service /etc/systemd/system/litespeed.service 644 root:root || return 1
	systemctl daemon-reload
	systemctl enable litespeed.service
	set_service litespeed ON

	PLUGIN_DIR=/usr/local/directadmin/plugins/litespeed_webconsole

	mkdir -p ${PLUGIN_DIR}/hooks
	mkdir -p ${PLUGIN_DIR}/admin
	mkdir -p ${PLUGIN_DIR}/images

	safeDownloadWithMove "${PLUGIN_DIR}/images/admin_icon.svg" https://www.litespeedtech.com/images/logos/lsws-icon.svg
	chmod 644 "${PLUGIN_DIR}/images/admin_icon.svg"

	echo '<a href="http://|SERVER_NAME|:7080" target="_blank">LiteSpeed WebAdmin Console</a>' > ${PLUGIN_DIR}/hooks/admin_img.html
	echo '<a href="http://|SERVER_NAME|:7080" target="_blank">LiteSpeed WebAdmin Console</a>' > ${PLUGIN_DIR}/hooks/admin_txt.html

	touch ${PLUGIN_DIR}/admin/index.html

	echo 'active=yes' > ${PLUGIN_DIR}/plugin.conf
	echo 'author=www.litespeedtech.com, Martynas Bendorius' >> ${PLUGIN_DIR}/plugin.conf
	echo 'id=litespeed' >> ${PLUGIN_DIR}/plugin.conf
	echo 'installed=yes' >> ${PLUGIN_DIR}/plugin.conf
	echo 'name=LiteSpeed WebAdmin Console' >> ${PLUGIN_DIR}/plugin.conf
	echo 'update_url=' >> ${PLUGIN_DIR}/plugin.conf
	echo 'version=0.1' >> ${PLUGIN_DIR}/plugin.conf
	echo 'version_url=' >> ${PLUGIN_DIR}/plugin.conf

	chown -R diradmin:diradmin ${PLUGIN_DIR}

	update_csf_conf

	#Disable nginx & apache when switching to litespeed
	if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		if [ -e ${SYSTEMDDIR}/nginx.service ]; then
			systemctl disable nginx.service 2> /dev/null
			rm -f ${SYSTEMDDIR}/nginx.service
			systemctl daemon-reload
		fi
		if [ -e ${SYSTEMDDIR}/httpd.service ]; then
			systemctl disable httpd.service 2> /dev/null
			rm -f ${SYSTEMDDIR}/httpd.service
			systemctl daemon-reload
		fi
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
	if [ "${CAGEFS_OPT}" = "yes" ]; then
		/usr/sbin/cagefsctl --configure-litespeed
		/usr/sbin/cagefsctl --remount-all
	fi

	if [ -d /tmp/lshttpd ]; then
		rm -rf /tmp/lshttpd
	fi

	if ! grep -m1 -q '<cgroups>' /usr/local/lsws/conf/httpd_config.xml; then 
		perl -pi -e 's|</CGIRLimit>|  <cgroups>2</cgroups>\n    </CGIRLimit>|g' /usr/local/lsws/conf/httpd_config.xml
	fi

	echo "Restarting litespeed."
	control_service litespeed reload-or-restart

	#Reload detached lsphp processes
	touch /usr/local/lsws/admin/tmp/.lsphp_restart.txt

	echo "Installation of LiteSpeed ${LITESPEED_VER} is now complete."
	echo "Admin panel address: http://${HOSTNAME}:7080. Please make sure that port 7080 is open in firewall."
	if [ "${SHOWPASSWORD}" = "1" ]; then
		if [ -e /usr/local/directadmin/scripts/setup.txt ]; then
			if ! grep -m1 -q '^litespeedadmin=' /usr/local/directadmin/scripts/setup.txt; then
				echo "litespeedadmin=${ADMIN_PASS}" >> /usr/local/directadmin/scripts/setup.txt
			fi
		fi
		echo "Admin password: ${ADMIN_PASS}"
	fi
	
	writeLog "LiteSpeed ${LITESPEED_VER} installed"
}

####################################################

doRemoveLiteSpeed() {
	if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		do_exit 1 "You cannot remove LiteSpeed, because you have it set in options.conf file."
	fi

	if [ ! -d /usr/local/lsws ]; then
		do_exit 1 "/usr/local/lsws does not exist, cannot remove..."
	fi

	echo "Disabling litespeed in services.status..."
	set_service litespeed delete

	control_service litespeed stop

	remove_directory /usr/local/directadmin/plugins/litespeed_webconsole
	remove_directory /usr/local/lsws

	echo "Disabling litespeed in systemd..."
	if [ -e ${SYSTEMDDIR}/litespeed.service ]; then
		systemctl disable lshttpd.service 2> /dev/null
		systemctl disable litespeed.service 2> /dev/null
		rm -f ${SYSTEMDDIR}/lshttpd.service
		rm -f ${SYSTEMDDIR}/litespeed.service
		rm -f ${SYSTEMDDIR}/openlitespeed.service
		systemctl daemon-reload
	fi

	ldconfig

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "LiteSpeed has been successfully removed"
	writeLog "LiteSpeed removed"
}

####################################################

add_openlitespeed_alias_redirect() {
	#A fake P real
	F=$1
	A=$2
	P=$3

	printf "\tcontext /${A}/ {\n" >> ${F}
	if [ -d /var/www/html/${P} ]; then
		printf "\t\tlocation                /var/www/html/${P}/\n" >> ${F}
	else
		printf "\t\tlocation                /var/www/html/${P}\n" >> ${F}
	fi
	printf "\t\tinclude /usr/local/lsws/conf/httpd-webapps-php.conf\n" >> ${F}
	printf "\t}\n" >> ${F}
}

add_openlitespeed_alias() {
	F=$1
	A=$2

	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		printf "\tcontext /${A}/ {\n" >> ${F}
		if [ -d /var/www/html/${A} ]; then
			printf "\t\tlocation                /var/www/html/${A}/\n" >> ${F}
		else
			printf "\t\tlocation                /var/www/html/${A}\n" >> ${F}
		fi
		printf "\t\tinclude /usr/local/lsws/conf/httpd-webapps-php.conf\n" >> ${F}
		printf "\t}\n" >> ${F}
	fi
}

do_rewrite_openlitespeed_webapps() {
	if [ -e ${WORKDIR}/custom/openlitespeed/conf/httpd-alias.conf ] && [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		cp -pf ${WORKDIR}/custom/openlitespeed/conf/httpd-alias.conf /usr/local/lsws/conf/httpd-alias.conf
	else
		NW=/usr/local/lsws/conf/httpd-alias.conf

		: > ${NW}
		
		#For let's encrypt challenges
		LETSENCRYPT=$(${DA_BIN} config-get letsencrypt)
		if [ "${LETSENCRYPT}" = "1" ]; then
			add_openlitespeed_alias ${NW} .well-known/acme-challenge
		fi
        
		if [ "${SQUIRRELMAIL_OPT}" = "yes" ]; then
			add_openlitespeed_alias ${NW} squirrelmail
		fi

		if [ "${ROUNDCUBE_OPT}" = "yes" ]; then
			add_openlitespeed_alias ${NW} roundcube
		fi

		if [ "${PHPMYADMIN_OPT}" = "yes" ]; then
			add_openlitespeed_alias ${NW} phpMyAdmin
			add_openlitespeed_alias_redirect ${NW} phpmyadmin phpMyAdmin
			add_openlitespeed_alias_redirect ${NW} pma phpMyAdmin
		fi

		WEBMAILLINK=`get_webmail_link`
		if [ -e /var/www/html/${WEBMAILLINK} ]; then
			if [ "${WEBMAILLINK}" = "webmail" ]; then
				add_openlitespeed_alias ${NW} webmail
			else
				add_openlitespeed_alias_redirect ${NW} webmail ${WEBMAILLINK}
			fi
		fi
		
		#protect other places
		printf '\tcontext /roundcube/bin/ {\n' >> ${NW}
		printf '\t\ttype                    NULL\n' >> ${NW}
  		printf '\t\tlocation                /var/www/html/roundcube/bin\n' >> ${NW}
  		printf '\t\tallowBrowse             0\n' >> ${NW}
  		printf '\t\taddDefaultCharset       off\n' >> ${NW}
		printf '\t}\n' >> ${NW}
		
		printf '\tcontext /roundcube/SQL/ {\n' >> ${NW}
		printf '\t\ttype                    NULL\n' >> ${NW}
  		printf '\t\tlocation                /var/www/html/roundcube/SQL\n' >> ${NW}
  		printf '\t\tallowBrowse             0\n' >> ${NW}
  		printf '\t\taddDefaultCharset       off\n' >> ${NW}
		printf '\t}\n' >> ${NW}
		
		printf '\tcontext /roundcube/config/ {\n' >> ${NW}
		printf '\t\ttype                    NULL\n' >> ${NW}
  		printf '\t\tlocation                /var/www/html/roundcube/config\n' >> ${NW}
  		printf '\t\tallowBrowse             0\n' >> ${NW}
  		printf '\t\taddDefaultCharset       off\n' >> ${NW}
		printf '\t}\n' >> ${NW}
		
		printf '\tcontext /roundcube/logs/ {\n' >> ${NW}
		printf '\t\ttype                    NULL\n' >> ${NW}
  		printf '\t\tlocation                /var/www/html/roundcube/logs\n' >> ${NW}
  		printf '\t\tallowBrowse             0\n' >> ${NW}
  		printf '\t\taddDefaultCharset       off\n' >> ${NW}
		printf '\t}\n' >> ${NW}
		
		printf '\tcontext /roundcube/temp/ {\n' >> ${NW}
		printf '\t\ttype                    NULL\n' >> ${NW}
  		printf '\t\tlocation                /var/www/html/roundcube/temp\n' >> ${NW}
  		printf '\t\tallowBrowse             0\n' >> ${NW}
  		printf '\t\taddDefaultCharset       off\n' >> ${NW}
		printf '\t}\n' >> ${NW}

		printf '\tcontext /phpMyAdmin/log/ {\n' >> ${NW}
		printf '\t\ttype                    NULL\n' >> ${NW}
  		printf '\t\tlocation                /var/www/html/phpMyAdmin/log\n' >> ${NW}
  		printf '\t\tallowBrowse             0\n' >> ${NW}
  		printf '\t\taddDefaultCharset       off\n' >> ${NW}
		printf '\t}\n' >> ${NW}
	fi

	if [ -s "${WEBAPPS_LIST}" ]; then
		#https://forum.directadmin.com/showthread.php?t=48203&p=247343#post247343
		echo "Adding custom webapps from ${WEBAPPS_LIST}"

		cat ${WEBAPPS_LIST} | while read l; do
			app=`echo "$l" | cut -d= -f1`
			app_path=`echo "$l" | cut -d= -f2`

			if [ "${app}" = "" ] || [ "${app_path}" = "" ]; then
				echo "${boldon}Check your ${WEBAPPS_LIST}.  A name or path is blank.${boldoff}"
				echo "name=$app"
				echo "path=$app_path"
				continue
			fi

			if [ ! -e /var/www/html/${app_path} ]; then
				echo "${boldon}Cannot find path /var/www/html/${app_path} for alias ${app}${boldoff}"
				continue
			fi

			if [ -e /var/www/html/${app} ] && [ "${app}" = "${app_path}" ]; then
				add_openlitespeed_alias ${NW} ${app}
			else
				add_openlitespeed_alias_redirect ${NW} ${app} ${app_path}
			fi
			echo "Added ${app} pointing to ${app_path}"
		done
	fi
}

doOpenLiteSpeed() {
	if [ "${WEBSERVER_OPT}" != "openlitespeed" ]; then
		do_exit 1 "You cannot install OpenLiteSpeed, because you do not have it set in options.conf file."
	fi

	if is_arm64; then
		echo "OpenLiteSpeed is not yet supported on ARM64 systems" 1>&2
		return 1
	fi

	install_rpms libnsl
	if rhel_version_is 9; then
		install_rpms libxcrypt-compat
	fi

	addWebappsUser

	safeDownloadWithMove "${WORKDIR}/openlitespeed-${OPENLITESPEED_VER}.tgz" "${OPENLITESPEED_DOWNLOADURL}"
	FILE=${WORKDIR}/openlitespeed-${OPENLITESPEED_VER}.tgz
	
	#die die die!!
	if [ -s /usr/sbin/apache2 ]; then
		chmod 0 /usr/sbin/apache2
		pkill -x -9 apache2 2> /dev/null
	fi
	if [ -s /usr/lib/apache2/mpm-prefork/apache2 ]; then
		chmod 0 /usr/lib/apache2/mpm-prefork/apache2
		pkill -x -9 apache2 2> /dev/null
	fi

	if [ ! -d /var/www/html ]; then
		mkdir -p /var/www/html
	fi

	set64

	addUserGroup lsadm lsadm
	addUserGroup apache apache
	addToAccess apache

	find /var/log/httpd -user root -exec chown apache {} \;

	cd ${WORKDIR}
	checkFile ${FILE}

	echo "Installing OpenLiteSpeed ${OPENLITESPEED_VER}..."
	if [ ! -d "${LSWS_HOME}" ]; then
		mkdir -p "${LSWS_HOME}/conf"
	elif [ -d /usr/local/lsws/autoupdate ]; then
		rm -rf /usr/local/lsws/autoupdate
	fi

	if [ -L /usr/local/lsws/admin/html ]; then
		rm -f /usr/local/lsws/admin/html
	fi

	tar xzf ${FILE} -C /usr/local/lsws/ --strip-components=1 --no-same-owner

	#setup the directadmin.conf
	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		setVal cloud_cache 1 ${DACONF_FILE}
		"${DA_BIN}" taskq --run 'action=cache&value=showallusers'
	elif [ "${CLOUDLINUX_OPT}" = "no" ]; then
		setVal cloud_cache 0 ${DACONF_FILE}
	fi

	setVal nginx 0 ${DACONF_FILE}
	setVal nginx_proxy 0 ${DACONF_FILE}
	setVal litespeed 0 ${DACONF_FILE}
	setVal openlitespeed 1 ${DACONF_FILE}
	pkill -x nginx >/dev/null 2>&1
	pkill -x litespeed >/dev/null 2>&1
	pkill -x httpd >/dev/null 2>&1
	doRestartDA
	set_service nginx delete
	set_service httpd delete
	pkill -x -9 nginx >/dev/null 2>&1
	pkill -x -9 litespeed >/dev/null 2>&1
	pkill -x -9 httpd >/dev/null 2>&1

	# Remove LiteSpeed Enterprise binary if it exists, symlink to OpenLiteSpeed
	ln -sf /usr/local/lsws/bin/openlitespeed /usr/local/lsws/bin/litespeed
	ln -sf /usr/local/lsws/bin/openlitespeed /usr/local/lsws/bin/lshttpd
	rm -f /usr/local/lsws/bin/lscgid
	cp -pf /usr/local/lsws/admin/conf/admin_config.conf.in /usr/local/lsws/admin/conf/admin_config.conf
	perl -pi -e 's|%ADMIN_PORT%|7080|g' /usr/local/lsws/admin/conf/admin_config.conf
	perl -pi -e 's|secure            0|secure            1\n  keyFile\t/usr/local/lsws/ssl.key/server.key\n  certFile\t/usr/local/lsws/ssl.crt/server.crt.combined \n  clientVerify\t0|g' /usr/local/lsws/admin/conf/admin_config.conf

	if [ -s /usr/local/lsws/admin/fcgi-bin/admin_php5 ] && [ ! -L /usr/local/lsws/admin/fcgi-bin/admin_php ]; then
		ln -sf /usr/local/lsws/admin/fcgi-bin/admin_php5 /usr/local/lsws/admin/fcgi-bin/admin_php
	fi
	if [ -d /usr/local/lsws/admin/html.open ] && [ ! -L /usr/local/lsws/admin/html ]; then
		ln -sf /usr/local/lsws/admin/html.open /usr/local/lsws/admin/html
	fi
	if [ ! -d /usr/local/lsws/admin/logs ]; then
		mkdir -p /usr/local/lsws/admin/logs
	fi
	chmod 700 /usr/local/lsws/admin/conf
	chown -R lsadm:lsadm /usr/local/lsws/admin/conf
	chmod 600 /usr/local/lsws/admin/conf/*
	if [ ! -s /usr/local/lsws/admin/conf/htpasswd ]; then
		export ADMIN_USER=admin
		export ADMIN_PASS="`random_pass`"
		ENCRYPT_PASS="`/usr/local/lsws/admin/fcgi-bin/admin_php -q /usr/local/lsws/admin/misc/htpasswd.php \"${ADMIN_PASS}\"`"
		echo "admin:${ENCRYPT_PASS}" > "/usr/local/lsws/admin/conf/htpasswd"
		SHOWPASSWORD=1
	else
		SHOWPASSWORD=0
	fi

	if [ ! -d /usr/local/lsws/admin/tmp ]; then
		mkdir -p /usr/local/lsws/admin/tmp
		chown lsadm:apache /usr/local/lsws/admin/tmp
		chmod 710 /usr/local/lsws/admin/tmp	
	fi
	chown lsadm:apache /usr/local/lsws/admin
	chmod 710 /usr/local/lsws/admin

	if [ "${MODSECURITY_OPT}" = "yes" ]; then
		if is_arm64; then
			echo "Installing ModSecurity module for OpenLiteSpeed ${OPENLITESPEED_VER}..."
			cd ./src/modules/modsecurity-ls
			gmake -f Makefile.f
			cp -fp mod_security.so /usr/local/lsws/modules/mod_security.so
			cd ${WORKDIR}/openlitespeed-${OPENLITESPEED_VER}
		fi
		echo -n '' > ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
		echo 'module mod_security {' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
		echo 'modsecurity on' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
		echo 'modsecurity_rules_file /usr/local/lsws/conf/httpd-modsecurity.conf' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
		create_global_modsecurity_rules
		echo 'modsecurity_rules_file /usr/local/directadmin/data/admin/modsecurity_rules' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
		echo '}' >> ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
		cp -pf ${MODSECURITY_OPENLITESPEED_INCLUDE} ${LSWS_HOME}/conf/httpd-modsecurity.conf
	else
		echo -n '' > ${LSWS_HOME}/conf/httpd-modsecurity-enable.conf
	fi

	#fresh install, add to System Backup
	if [ ! -s ${SYSTEMDDIR}/litespeed.service ]; then
		add_to_system_backup dirs /usr/local/lsws
	fi

	echo "Enabling openlitespeed in systemd..."
	rm -f /etc/systemd/system/lshttpd.service
	rm -f /etc/systemd/system/lsws.service
	rm -f /etc/systemd/system/multi-user.target.wants/lshttpd.service
	rm -f /etc/systemd/system/multi-user.target.wants/lsws.service
	install_custom_file systemd/openlitespeed.service ${SYSTEMDDIR}/litespeed.service 644 root:root || return 1
	systemctl daemon-reload
	systemctl enable litespeed.service
	set_service litespeed ON

	#Disable nginx & apache when switching to openlitespeed
	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		if [ -e ${SYSTEMDDIR}/nginx.service ]; then
			systemctl disable nginx.service 2> /dev/null
			rm -f ${SYSTEMDDIR}/nginx.service
			systemctl daemon-reload
		fi
		if [ -e ${SYSTEMDDIR}/httpd.service ]; then
			systemctl disable httpd.service 2> /dev/null
			rm -f ${SYSTEMDDIR}/httpd.service
			systemctl daemon-reload
		fi
	fi
	
	doRewriteConfs
	
	update_csf_conf

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
	if [ "${CAGEFS_OPT}" = "yes" ]; then
		/usr/sbin/cagefsctl --remount-all
	fi
	
	if [ "${CLOUDLINUX_OPT}" = "yes" ] && [ "${CAGEFS_OPT}" = "yes" ]; then
		OLS_ENABLELVE=2
	elif [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		OLS_ENABLELVE=1
	else
		OLS_ENABLELVE=0
	fi

	if ! grep -m1 -q "^enableLVE.*=${OLS_ENABLELVE}" ${LSWS_HOME}/conf/httpd-defaults.conf; then
		perl -pi -e "s|^enableLVE.*|enableLVE                        ${OLS_ENABLELVE}|g" ${LSWS_HOME}/conf/httpd-defaults.conf
	fi

	ldconfig

	if [ ! -d ${LSWS_HOME}/logs ]; then
		mkdir -p ${LSWS_HOME}/logs
	fi
	# lsadm owner needed for WebAdmin to work (disabled by default) + "make install" to succeed
	chown -R lsadm:lsadm /usr/local/lsws/conf
	mkdir -p ${LSWS_HOME}/cachedata
	chown apache:apache ${LSWS_HOME}/cachedata
	# chmod lsws directory 750
	if ! stat ${LSWS_HOME}/conf | grep -m1 Access | grep -m1 -q -o "\---"; then
		chmod 750 ${LSWS_HOME}/conf
	fi

	if [ -d /tmp/lshttpd ]; then
		rm -rf /tmp/lshttpd
	fi

	echo "Restarting OpenLiteSpeed."
	control_service litespeed reload

	#Reload detached lsphp processes
	touch /usr/local/lsws/admin/tmp/.lsphp_restart.txt

	echo "Installation of OpenLiteSpeed ${OPENLITESPEED_VER} is now complete."
	echo "Admin panel address: http://${HOSTNAME}:7080. Please make sure that port 7080 is open in firewall. Panel is read-only."
	if [ "${SHOWPASSWORD}" = "1" ]; then
		if [ -e /usr/local/directadmin/scripts/setup.txt ]; then
			if ! grep -m1 -q '^litespeedadmin=' /usr/local/directadmin/scripts/setup.txt; then
				echo "litespeedadmin=${ADMIN_PASS}" >> /usr/local/directadmin/scripts/setup.txt
			fi
		fi
		echo "Admin password: ${ADMIN_PASS}"
	fi

	writeLog "OpenLiteSpeed ${OPENLITESPEED_VER} installed"
}

doModSecurityAdj() {
	if [ "${MODSECURITY_OPT}" = "yes" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ]; then
			MODSECURITY_CONF_FILE=/etc/httpd/conf/extra/httpd-modsecurity.conf
			if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
				if ! grep -m1 -q '<enableCensorship>0</enableCensorship>' /usr/local/lsws/conf/httpd_config.xml; then
					perl -pi -e 's|<enableCensorship>0</enableCensorship>|<enableCensorship>1</enableCensorship>|g' /usr/local/lsws/conf/httpd_config.xml
				fi
				if ! grep -m1 -q '<uploadTmpDir>' /usr/local/lsws/conf/httpd_config.xml; then
					perl -pi -e 's|</enableCensorship>|</enableCensorship>\n      <uploadTmpDir>/tmp</uploadTmpDir>|g' /usr/local/lsws/conf/httpd_config.xml
				fi
				if ! grep -m1 -q '<secAuditLog>' /usr/local/lsws/conf/httpd_config.xml; then
					perl -pi -e 's|</enableCensorship>|</enableCensorship>\n      <secAuditLog>/var/log/httpd/modsec_audit.log</secAuditLog>|g' /usr/local/lsws/conf/httpd_config.xml
				fi
			fi
		elif [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
			MODSECURITY_CONF_FILE=/usr/local/lsws/conf/httpd-modsecurity.conf
		else
			MODSECURITY_CONF_FILE=/etc/nginx/nginx-modsecurity.conf
		fi

		if [ "${MODSECURITY_UPLOADSCAN_OPT}" = "yes" ] && [ "${CLAMAV_OPT}" = "yes" ]; then
			if [ ! -x /usr/bin/clamdscan ]; then
				doclamav
			fi
			cp -pf ${RUNAV_PL} /usr/local/bin/runav.pl
			chmod 755 /usr/local/bin/runav.pl
			cp -pf ${RUNAV_CONF} /etc/modsecurity.d/runav.conf
		else
			rm -f /usr/local/bin/runav.pl
			rm -f /etc/modsecurity.d/runav.conf
		fi

		if [ -d ${MODSECURITY_CUSTOM_RULES} ]; then
			echo "Copying custom ModSecurity rules to /etc/modsecurity.d/..."
			cp -Rpf ${MODSECURITY_CUSTOM_RULES}/* /etc/modsecurity.d/
		fi

		if [ -s /etc/modsecurity.d/000_i360_0.conf ]; then
			echo "Defaulting to Imunify 360 SecDefaultAction..."
			perl -pi -e 's|^SecDefaultAction|#SecDefaultAction|g' ${MODSECURITY_CONF_FILE}
		fi
		if [ "${MODSECURITY_RULESET_OPT}" = "comodo" ]; then
			echo "Defaulting to Comodo WAF SecDefaultAction..."
			perl -pi -e 's|^SecDefaultAction|#SecDefaultAction|g' ${MODSECURITY_CONF_FILE}
		fi
	else
		if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
			if ! grep -m1 -q '<enableCensorship>1</enableCensorship>' /usr/local/lsws/conf/httpd_config.xml; then
				perl -pi -e 's|<enableCensorship>1</enableCensorship>|<enableCensorship>0</enableCensorship>|g' /usr/local/lsws/conf/httpd_config.xml
			fi
		fi
	fi
}

####################################################

doModSecurityRules() {
	cd ${WORKDIR}

	if [ ! -d /etc/modsecurity.d ]; then
		mkdir -p /etc/modsecurity.d
	fi

	rm -f /etc/modsecurity.d/*

	if [ "${MODSECURITY_RULESET_OPT}" = "" ]; then
		echo "";
		echo "";
		echo "";
		echo "**********************";
		echo "";
		echo "The setting modsecurity_ruleset is blank. This will cause rewrite issues.";
		echo "Please set it to something, eg:";
		echo "  ./build set modsecurity_ruleset ${MODSECURITY_RULESET_DEF}";
		echo "";
		echo "**********************";
		echo "";
		echo "";
		echo "";
		sleep 5;
	fi

	if [ "${MODSECURITY_RULESET_OPT}" = "comodo" ]; then
		echo "Installing Comodo Rule Set for ModSecurity..."
		if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
			# Generate empty files, so that nginx would still be able to start
			if [ ! -e /etc/modsecurity.d/comodo_rules.conf.main ]; then
				touch /etc/modsecurity.d/comodo_rules.conf.main
			fi

			if [ ! -e /etc/modsecurity.d/comodo_rules.conf ]; then
				touch /etc/modsecurity.d/comodo_rules.conf
			fi
			safeDownloadWithMove "${WORKDIR}/cwaf_rules_nginx_3-${CWAF_RULES_VER}.tgz" "${CWAF_RULES_NGINX_DOWNLOADURL}"
			CWAF_PLATFORM=Nginx
		elif [ "${WEBSERVER_OPT}" = "litespeed" ]; then
			safeDownloadWithMove "${WORKDIR}/cwaf_rules_ls-${CWAF_RULES_VER}.tgz" "${CWAF_RULES_LS_DOWNLOADURL}"
			CWAF_PLATFORM=LiteSpeed
		else
			safeDownloadWithMove "${WORKDIR}/cwaf_rules-${CWAF_RULES_VER}.tgz" "${CWAF_RULES_DOWNLOADURL}"
			CWAF_PLATFORM=Apache
		fi
		if [ ! -e /usr/local/cwaf/scripts/updater.pl ]; then
			safeDownloadWithMove "${WORKDIR}/cwaf_client_install.sh" "https://waf.comodo.com/cpanel/cwaf_client_install.sh"
			chmod 700 cwaf_client_install.sh
			HOME=/root TERM=xterm ./cwaf_client_install.sh -- --batch --login=nologin --password=nopassword --platform=${CWAF_PLATFORM}

			#### plugin was not installed exit ###
			if [ $? -ne 0 ]; then
				rm -f cwaf_client_install.sh
				do_exit 1 "Installation of Comodo WAF plugin failed"
			fi

			cd ${WORKDIR}
			rm -f cwaf_client_install.sh
		else
			echo 'Updating to latest CWAF client version'
			/usr/local/cwaf/scripts/update-client.pl
		fi
		echo "Include /etc/cwaf/cwaf.conf" > /etc/modsecurity.d/comodo_rules.conf.main	
		
		if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
			perl -pi -e 's/cwaf_platform="Apache"/cwaf_platform="Nginx"/' /etc/cwaf/main.conf
			perl -pi -e 's/cwaf_platform="LiteSpeed"/cwaf_platform="Nginx"/' /etc/cwaf/main.conf
			/usr/local/cwaf/scripts/updater.pl -p /usr/local/directadmin/custombuild/cwaf_rules_nginx_3-${CWAF_RULES_VER}.tgz
			cd ${WORKDIR}
			rm -f cwaf_rules_nginx_3-${CWAF_RULES_VER}.tgz cwaf_rules_nginx_3
			if [ -s /etc/cwaf/cwaf.conf ]; then
				if grep -m1 -q '^IncludeOptional' /etc/cwaf/cwaf.conf; then
					perl -pi -e 's|IncludeOptional|Include|g' /etc/cwaf/cwaf.conf
				fi
			fi
		elif [ "${WEBSERVER_OPT}" = "litespeed" ]; then
			perl -pi -e 's/cwaf_platform="Nginx"/cwaf_platform="LiteSpeed"/' /etc/cwaf/main.conf
			perl -pi -e 's/cwaf_platform="Apache"/cwaf_platform="LiteSpeed"/' /etc/cwaf/main.conf
			/usr/local/cwaf/scripts/updater.pl -p /usr/local/directadmin/custombuild/cwaf_rules_ls-${CWAF_RULES_VER}.tgz
			cd ${WORKDIR}
			rm -f cwaf_rules_ls-${CWAF_RULES_VER}.tgz
		else
			perl -pi -e 's/cwaf_platform="Nginx"/cwaf_platform="Apache"/' /etc/cwaf/main.conf
			perl -pi -e 's/cwaf_platform="LiteSpeed"/cwaf_platform="Apache"/' /etc/cwaf/main.conf
			/usr/local/cwaf/scripts/updater.pl -p /usr/local/directadmin/custombuild/cwaf_rules-${CWAF_RULES_VER}.tgz
			cd ${WORKDIR}
			rm -f cwaf_rules-${CWAF_RULES_VER}.tgz
		fi
        if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
            if grep -m1 -q 'Include [0-9].' /etc/modsecurity.d/comodo_rules.conf.main; then
                sed -i '/Include \//! s/Include /Include \/usr\/local\/cwaf\/rules\//g' /etc/modsecurity.d/comodo_rules.conf.main
            fi
        fi
	fi

	if [ "${MODSECURITY_RULESET_OPT}" = "owasp" ]; then
		echo "Installing OWASP Core Rule Set for ModSecurity..."
		safeDownloadWithMove "${WORKDIR}/owasp-modsecurity-crs-${OWASP_RULES_VER}.tar.gz" "${OWASP_RULES_DOWNLOADURL}"
		tar xzf owasp-modsecurity-crs-${OWASP_RULES_VER}.tar.gz -C /etc/modsecurity.d/ owasp-modsecurity-crs-${OWASP_RULES_VER}/crs-setup.conf.example --strip-components=1 --no-same-owner
		tar xzf owasp-modsecurity-crs-${OWASP_RULES_VER}.tar.gz -C /etc/modsecurity.d/ owasp-modsecurity-crs-${OWASP_RULES_VER}/rules --strip-components=2 --no-same-owner
		echo ${OWASP_RULES_VER} > /etc/modsecurity.d/owasp_rules_version
		if [ -e /etc/modsecurity.d/crs-setup.conf.example ]; then
			mv -f /etc/modsecurity.d/crs-setup.conf.example /etc/modsecurity.d/crs-setup.conf.main
		fi
		perl -pi -e 's|^SecDefaultAction|#SecDefaultAction|' /etc/modsecurity.d/crs-setup.conf.main
	fi

	doModSecurityAdj
	echo "Installation of ModSecurity Rule Set has been finished."

	if [ ! -e /etc/modsecurity.d/comodo_rules.conf.main ]; then
		touch /etc/modsecurity.d/comodo_rules.conf.main
	fi

	if [ ! -e /etc/modsecurity.d/comodo_rules.conf ]; then
		touch /etc/modsecurity.d/comodo_rules.conf
	fi

	if [ "$1" != "norestart" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			control_service httpd restart
		fi
		if [ "${WEBSERVER_OPT}" = "nginx_apache" ] || [ "${WEBSERVER_OPT}" = "nginx" ]; then
			control_service nginx restart
		fi
		if [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
			control_service litespeed reload
		fi
	fi

	cd ${WORKDIR}
}

####################################################

doModSecsdbmutil() {
	cd ${WORKDIR}

	if [ "${MODSECURITY_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ModSecurity, because you do not have it set in options.conf file."
	fi
	ensureBuildPackages
	#We don't expect version to change, so, hardcoding it here
	MODSECSDBMUTIL_VER=1.0
	MODSECSDBMUTIL_FILENAME=modsec-sdbm-util
	
	safeDownloadWithMove "${WORKDIR}/${MODSECSDBMUTIL_FILENAME}-${MODSECSDBMUTIL_VER}.tar.gz" "${WEBPATH}/${MODSECSDBMUTIL_FILENAME}-${MODSECSDBMUTIL_VER}.tar.gz"

	FILE=${WORKDIR}/${MODSECSDBMUTIL_FILENAME}-${MODSECSDBMUTIL_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE} --no-same-owner
	cd ${MODSECSDBMUTIL_FILENAME}-${MODSECSDBMUTIL_VER}
	./autogen.sh
	echo "Configuring ${MODSECSDBMUTIL_FILENAME}-${MODSECSDBMUTIL_VER}..."
	./configure
	if [ $? -ne 0 ]; then
		printf "\n*** There was an error while trying to configure ModSecurity\n"
		do_exit 1
	fi

	echo "Done Configuration."
	echo "Trying to make ModSec-sdbm-util..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing ModSec-sdbm-util..."
	make install
	echo "ModSec-sdbm-util has been installed successfully."
	writeLog "ModSec-sdbm-util ${MODSECSDBMUTIL_VER} installed"

	cd ${WORKDIR}
}

doModSecurity() {
	cd ${WORKDIR}

	if [ "${MODSECURITY_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ModSecurity, because you do not have it set in options.conf file."
	fi

	if rhel_version_is 9; then
		install_rpms libxslt-devel compat-lua-devel yajl-devel
	else
		install_rpms libxslt-devel lua-devel yajl-devel
	fi
	install_debs libxslt-dev libyajl-dev

	if [ "${WEBSERVER_OPT}" = "apache" ]; then
		if [ ! -e /usr/sbin/apxs ]; then
			echo "/usr/sbin/apxs is not found, skipping ModSecurity for now."
			return
		fi
		if [ ! -e /usr/lib/apache/libaprutil-1.so ]; then
			echo "/usr/lib/apache/libaprutil-1.so is not found, skipping ModSecurity for now. Please run './build apache' to get the libraries in place."
			return
		fi
	elif [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		echo "ModSecurity is built-in with LiteSpeed, there is no need to install it."
	elif [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		doOpenLiteSpeed
	else
		echo "ModSecurity is not needed for Nginx, please check LibModSecurity (ModSecurity 3.0)."
		return
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ]; then
		safeDownloadWithMove "${WORKDIR}/${MODSECURITY_FILENAME}-${MODSECURITY_VER}.tar.gz" "${MODSECURITY_DOWNLOADURL}"

		FILE=${WORKDIR}/${MODSECURITY_FILENAME}-${MODSECURITY_VER}.tar.gz
		checkFile ${FILE}
		echo "Extracting ${FILE}..."

		tar xzf ${FILE} --no-same-owner
		cd ${MODSECURITY_FILENAME}-${MODSECURITY_VER}
		
		echo "Installing ${MODSECURITY_FILENAME}-${MODSECURITY_VER}..."

		if [ ! -e ./configure ]; then
			install_rpms libtool autoconf automake
			install_debs libtool autoconf automake
			echo "calling aclocal:"
			aclocal

			echo "calling libtoolize:"
			libtoolize --force

			echo "calling automake:"
			automake --add-missing

			echo "calling autoreconf:"
			autoreconf
		fi

		echo "Configuring ${MODSECURITY_FILENAME}-${MODSECURITY_VER}..."
		"${configure_scripts_active[apache_modsecurity]}"

		if [ $? -ne 0 ]; then
			printf "\n*** There was an error while trying to configure ModSecurity\n"
			do_exit 1
		fi

		echo "Done Configuration."

		echo "Trying to make ModSecurity..."
		if ! make CPPFLAGS="-I/usr/include/apache -L/usr/lib/apache  -DDEFAULT_USER='\"nginx\"' -DDEFAULT_GROUP='\"nginx\"'" CFLAGS="-I/usr/include/apache -L/usr/lib/apache -DDEFAULT_USER='\"nginx\"' -DDEFAULT_GROUP='\"nginx\"'" -j ${CPU_CORES}; then
			do_exit 1 "*** The make has failed. Exiting..."
		fi
	fi

	mkdir -p /etc/modsecurity.d
	chmod 700 /etc/modsecurity.d

	if [ "${WEBSERVER_OPT}" = "apache" ]; then
		if [ -e /usr/lib/apache/mod_security2.so ]; then
			rm -f /usr/lib/apache/mod_security2.so
		fi

		echo "Installing ModSecurity..."
		make install
	fi

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		#Add mod_security include in apache
		if [ -e ${PHPMODULES} ]; then
			perl -pi -e 's|^LoadModule security2_module|#LoadModule security2_module|' /etc/httpd/conf/httpd.conf
			if ! grep -m1 -q 'httpd-modsecurity' ${PHPMODULES}; then
				echo "Include /etc/httpd/conf/extra/httpd-modsecurity.conf" >> ${PHPMODULES}
			fi
			cp -pf ${MODSECURITY_APACHE_INCLUDE} /etc/httpd/conf/extra/httpd-modsecurity.conf
			if [ -e /usr/lib/libxml2.so ] && [ ! -e /usr/local/lib/libxml2.so ]; then
				perl -pi -e 's|LoadFile /usr/local/lib/libxml2.so|LoadFile /usr/lib/libxml2.so|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
			elif [ -e /usr/lib64/libxml2.so ] && [ ! -e /usr/local/lib/libxml2.so ]; then
				perl -pi -e 's|LoadFile /usr/local/lib/libxml2.so|LoadFile /usr/lib64/libxml2.so|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
			elif [ -e /usr/lib/x86_64-linux-gnu/libxml2.so ] && [ ! -e /usr/local/lib/libxml2.so ]; then
				perl -pi -e 's|LoadFile /usr/local/lib/libxml2.so|LoadFile /usr/lib/x86_64-linux-gnu/libxml2.so|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
			elif [ -e /usr/lib/aarch64-linux-gnu/libxml2.so ] && [ ! -e /usr/local/lib/libxml2.so ]; then
				perl -pi -e 's|LoadFile /usr/local/lib/libxml2.so|LoadFile /usr/lib/aarch64-linux-gnu/libxml2.so|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
			fi
			if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
				perl -pi -e 's|^Load|#Load|g' /etc/httpd/conf/extra/httpd-modsecurity.conf
			fi
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		if ! grep -m1 -q '<enableCensorship>0</enableCensorship>' /usr/local/lsws/conf/httpd_config.xml; then
			perl -pi -e 's|<enableCensorship>0</enableCensorship>|<enableCensorship>1</enableCensorship>|g' /usr/local/lsws/conf/httpd_config.xml
		fi
		if ! grep -m1 -q '<uploadTmpDir>' /usr/local/lsws/conf/httpd_config.xml; then
			perl -pi -e 's|</enableCensorship>|</enableCensorship>\n      <uploadTmpDir>/tmp</uploadTmpDir>|g' /usr/local/lsws/conf/httpd_config.xml
		fi
		if ! grep -m1 -q '<secAuditLog>' /usr/local/lsws/conf/httpd_config.xml; then
			perl -pi -e 's|</enableCensorship>|</enableCensorship>\n      <secAuditLog>/var/log/httpd/modsec_audit.log</secAuditLog>|g' /usr/local/lsws/conf/httpd_config.xml
		fi
	fi

	"${DA_BIN}" taskq --run 'action=rewrite&value=httpd'

	if [ -s /usr/local/modsecurity/lib/mod_security2.so ]; then
		cp -pf /usr/local/modsecurity/lib/mod_security2.so /usr/lib/apache/mod_security2.so
	fi
	echo "ModSecurity has been installed successfully."
	writeLog "ModSecurity ${MODSECURITY_VER} installed"

	#For initial comodo ruleset installation we need to restart webserver
	#So that it detects installation of modsecurity
	if [ "${MODSECURITY_RULESET_OPT}" = "comodo" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ]; then
			control_service httpd restart
		elif [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
			control_service litespeed reload
		fi
	fi

	doModSecurityRules norestart

	if [ "${WEBSERVER_OPT}" = "apache" ]; then
		control_service httpd restart
	elif [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		control_service litespeed reload
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	cd ${WORKDIR}
}

####################################################

doModSecurityConnector() {
	cd ${WORKDIR}
	ensureBuildPackages
	#For nginx we need to rebuild it, because ModSecurity is added as a static module
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		safeDownloadWithMove "${WORKDIR}/${MODSECURITY_NGINX_CONNECTOR_FILENAME}-${MODSECURITY_NGINX_CONNECTOR_VER}.tar.gz" "${MODSECURITY_NGINX_CONNECTOR_DOWNLOADURL}"
		tar xzf ${MODSECURITY_NGINX_CONNECTOR_FILENAME}-${MODSECURITY_NGINX_CONNECTOR_VER}.tar.gz
		echo -n '' > /etc/nginx/nginx-modsecurity-enable.conf
		echo 'modsecurity on;' >> /etc/nginx/nginx-modsecurity-enable.conf
		echo 'modsecurity_rules_file /etc/nginx/nginx-modsecurity.conf;' >> /etc/nginx/nginx-modsecurity-enable.conf
		create_global_modsecurity_rules
		echo 'modsecurity_rules_file /usr/local/directadmin/data/admin/modsecurity_rules;' >> /etc/nginx/nginx-modsecurity-enable.conf
		if [ -s /etc/httpd/conf/extra/nginx-modsecurity-enable.conf ]; then
			echo -n '' > /etc/httpd/conf/extra/nginx-modsecurity-enable.conf
		fi
		if nginx -V 2>&1 | grep -q -o -m1 'modsecurity-nginx-v[^ ]*'; then
			MODSECURITY_NGINX_CONNECTORV=`nginx -V 2>&1 | grep -o -m1 'modsecurity-nginx-v[^ ]*' | cut -d- -f3`
		else
			MODSECURITY_NGINX_CONNECTORV=0
		fi
		#Recompile nginx only if connector's version is different
		if [ "${MODSECURITY_NGINX_CONNECTORV}" != "${MODSECURITY_NGINX_CONNECTOR_VER}" ]; then
			if [ "$1" = "1" ]; then
				cd ${WORKDIR}
				# Build nginx to enable the module statically (./configure --add-module=../mod_security/nginx/modsecurity)
				echo "Building Nginx to enable ModSecurity module statically."
				doNginx
			fi
		fi
	elif [ "${WEBSERVER_OPT}" = "apache" ]; then
		safeDownloadWithMove "${WORKDIR}/${MODSECURITY_APACHE_CONNECTOR_FILENAME}-${MODSECURITY_APACHE_CONNECTOR_VER}.tar.gz" "${MODSECURITY_APACHE_CONNECTOR_DOWNLOADURL}"
		tar xzf ${MODSECURITY_APACHE_CONNECTOR_FILENAME}-${MODSECURITY_APACHE_CONNECTOR_VER}.tar.gz
		if [ -d "${MODSECURITY_APACHE_CONNECTOR_FILENAME}-${MODSECURITY_APACHE_CONNECTOR_VER}" ]; then
			rm -rf "${MODSECURITY_APACHE_CONNECTOR_FILENAME}-${MODSECURITY_APACHE_CONNECTOR_VER}"
		fi
		cd ${MODSECURITY_APACHE_CONNECTOR_FILENAME}-${MODSECURITY_APACHE_CONNECTOR_VER}
		./autogen.sh
		./configure
		make -j ${CPU_CORES}
		make install
		if [ -s ./src/.libs/mod_security3.so ]; then
			cp -pf ./src/.libs/mod_security3.so /usr/lib/apache/mod_security3.so
		fi
		echo -n '' > /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
		echo '<IfModule mod_security3.c>' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
		echo 'modsecurity on' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
		echo 'modsecurity_rules_file /etc/nginx/nginx-modsecurity.conf' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
		create_global_modsecurity_rules
		echo 'modsecurity_rules_file /usr/local/directadmin/data/admin/modsecurity_rules' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
		echo '</IfModule>' >> /etc/httpd/conf/extra/httpd-modsecurity-enable.conf
		cp -pf ${MODSECURITY_APACHE_INCLUDE} /etc/httpd/conf/extra/httpd-modsecurity.conf
	else
		if [ -d /etc/nginx ]; then
			echo -n '' > /etc/nginx/nginx-modsecurity-enable.conf
		fi
	fi
	if [ ! -d /etc/nginx ]; then
		mkdir -p /etc/nginx
	fi

	if [ "${WEBSERVER_OPT}" = "nginx" ]; then
		cp -pf ${MODSECURITY_NGINX_INCLUDE} /etc/nginx/nginx-modsecurity.conf
	elif [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		cp -pf ${MODSECURITY_NGINX_REVERSE_INCLUDE} /etc/nginx/nginx-modsecurity.conf
	fi
	echo "ModSecurity Connector ${MODSECURITY_NGINX_CONNECTOR_VER} is now enabled in Nginx"
}

doLibModSecurity() {
	cd ${WORKDIR}

	if [ "${MODSECURITY_OPT}" = "no" ]; then
		do_exit 1 "Cannot build ModSecurity, because you do not have it set in options.conf file."
	fi
	ensureBuildPackages
	#redirect to doModSecurity
	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		doModSecurity
		return
	fi

	if [ ! -e /usr/include/libxslt/xslt.h ] && [ ! -e /usr/local/include/libxslt/xslt.h ]; then
		echo "Cannot find libxslt, installing..."
		install_rpms libxslt-devel
		install_debs libxslt-dev
	fi

	if [ ! -e /usr/lib64/libyajl.so ] && [ ! -e /usr/lib/x86_64-linux-gnu/libyajl.so ] && [ ! -e /usr/lib/aarch64-linux-gnu/libyajl.so ] && [ ! -e /usr/local/lib/libyajl.so ]; then
		install_rpms yajl-devel
		install_debs libyajl-dev
	fi

	if [ "${WEBSERVER_OPT}" != "nginx" ] && [ "${WEBSERVER_OPT}" != "nginx_apache" ] && [ "${WEBSERVER_OPT}" != "apache" ]; then
		do_exit 1 "LibModSecurity connector is only available for nginx and apache right now."
	fi

	ldconfig

	safeDownloadWithMove "${WORKDIR}/${LIBMODSECURITY_FILENAME}-v${LIBMODSECURITY_VER}.tar.gz" "${LIBMODSECURITY_DOWNLOADURL}"

	FILE=${WORKDIR}/${LIBMODSECURITY_FILENAME}-v${LIBMODSECURITY_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE} --no-same-owner
	cd ${LIBMODSECURITY_FILENAME}-v${LIBMODSECURITY_VER}

	echo "Configuring ${LIBMODSECURITY_FILENAME}-v${LIBMODSECURITY_VER}..."
	"${configure_scripts_active[modsecurity]}"

	if [ $? -ne 0 ]; then
		printf "\n*** There was an error while trying to configure LibModSecurity\n"
		do_exit 1
	fi

	echo "Done Configuration."

	echo "Trying to make LibModSecurity..."
	if ! make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi

	mkdir -p /etc/modsecurity.d
	chmod 700 /etc/modsecurity.d

	echo "Installing LibModSecurity..."
	make install

	#For nginx we need to rebuild it, because ModSecurity is added as a static module
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ] || [ "${WEBSERVER_OPT}" = "apache" ] ; then
		if [ "$1" = "0" ]; then
			doModSecurityConnector 0
		else
			doModSecurityConnector 1
		fi
	fi

	"${DA_BIN}" taskq --run 'action=rewrite&value=httpd'

	echo "LibModSecurity has been installed successfully."
	writeLog "LibModSecurity ${LIBMODSECURITY_VER} installed"

	#For initial comodo ruleset installation we need to restart webserver
	#So that it detects installation of modsecurity
	if [ "${MODSECURITY_RULESET_OPT}" = "comodo" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ]; then
			control_service httpd restart
		elif [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
			control_service litespeed reload
		elif [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			control_service nginx restart
		fi
	fi

	doModSecurityRules norestart

	if [ "${WEBSERVER_OPT}" = "apache" ]; then
		control_service httpd restart
	elif [ "${WEBSERVER_OPT}" = "litespeed" ] || [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
			control_service litespeed reload
	elif [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		control_service nginx restart
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	cd ${WORKDIR}
}

####################################################

command_nginx_apache() {
	doApache2 || return 1
	doNginx
}

doNginx() {
	if [ "${WEBSERVER_OPT}" != "nginx" ] && [ "${WEBSERVER_OPT}" != "nginx_apache" ]; then
		do_exit 1 "You cannot install Nginx, because you do not have it set in options.conf file."
	fi
	ensureBuildPackages
	safeDownloadWithMove "${WORKDIR}/nginx-${NGINX_VER}.tar.gz" "${NGINX_DOWNLOADURL}"
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		safeDownloadWithMove "${WORKDIR}/ngx_cache_purge-${NGX_CACHE_PURGE_VER}.tar.gz" "${NGX_CACHE_PURGE_DOWNLOADURL}"
		mkdir -p ngx_cache_purge/
		tar xzf ngx_cache_purge-${NGX_CACHE_PURGE_VER}.tar.gz -C ngx_cache_purge/ --strip-components=1 --no-same-owner
	fi

	install_debs libssl-dev    libpcre2-dev zlib1g-dev
	install_rpms openssl-devel pcre2-devel  zlib-devel

	addWebappsUser

	set64

	addUserGroup nginx nginx
	addToAccess nginx

	if grep -m1 -q '^apache:' /etc/group; then
		usermod -a -G apache nginx 2>/dev/null
	fi

	cd ${WORKDIR}
	FILE=${WORKDIR}/nginx-${NGINX_VER}.tar.gz

	checkFile ${FILE}

	echo "Extracting ${FILE}..."
	tar xzf ${FILE} --no-same-owner

	cd nginx-${NGINX_VER}

	setFDSETSIZE

	local config_script=${configure_scripts_active[nginx]}
	if [ "${WEBSERVER_OPT}" == "nginx_apache" ]; then
		config_script=${configure_scripts_active[nginx_reverse]}
	fi
	MODSEC_APPENDED=0
	if [ "${MODSECURITY_OPT}" = "yes" ]; then
		if [ ! -s /usr/local/modsecurity/lib/pkgconfig/modsecurity.pc ]; then
			echo "LibModSecurity has not been installed, installing..."
			doLibModSecurity 0
		fi
		cd ${WORKDIR}/nginx-${NGINX_VER}
		MODSEC_DIR=../${MODSECURITY_NGINX_CONNECTOR_FILENAME}-${MODSECURITY_NGINX_CONNECTOR_VER}
		if [ ! -d ${MODSEC_DIR} ]; then
			cd ${WORKDIR}
			doModSecurityConnector 0
			cd nginx-${NGINX_VER}
		fi
		if ! grep -q \"\-\-add-module=${MODSEC_DIR}\" "${config_script}"; then
			MODSEC_APPENDED=1
			perl -pi -e "s#./configure \\\#./configure --add-module=${MODSEC_DIR} \\\#" "${config_script}"
		fi
	fi

	#configure
	echo "Configuring nginx-${NGINX_VER}"
	"${config_script}"

	if [ $? -ne 0 ]; then
		printf "\n*** There was an error while trying to configure Nginx. Check the %s file\n" "${config_file}"
		do_exit 1
	fi
	echo "Done Configuration."

	if [ "${MODSEC_APPENDED}" = "1" ]; then
		perl -pi -e "s#./configure --add-module=${MODSEC_DIR} \\\#./configure \\\#" "${config_file}"
	fi

	echo "increasing FD_SETSIZE in os/tpf/os.h .."
	if [ -e ./os/tpf/os.h ]; then
		perl -pi -e 's/\#define FD_SETSIZE.*2048/\#ifdef FD_SETSIZE\n\#undef FD_SETSIZE\n\#endif\n\#define FD_SETSIZE 32768/' ./os/tpf/os.h
	fi

	echo "Trying to make Nginx..."
	if ! C_INCLUDE_PATH=/usr/kerberos/include make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi

	checkRPMS

	echo "Installing Nginx..."
	control_service nginx stop >/dev/null 2>&1
	# A fix for "cp: cannot create regular file `/usr/sbin/nginx': Text file busy"
	pkill -x nginx
	sleep 2
	pkill -x -9 nginx >/dev/null 2>&1
	sleep 1

	make install

	cd ${WORKDIR}
	
	#fresh install, add to System Backup
	if [ ! -s ${SYSTEMDDIR}/nginx.service ]; then
		add_to_system_backup dirs /etc/nginx
	fi
	
	echo "Enabling nginx in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/nginx.service ]; then
		cp -f ${CB_CUST_SYSTEMD}/nginx.service ${SYSTEMDDIR}/nginx.service
	else
		cp -f ${CB_SYSTEMD}/nginx.service ${SYSTEMDDIR}/nginx.service
	fi
	chmod 644 ${SYSTEMDDIR}/nginx.service
	systemctl daemon-reload
	systemctl enable nginx.service

	#Disable httpd & litespeed, when switching to nginx
	if [ "${WEBSERVER_OPT}" = "nginx" ]; then
		if [ -e ${SYSTEMDDIR}/httpd.service ]; then
			systemctl disable httpd.service 2> /dev/null
			rm -f ${SYSTEMDDIR}/httpd.service
			systemctl daemon-reload
		fi
		if [ -e ${SYSTEMDDIR}/litespeed.service ]; then
			systemctl disable lshttpd.service 2> /dev/null
			systemctl disable litespeed.service 2> /dev/null
			rm -f ${SYSTEMDDIR}/lshttpd.service
			rm -f ${SYSTEMDDIR}/litespeed.service
			systemctl daemon-reload
		fi
	fi

	#Disable litespeed, when switching to nginx_apache
	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		if [ -e ${SYSTEMDDIR}/litespeed.service ]; then
			systemctl disable lshttpd.service 2> /dev/null
			systemctl disable litespeed.service 2> /dev/null
			rm -f ${SYSTEMDDIR}/lshttpd.service
			rm -f ${SYSTEMDDIR}/litespeed.service
			systemctl daemon-reload
		fi
	fi

	doRewriteConfs

	#setup the directadmin.conf
	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		setVal cloud_cache 1 ${DACONF_FILE}
		"${DA_BIN}" taskq --run 'action=cache&value=showallusers'
	elif [ "${CLOUDLINUX_OPT}" = "no" ]; then
		setVal cloud_cache 0 ${DACONF_FILE}
	fi

	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		setVal nginx_proxy 1 ${DACONF_FILE}
		setVal nginx 0 ${DACONF_FILE}
		setVal litespeed 0 ${DACONF_FILE}
		pkill -x litespeed >/dev/null 2>&1
		setVal openlitespeed 0 ${DACONF_FILE}
		doRestartDA
		set_service litespeed delete
		pkill -x -9 litespeed >/dev/null 2>&1
	else
		setVal nginx_proxy 0 ${DACONF_FILE}
		setVal nginx 1 ${DACONF_FILE}
		setVal litespeed 0 ${DACONF_FILE}
		setVal openlitespeed 0 ${DACONF_FILE}

		pkill -x httpd >/dev/null 2>&1
		pkill -x litespeed >/dev/null 2>&1
		doRestartDA
		set_service httpd delete
		set_service litespeed delete
		pkill -x -9 httpd >/dev/null 2>&1
		pkill -x -9 litespeed >/dev/null 2>&1
	fi

	set_service nginx ON

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "Restarting nginx."

	control_service nginx stop >/dev/null 2>&1
	control_service nginx start

	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		rm -rf ${WORKDIR}/ngx_cache_purge
	fi
	writeLog "Nginx ${NGINX_VER} installed"
}

doRemoveNginx() {
	if [ "${WEBSERVER_OPT}" = "nginx" ] && [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		do_exit 1 "You cannot remove Nginx, because you have it set in options.conf file."
	fi

	if [ ! -e /usr/sbin/nginx ]; then
		do_exit 1 "/usr/sbin/nginx does not exist, cannot remove..."
	fi

	echo "Disabling nginx in services.status..."
	set_service nginx delete

	control_service nginx stop >/dev/null 2>&1
	# A fix for "cp: cannot create regular file `/usr/sbin/nginx': Text file busy"
	sleep 2
	pkill -x -9 nginx >/dev/null 2>&1

	echo "Disabling nginx in systemd..."
	if [ -e ${SYSTEMDDIR}/nginx.service ]; then
		systemctl disable nginx.service
		rm -f ${SYSTEMDDIR}/nginx.service
		systemctl daemon-reload
	fi

	remove_file /etc/logrotate.d/nginx
	remove_file /usr/sbin/nginx
	remove_directory /var/log/nginx
	remove_directory /etc/nginx

	ldconfig

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "Nginx has been successfully removed"
	writeLog "Nginx removed"
}

####################################################
doJailshell() {
	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		echo "Please rely on CloudLinux CageFS for isolation of the users (cloudlinux=yes detected in the settings)."
		return
	elif systemd-detect-virt | grep -m1 -q -E 'lxc|openvz'; then
		if [ ! -e /dev/.lxc/proc/self/uid_map ] || cat /dev/.lxc/proc/self/uid_map >/dev/null 2>&1; then
			echo "Your container virtualization does not support Linux namespaces for user isolation, please switch to XEN/KVM/VMware or other non-container virtualization.."
			return
		fi
	fi

	if rhel_version_is 7; then
		rpm -ihf ${WEBPATH}/centos7_deps/bubblewrap-0.3.3-2.el7.x86_64.rpm
	else
		install_debs bubblewrap
		install_rpms bubblewrap
	fi

	#remove compiled msmtp if it exists
	if [ -x /usr/local/bin/msmtpd ]; then
		remove_file /usr/local/bin/msmtpd
		remove_file /usr/local/bin/msmtp
		remove_file /usr/local/share/doc/msmtp/msmtp.dvi
		remove_file /usr/local/share/doc/msmtp/msmtp.html
		remove_file /usr/local/share/info/msmtp.info
		remove_file /usr/local/share/man/man1/msmtp.1
		remove_file /usr/local/share/man/man1/msmtpd.1
		remove_file /usr/local/share/doc/msmtp/msmtp.pdf
		remove_file /usr/local/share/doc/msmtp/msmtp.ps
	fi
	install_debs msmtp
	install_rpms msmtp

	if [ ! -d /etc/exim.jail ]; then
		echo "Executing the task.queue cotents now, please be patient ..."
		 "${DA_BIN}" taskq --run 'action=rewrite&value=jail'
	fi
	if [ ! -d /usr/lib/modules ]; then
		mkdir -p /usr/lib/modules
	fi

	install_custom_file jailshell.sh /usr/bin/jailshell 755 root:root || return 1
	#enable jail=1
	if ! grep -q -m1 'jail=0' ${DACONF_FILE}; then
		setVal jail 1 ${DACONF_FILE}
		doRestartDA
	fi
	echo "/usr/bin/jailshell has been installed."
}

####################################################

doXapian() {
	cd ${WORKDIR}

	ensureBuildPackages
	install_rpms xz
	install_debs xz-utils

	safeDownloadWithMove "${WORKDIR}/xapian-core-${XAPIAN_CORE_VER}.tar.xz" "${XAPIAN_CORE_DOWNLOADURL}"

	tar xJf xapian-core-${XAPIAN_CORE_VER}.tar.xz --no-same-owner
	cd xapian-core-${XAPIAN_CORE_VER}
	./configure
	echo "Trying to make xapian-core"
	if ! make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	make install

	writeLog "xapian-core ${XAPIAN_CORE_VER} installed"
		
	cd ${WORKDIR}
}

####################################################

doFTSXapian() {
	if [ ! -x /usr/local/bin/xapian-config ]; then
		doXapian
	fi

	ensureBuildPackages
	install_rpms sqlite-devel autoconf
	install_debs libsqlite3-dev autoconf

	cd ${WORKDIR}

	safeDownloadWithMove "${WORKDIR}/fts-xapian-${FTS_XAPIAN_VER}.tar.gz" "${FTS_XAPIAN_DOWNLOADURL}"

	tar xzf fts-xapian-${FTS_XAPIAN_VER}.tar.gz --no-same-owner
	cd fts-xapian-${FTS_XAPIAN_VER}

	if [ -d /usr/lib64/dovecot ]; then
		DOVECOT_FLAG="--with-dovecot=/usr/lib64/dovecot"
	elif [ -d /usr/lib/dovecot ]; then
		DOVECOT_FLAG="--with-dovecot=/usr/lib/dovecot"
	else
		DOVECOT_FLAG=""
	fi
	
	autoreconf -i
	./configure --prefix=/usr ${DOVECOT_FLAG}
	echo "Trying to make fts-xapian ${FTS_XAPIAN_VER}"
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	make install

	if [ "${DOVECOT_CONF_OPT}" = "yes" ]; then
		cp -f ${DOVECTCONFFTS} /etc/dovecot/conf.d/90-fts-xapian.conf
		echo 'mail_plugins = $mail_plugins fts fts_xapian quota zlib' > /etc/dovecot/conf/mail_plugins.conf
	fi

	ldconfig

	cd ${WORKDIR}

	echo "Restarting dovecot."
	control_service dovecot restart
}

####################################################

doPigeonhole() {
	if [ "${PIGEONHOLE_OPT}" = "no" ]; then
		do_exit 1 "Cannot install pigeonhole, because there is no version available for Dovecot ${DOVECOT_VER}."
	fi
	ensureBuildPackages
	cd ${WORKDIR}

	safeDownloadWithMove "${WORKDIR}/dovecot-${DOVECOT_REL}-pigeonhole-${PIGEONHOLE_VER}.tar.gz" "${PIGEONHOLE_DOWNLOADURL}"

	tar xzf dovecot-${DOVECOT_REL}-pigeonhole-${PIGEONHOLE_VER}.tar.gz --no-same-owner
	cd dovecot-${DOVECOT_REL}-pigeonhole-${PIGEONHOLE_VER}

	if [ -d /usr/lib64/dovecot ]; then
		DOVECOT_FLAG="--with-dovecot=/usr/lib64/dovecot"
	elif [ -d /usr/lib/dovecot ]; then
		DOVECOT_FLAG="--with-dovecot=/usr/lib/dovecot"
	else
		DOVECOT_FLAG=""
	fi
	./configure --prefix=/usr ${DOVECOT_FLAG}
	echo "Trying to make pigeonhole ${PIGEONHOLE_VER}"
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	make install

	mkdir -p /var/lib/dovecot/sieve >/dev/null 2>&1
	touch /var/lib/dovecot/sieve/default.sieve
	sievec /var/lib/dovecot/sieve/default.sieve
	chown root:root /var/lib/dovecot/sieve/default.sieve

	perl -pi -e 's#transport = virtual_localdelivery#transport = dovecot_lmtp_udp#' /etc/exim.conf

	if [ "${DOVECOT_CONF_OPT}" = "no" ]; then
		echo "Warning: cannot enable pigeonhole in Dovecot configuration, because options.conf is set not to manage it"
	else
		cp -f ${DOVECTCONFSIEVE} /etc/dovecot/conf.d/90-sieve.conf
		echo 'protocols = imap pop3 lmtp sieve' > /etc/dovecot/conf/protocols.conf
		echo 'mail_plugins = $mail_plugins quota sieve zlib' > /etc/dovecot/conf/lmtp_mail_plugins.conf
	fi

	cd ${WORKDIR}

	echo "Restarting dovecot."
	control_service dovecot restart

	echo "Restarting exim."
	control_service exim restart
}

ensure_dovecot_dh() {
	D_SSL=/etc/dovecot/conf/ssl.conf
	SSL_DH=/etc/dovecot/dh.pem
	echo "ensuring ssl_dh for dovecot: ${SSL_DH}";

	NEED_SSL_DH=false
	if [ ! -s ${SSL_DH} ]; then
		NEED_SSL_DH=true
	fi

	if [ -s ${SSL_DH} ]; then
		DH_FILE_SIZE=`stat -c %s ${SSL_DH}`
		
		if [ "${DH_FILE_SIZE}" = "245" ]; then
			echo "${SSL_DH} is only 1024 bits.  Upgrading to 2048 bits."
			NEED_SSL_DH=true
		fi
	fi
	
	if ${NEED_SSL_DH}; then
		ensure_dhparam ${SSL_DH}

		if [ ! -s ${SSL_DH} ] && [ -s /var/lib/dovecot/ssl-parameters.dat ]; then
			#this is only 1024 bits, backup if above fails.
			dd if=/var/lib/dovecot/ssl-parameters.dat bs=1 skip=88 | openssl dh -inform der > ${SSL_DH}
		fi

		chmod 600 ${SSL_DH}
	fi

	if [ -e $D_SSL ]; then
		C=`grep -c ssl_dh ${D_SSL}`
		if [ -s ${SSL_DH} ] && [ "$C" -eq 0 ]; then
			echo "adding ssl_dh to ${D_SSL}";
			echo "ssl_dh=<${SSL_DH}" >> ${D_SSL}
		fi

		C=`grep -c ssl_protocols ${D_SSL}`
		if [ "${C}" -gt 0 ]; then
			echo "swapping ssl_protocols to be ssl_min_protocols in ${D_SSL}"
			perl -pi -e 's/^ssl_protocols = .*/ssl_min_protocol = TLSv1.1/' ${D_SSL}
		fi
	fi
}

doDovecotConf() {
	if [ "${DOVECOT_CONF_OPT}" != "yes" ]; then
		do_exit 1 "You cannot update Dovecot configuration files, because you do not have it set in options.conf file."
	fi

	echo "Updating dovecot configuration files..."
	#Enable dovecot quota by default
	COUNT=0
	if [ -e ${DACONF_FILE} ]; then
		COUNT="`grep -m1 -c -e '^add_userdb_quota=1' ${DACONF_FILE}`"
	fi
	if [ "${COUNT}" = "0" ] && [ -e ${DACONF_FILE} ]; then
		echo "Adding add_userdb_quota=1 to the ${DACONF_FILE} file to enable dovecot quota..."
		echo "add_userdb_quota=1" >> ${DACONF_FILE}
		doRestartDA
		"${DA_BIN}" taskq --run 'action=rewrite&value=email_passwd'
	fi

	if [ ! -d /etc/dovecot/conf ]; then
		mkdir -p /etc/dovecot/conf
	fi
	if [ ! -d /etc/dovecot/conf.d ]; then
		mkdir -p /etc/dovecot/conf.d
	fi

	cp -rf ${DOVECOTCONFDIR} /etc/dovecot/

	doSslConfigurationEmail

	#remove SSLv2 from dovecot config for openssl 1.1+
	OV=`openssl_version | cut -d. -f1,2`
	OPENSSL_11_OR_HIGHER=false
	if [ "${OV}" != "" ] && [ "`version_cmp ${OV} 1.1 'dovecot SSLv2 support for openssl 1.1.0 ver check'`" -ge 0 ]; then
		OPENSSL_11_OR_HIGHER=true
	fi
	if ${OPENSSL_11_OR_HIGHER}; then
		perl -pi -e 's|ssl_protocols \= !SSLv2 !SSLv3|ssl_protocols = !SSLv3|g' /etc/dovecot/conf/ssl.conf
	fi

	ensure_dovecot_dh

	doCheckIPV6
	if [ "${IPV6}" = "1" ]; then
		echo "listen = *, ::" > /etc/dovecot/conf/ip.conf
	fi

	if [ "${DOVECOTCUSTOMCONFDIR}" != "0" ]; then
		cp -rf ${DOVECOTCUSTOMCONFDIR} /etc/dovecot/
	fi

	cp -f ${DOVECTCONFFILE} /etc/dovecot/dovecot.conf
	cp -f ${DOVECTCONFQUOTA} /etc/dovecot/conf.d/90-quota.conf
	if [ "${PIGEONHOLE_OPT}" = "yes" ]; then
		cp -f ${DOVECTCONFSIEVE} /etc/dovecot/conf.d/90-sieve.conf
		echo 'protocols = imap pop3 lmtp sieve' > /etc/dovecot/conf/protocols.conf
		echo 'mail_plugins = $mail_plugins quota sieve zlib' > /etc/dovecot/conf/lmtp_mail_plugins.conf
	else
		rm -f /etc/dovecot/conf.d/90-sieve.conf
		echo 'mail_plugins = $mail_plugins quota zlib' > /etc/dovecot/conf/lmtp_mail_plugins.conf
	fi
	if [ "${MAIL_COMPRESS_OPT}" = "yes" ]; then
		cp -f ${DOVECOTCONFZLIB} /etc/dovecot/conf.d/90-zlib.conf
	else
		rm -f /etc/dovecot/conf.d/90-zlib.conf
	fi
	if [ -e /etc/dovecot/conf/lmtp.conf ]; then
		perl -pi -e "s|HOSTNAME|${HOSTNAME}|" /etc/dovecot/conf/lmtp.conf
	fi

	if [ ! -L /etc/dovecot.conf ]; then
		mv -f /etc/dovecot.conf /etc/dovecot.conf.old
		ln -s ${DOVECOT_CONFIG} /etc/dovecot.conf
	fi

	if [ ! -e /usr/lib/dovecot/lib21_fts_xapian_plugin.a ] && [ ! -e /usr/lib64/dovecot/lib21_fts_xapian_plugin.a ]; then
		echo 'mail_plugins = $mail_plugins quota zlib' > /etc/dovecot/conf/mail_plugins.conf
	else
		cp -f ${DOVECTCONFFTS} /etc/dovecot/conf.d/90-fts-xapian.conf
		echo 'mail_plugins = $mail_plugins fts fts_xapian quota zlib' > /etc/dovecot/conf/mail_plugins.conf
	fi
	echo 'mail_plugins = $mail_plugins quota imap_quota zlib' > /etc/dovecot/conf/imap_mail_plugins.conf
	
	#SSO alternate passwd file
	if [ -x ${DA_BIN} ] && [ -s ${DACONF_FILE} ]; then
		if ${DA_BIN} c | grep -m1 -q '^one_click_webmail_login=1$'; then
			safeDownloadWithMove /etc/dovecot/conf/alternate_passwd.conf "${WEBPATH_SERVICES}/all/auto_login/dovecot/alternate_passwd.conf"
		elif [ -s /etc/dovecot/conf/alternate_passwd.conf ]; then
			rm -f /etc/dovecot/conf/alternate_passwd.conf
		fi
	fi
	
	MAIL_SNI_OPT=$(${DA_BIN} config-get mail_sni)
	if [ "${MAIL_SNI_OPT}" -eq 0 ]; then
		rm -f /etc/dovecot/conf.d/95-sni.conf
	else
		if [ ! -d /etc/dovecot/conf/sni ]; then
			mkdir /etc/dovecot/conf/sni
			chmod 755 /etc/dovecot/conf/sni
			chown mail:mail /etc/dovecot/conf/sni
		fi
	
		rm -f /etc/dovecot/conf/sni/*.conf
		"${DA_BIN}" taskq --run 'action=rewrite&value=mail_sni'
		
		echo '!include_try /etc/dovecot/conf/sni/*.conf' > /etc/dovecot/conf.d/95-sni.conf
	fi	

	#If customized configs - overwrite existing ones, which we modified above
	if [ "${DOVECOTCUSTOMCONFDIR}" != "0" ]; then
		if [ -e ${DOVECOTCUSTOMCONFDIR}/protocols.conf ]; then
			cp -f ${DOVECOTCUSTOMCONFDIR}/protocols.conf /etc/dovecot/conf/protocols.conf
		fi
		if [ -e ${DOVECOTCUSTOMCONFDIR}/lmtp_mail_plugins.conf ]; then
			cp -f ${DOVECOTCUSTOMCONFDIR}/lmtp_mail_plugins.conf /etc/dovecot/conf/lmtp_mail_plugins.conf
		fi
		if [ -e ${DOVECOTCUSTOMCONFDIR}/mail_plugins.conf ]; then
			cp -f ${DOVECOTCUSTOMCONFDIR}/mail_plugins.conf /etc/dovecot/conf/mail_plugins.conf
		fi
		if [ -e ${DOVECOTCUSTOMCONFDIR}/imap_mail_plugins.conf ]; then
			cp -f ${DOVECOTCUSTOMCONFDIR}/imap_mail_plugins.conf /etc/dovecot/conf/imap_mail_plugins.conf
		fi
		if [ -e ${DOVECOTCUSTOMCONFDIR}/lmtp.conf ]; then
			cp -f ${DOVECOTCUSTOMCONFDIR}/lmtp.conf /etc/dovecot/conf/lmtp.conf
		fi
	fi

	if [ "$1" != "norestart" ]; then
		echo "Restarting dovecot."
		control_service dovecot restart
	fi

	echo "Dovecot configuration files have been updated successfully."
	writeLog "dovecot.conf installed"
}

doDovecot() {
	safeDownloadWithMove "${WORKDIR}/dovecot-${DOVECOT_VER}.tar.gz" "${DOVECOT_DOWNLOADURL}"
	if [ "${DOVECOT_OPT}" != "yes" ]; then
		do_exit 1 "You cannot install Dovecot, because you do not have it set in options.conf file."
	fi
	ensureBuildPackages
	install_debs zstd libzstd-dev
	install_rpms zstd libzstd-devel

	if [ "${DOVECOT_OPT}" = "no" ]; then
		do_exit 1 "Dovecot is not set in options.conf."
	fi

	if [ ! -e ${WORKDIR}/dovecot-${DOVECOT_VER}.tar.gz ]; then
		do_exit 1 "File dovecot-${DOVECOT_VER}.tar.gz does not exist. Try running ${boldon}./build update.${boldoff}"
	fi

	if [ -e ${DACONF_FILE} ]; then
		if ! grep -m1 -q -e '^dovecot=1' ${DACONF_FILE}; then
			echo "Adding dovecot=1 to the ${DACONF_FILE} file..."
			echo "dovecot=1" >> ${DACONF_FILE}
			set_service dovecot ON
			set_service vm-pop3d delete
			doRestartDA
		fi
	fi

	echo "Installing dovecot ${DOVECOT_VER} ..."

	addUserGroup dovecot dovecot

	cd ${WORKDIR}
	FILE=${WORKDIR}/dovecot-${DOVECOT_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ..."
	tar xzf ${FILE} --no-same-owner
	echo "Done."

	cd dovecot-${DOVECOT_VER}

	echo "Patching syslog with LOG_PID ..."

	perl -pi -e 's/LOG_NDELAY/LOG_NDELAY|LOG_PID/' src/auth/main.c
	perl -pi -e 's/LOG_NDELAY/LOG_NDELAY|LOG_PID/' src/imap/main.c
	perl -pi -e 's/LOG_NDELAY/LOG_NDELAY|LOG_PID/' src/master/main.c
	perl -pi -e 's/LOG_NDELAY/LOG_NDELAY|LOG_PID/' src/pop3/main.c

	perl -pi -e 's/LOG_NDELAY/LOG_NDELAY|LOG_PID/' src/lib-master/master-service.c

	if ! grep -m1 -q 'this should never be reached anyways' src/util/maildirlock.c; then
		echo "Patching maildirlock utility..."
		patch -p1 < ${WORKDIR}/patches/maildirlock-crash.patch
	fi

	echo "Configuring dovecot ${DOVECOT_VER} ..."
	
	"${configure_scripts_active[dovecot]}"

	if [ $? -ne 0 ]; then
		printf "\n*** There was an error while trying to configure dovecot. Please check %s file.\n" "${configure_scripts_active[dovecot]}"
		do_exit 1
	fi
	echo "Done Configuration."

	echo "Trying to make dovecot..."
	if ! make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing ..."

	make install

	touch /var/log/dovecot-lmtp.log /var/log/dovecot-lmtp-errors.log 
	chown root:root /var/log/dovecot-lmtp.log /var/log/dovecot-lmtp-errors.log
	chmod 600 /var/log/dovecot-lmtp.log /var/log/dovecot-lmtp-errors.log 
 
	cd ${WORKDIR}

	if [ ! -d /etc/dovecot ]; then
		mkdir -p /etc/dovecot
	fi

	if [ "${DOVECOT_CONF_OPT}" != "no" ]; then
		doDovecotConf norestart
	fi

	if [ ! -L /etc/dovecot.conf ]; then
		mv -f /etc/dovecot.conf /etc/dovecot.conf.old
		ln -s ${DOVECOT_CONFIG} /etc/dovecot.conf
	fi

	if [ "${PIGEONHOLE_OPT}" = "yes" ]; then
		doPigeonhole
		perl -pi -e 's#transport = virtual_localdelivery#transport = dovecot_lmtp_udp#' /etc/exim.conf
	else
		if [ -d /var/lib/dovecot/sieve ]; then
			echo "Dovecot's Sieve/Pigeonhole is not enabled, but the directroy /var/lib/dovecot/sieve exists. Removing it."
			rm -rf /var/lib/dovecot/sieve
		fi
	fi

	if [ -s /usr/lib/dovecot/lib21_fts_xapian_plugin.so ] || [ -s /usr/lib64/dovecot/lib21_fts_xapian_plugin.so ]; then
		doFTSXapian
	fi

	doCheckIPV6
	if [ "${IPV6}" = "1" ]; then
		perl -pi -e 's|^listen = \*$|#listen = \*|' ${DOVECOT_CONFIG}
		perl -pi -e 's|^#listen = \*, ::$|listen = \*, ::|' ${DOVECOT_CONFIG}
	else
		perl -pi -e 's|^#listen = \*$|listen = \*|' ${DOVECOT_CONFIG}
		perl -pi -e 's|^listen = \*, ::$|#listen = \*, ::|' ${DOVECOT_CONFIG}
	fi

	#remove SSLv2 from dovecot config for openssl 1.1+
	OV=`openssl_version | cut -d. -f1,2`
	OPENSSL_11_OR_HIGHER=false
	if [ "${OV}" != "" ] && [ "`version_cmp ${OV} 1.1 'dovecot SSLv2 support for openssl 1.1.0 ver check'`" -ge 0 ]; then
		OPENSSL_11_OR_HIGHER=true
	fi
	if ${OPENSSL_11_OR_HIGHER}; then
		perl -pi -e 's|ssl_protocols \= !SSLv2 !SSLv3|ssl_protocols = !SSLv3|g' ${DOVECOT_CONFIG}
	fi

	ensure_dovecot_dh

	# Dovecot's "make install" overwrites these scripts, so we need to re-enable them everytime
	#echo "Enabling dovecot.socket in systemd..."
	if [ -e ${SYSTEMDDIR}/dovecot.socket ]; then
		echo "Disabling dovecot.socket in systemd..."
		systemctl disable dovecot.socket 2> /dev/null
		rm -f ${SYSTEMDDIR}/dovecot.socket
		systemctl daemon-reload
	fi

	# Dovecot's "make install" overwrites these scripts, so we need to re-enable them everytime
	echo "Enabling dovecot in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/dovecot.service ]; then
		cp -f ${CB_CUST_SYSTEMD}/dovecot.service ${SYSTEMDDIR}/dovecot.service
	else
		cp -f ${CB_SYSTEMD}/dovecot.service ${SYSTEMDDIR}/dovecot.service
	fi
	chmod 644 ${SYSTEMDDIR}/dovecot.service
	systemctl daemon-reload
	systemctl enable dovecot.service
	if [ ! -e /etc/exim.cert ] || [ ! -e /etc/exim.key ]; then
		#install the cert/key
		create_da_conf_certs || return 1
		install_file /usr/local/directadmin/conf/cacert.pem.combined /etc/exim.cert 600 mail:mail || return 1
		install_file /usr/local/directadmin/conf/cakey.pem           /etc/exim.key  600 mail:mail || return 1
	fi

	if [ ! -d ${SYSTEMD_SCRIPTS}/dovecot ]; then
		mkdir -p ${SYSTEMD_SCRIPTS}/dovecot
	fi
	if [ ! -e ${SYSTEMD_SCRIPTS}/dovecot/dovecot_prestartscript ]; then
		if [ -e ${CB_CUST_SYSTEMD}/scripts/dovecot_prestartscript ]; then
			cp -f ${CB_CUST_SYSTEMD}/scripts/dovecot_prestartscript ${SYSTEMD_SCRIPTS}/dovecot/prestartscript
		else
			cp -f ${CB_SYSTEMD}/scripts/dovecot_prestartscript ${SYSTEMD_SCRIPTS}/dovecot/prestartscript
		fi
		chmod 755 ${SYSTEMD_SCRIPTS}/dovecot/prestartscript
	fi

	setupLogrotate dovecot

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	/sbin/ldconfig

	echo "Restarting dovecot."
	systemctl daemon-reload

	control_service dovecot restart
	set_service dovecot ON
	set_service vm-pop3d delete

	writeLog "Dovecot ${DOVECOT_VER} installed"
}

####################################################

doRemoveDovecot() {
	if [ "${DOVECOT_OPT}" != "no" ]; then
		do_exit 1 "Cannot remove Dovecot, because it is enabled in options.conf file."
	fi

	echo "Disabling dovecot in services.status"
	set_service dovecot delete

	control_service dovecot stop

	echo "Disabling dovecot in systemd..."

	systemctl disable dovecot.service
	rm -f ${SYSTEMDDIR}/dovecot.service
	systemctl daemon-reload

	remove_directory /usr/share/doc/dovecot
	remove_directory /etc/dovecot
	remove_directory /usr/lib/dovecot
	remove_directory /usr/lib64/dovecot
	remove_directory /usr/libexec/dovecot
	remove_directory /usr/include/dovecot
	remove_file /usr/sbin/dovecot
	remove_file /etc/dovecot.conf
	remove_file ${DOVECOT_CONFIG}

	ldconfig

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
	
	writeLog "Dovecot removed"
}

dospamassassin() {
	if [ "${SPAMD_OPT}" != "spamassassin" ]; then
		do_exit 1 "SpamAssassin is not set in options.conf."
	fi
	ensureBuildPackages

	#Install dependencies
	if [ ! -x /usr/bin/spamd ]; then
		TMPVAR="perl-Archive-Tar perl-Carp perl-DB_File perl-Data-Dumper perl-Digest-SHA perl-Encode-Detect perl-Exporter perl-File-Path perl-Getopt-Long perl-HTML-Parser perl-HTTP-Date perl-IO-Socket-SSL perl-IO-Zlib perl-Mail-DKIM perl-Mail-SPF perl-Net-DNS perl-NetAddr-IP perl-PathTools perl-Pod-Usage perl-Scalar-List-Utils perl-Socket perl-Sys-Syslog perl-Time-HiRes perl-Time-Local perl-constant perl-interpreter perl-libs perl-libwww-perl perl-version perl-DBI perl-Digest-SHA perl-ExtUtils-MakeMaker perl-IO-Socket-INET6 pyzor"
		install_rpms ${TMPVAR}
		if ! rhel_version_is 7; then
			TMPVAR="perl-Errno perl-IO"
			install_rpms ${TMPVAR}
		fi
		install_debs libhtml-parser-perl libsocket6-perl libsys-hostname-long-perl libnet-dns-perl libnetaddr-ip-perl libhttp-date-perl libmail-dkim-perl libwww-perl
	fi

	safeDownloadWithMove "${WORKDIR}/Mail-SpamAssassin-${SPAMASSASSIN_VER}.tar.gz" "${SPAMASSASSIN_DOWNLOADURL}"
	
	rm -f /etc/exim.spamassassin.conf

	if [ ! -e ${WORKDIR}/Mail-SpamAssassin-${SPAMASSASSIN_VER}.tar.gz ]; then
		do_exit 1 "File Mail-SpamAssassin-${SPAMASSASSIN_VER}.tar.gz does not exist. Try running ${boldon}./build update.${boldoff}"
	fi

	echo "Installing spamassassin ${SPAMASSASSIN_VER}..."

	cd ${WORKDIR}

	FILE=${WORKDIR}/Mail-SpamAssassin-${SPAMASSASSIN_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ..."
	tar xzf ${FILE} --no-same-owner
	echo "Done."
	cd Mail-SpamAssassin-${SPAMASSASSIN_VER}

	echo "Configuring SpamAssassin ${SPAMASSASSIN_VER}..."

	perl Makefile.PL PREFIX=/usr CONTACT_ADDRESS="the administrator of that system" RUN_NET_TESTS="no" INSTALL_BASE=""

	if [ $? -ne 0 ]; then
		printf "\n*** There was an error while trying to configure SpamAssassin.\n"
		do_exit 1
	fi

	echo "Done Configuration."

	echo "Trying to make SpamAssassin..."
	if ! make; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing ..."

	#It's not able to overwrite spamd binary sometimes, if process is still running
	pkill -x spamd >/dev/null 2>&1
	pkill -x -9 spamd >/dev/null 2>&1

	make install

	echo "Enabling spamassassin in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/spamassassin.service ]; then
		cp -f ${CB_CUST_SYSTEMD}/spamassassin.service ${SYSTEMDDIR}/spamassassin.service
	else
		cp -f ${CB_SYSTEMD}/spamassassin.service ${SYSTEMDDIR}/spamassassin.service
	fi
	chmod 644 ${SYSTEMDDIR}/spamassassin.service
	systemctl daemon-reload
	systemctl enable spamassassin.service
	
	cd ${WORKDIR}

    dospamassassinCron

	perl -pi -e 's|#.include_if_exists /etc/exim.spamassassin.conf|.include_if_exists /etc/exim.spamassassin.conf|' /etc/exim.conf

	V342PRE=/etc/mail/spamassassin/v342.pre
	if [ -s ${V342PRE} ]; then
		echo "Enabling new SA plugins"
		# loadplugin Mail::SpamAssassin::Plugin::HashBL
		perl -pi -e 's/^# loadplugin Mail::SpamAssassin::Plugin::HashBL$/loadplugin Mail::SpamAssassin::Plugin::HashBL/' ${V342PRE}
		
		# loadplugin Mail::SpamAssassin::Plugin::FromNameSpoof
		perl -pi -e 's/^# loadplugin Mail::SpamAssassin::Plugin::FromNameSpoof$/loadplugin Mail::SpamAssassin::Plugin::FromNameSpoof/' ${V342PRE}

		# loadplugin Mail::SpamAssassin::Plugin::Phishing
		perl -pi -e 's/^# loadplugin Mail::SpamAssassin::Plugin::Phishing$/loadplugin Mail::SpamAssassin::Plugin::Phishing/' ${V342PRE}
	fi

	echo "Running sa-update."
	if [ -e /usr/bin/sa-update ]; then
		/usr/bin/sa-update --nogpg --channel updates.spamassassin.org
	else
		echo "Cannot find /usr/bin/sa-update after install. Check for errors above."
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	set_service rspamd delete
	if [ -d /etc/exim/rspamd ]; then
		if [ ! -d /etc/exim/rspamd_disabled ]; then
			echo "Renaming /etc/exim/rspamd to /etc/exim/rspamd_disabled..."
			mv /etc/exim/rspamd /etc/exim/rspamd_disabled
		else
			echo "Removing old /etc/exim/rspamd directory..."
			rm -rf /etc/exim/rspamd
		fi
	fi
	echo "Starting SpamAssassin."
	systemctl restart spamassassin.service
	set_service spamd ON

	if ! grep -m1 -q '/etc/exim.spamd.conf' /etc/exim.conf; then
		perl -pi -e 's|\.include_if_exists /etc/exim\.clamav\.conf|.include_if_exists /etc/exim.spamd.conf\n  .include_if_exists /etc/exim.clamav.conf|g' /etc/exim.conf
	fi
	
	if ! grep -m1 -q '/etc/exim.spamd.load.conf' /etc/exim.conf; then
		perl -pi -e 's|\.include_if_exists /etc/exim\.clamav\.load\.conf|.include_if_exists /etc/exim.spamd.load.conf\n  .include_if_exists /etc/exim.clamav.load.conf|g' /etc/exim.conf
	fi

	# FIXME it is better to call doEximConfig instead of duplicating the code
	perl -pi -e 's|#.include_if_exists /etc/exim.spamassassin.conf|.include_if_exists /etc/exim.spamassassin.conf|' /etc/exim.conf
	install_custom_file exim/exim.spamassassin.conf /etc/exim.spamassassin.conf 644 root:root || exit 1
	rm -f /etc/exim.spamd.conf
	#disabling rspamd
	echo -n '' > /etc/exim.spamd.load.conf
	echo -n '' > /etc/exim.spamd.conf

	echo "Restarting exim."
	control_service exim restart

	ldconfig
	
	writeLog "SpamAssassin ${SPAMASSASSIN_VER} installed"
}

doRemoveSpamassassin() {
	if [ "${SPAMD_OPT}" = "spamassassin" ]; then
		do_exit 1 "Cannot remove SpamAssassin because it is enabled in options.conf."
	fi

	RESTART_EXIM=0
	if [ -e /etc/exim.spamassassin.conf ]; then
		RESTART_EXIM=1
	fi

	if [ -e ${SYSTEMDDIR}/spamassassin.service ]; then
		echo "Disabling spamassassin in systemd..."
		systemctl disable spamassassin.service
		rm -f ${SYSTEMDDIR}/spamassassin.service
		systemctl daemon-reload
	fi
	
	set_service spamd delete

	remove_directory /var/lib/spamassassin
	remove_directory /usr/share/perl5/Mail/SpamAssassin
	remove_directory /usr/lib64/perl5/auto/Mail/SpamAssassin
	remove_directory /usr/share/spamassassin
	remove_directory /etc/mail/spamassassin
	remove_directory /root/.spamassassin

	remove_file /usr/bin/spamassassin
	remove_file /usr/bin/sa-check_spamd
	remove_file /usr/bin/spamc
	remove_file /usr/bin/sa-learn
	remove_file /usr/bin/spamd
	remove_file /usr/bin/sa-awl
	remove_file /usr/bin/sa-update
	remove_file /usr/bin/sa-compile
	remove_file /etc/exim.spamassassin.conf

	#remove bits which may exist.
	remove_file /etc/cron.daily/sa-update
	remove_file /etc/cron.weekly/sa-update
	remove_file /etc/cron.monthly/sa-update
        
	ldconfig

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	if [ "${RESTART_EXIM}" = "1" ]; then
		control_service exim restart
	fi

	echo "SpamAssassin has been successfully removed"
	writeLog "SpamAssassin removed"
}

doRspamd() {
	if [ "${SPAMD_OPT}" != "rspamd" ]; then
		do_exit 1 "Rspamd is not set in options.conf."
	fi

	if distro_is_debian; then
		install_debs lsb-release
		CODENAME=`lsb_release -c -s`
		if [ ! -s /etc/apt/sources.list.d/rspamd.list ]; then
			curl ${CURL_CONNECT_OPTIONS} -o - https://rspamd.com/apt-stable/gpg.key | apt-key add -
			echo "deb [arch=amd64] https://rspamd.com/apt-stable/ $CODENAME main" > /etc/apt/sources.list.d/rspamd.list
			echo "deb-src [arch=amd64] https://rspamd.com/apt-stable/ $CODENAME main" >> /etc/apt/sources.list.d/rspamd.list
		fi
		apt-get -y update
		apt-get -y --no-install-recommends install rspamd
		if [ $? -ne 0 ]; then
			do_exit 1 "Apt-get failed to install rspamd."
		fi
	else
		if [ ! -s /etc/yum.repos.d/rspamd.repo ]; then
			RSPAMD_REPO_URL="https://rspamd.com/rpm-stable/centos-$(rhel_version)/rspamd.repo"
			if ! curl --silent --fail ${RSPAMD_REPO_URL}; then
				do_exit 1 "Cannot download rspamd repo file ${RSPAMD_REPO_URL}." 
			fi
			safeDownloadWithMove "/etc/yum.repos.d/rspamd.repo" "${RSPAMD_REPO_URL}"
			rpm --import https://rspamd.com/rpm-stable/gpg.key
		fi
		yum -y install rspamd
		if [ $? -ne 0 ]; then
			do_exit 1 "Yum failed to install rspamd."
		fi
	fi

	#Add _rspamd user/group if it doesn't exist after installation
	addUserGroup _rspamd _rspamd

	if [ ! -x /usr/bin/redis-server ] && [ ! -x /usr/local/bin/redis-server ]; then
		if [ "${REDIS_OPT}" = "no" ]; then
			command_set redis yes
			REDIS_OPT="yes"
		fi
		doRedis
	else
		echo "Enabling redis-rspamd in systemd..."
		if [ -e ${CB_CUST_SYSTEMD}/redis-rspamd.service ]; then
			cp -f ${CB_CUST_SYSTEMD}/redis-rspamd.service ${SYSTEMDDIR}/redis-rspamd.service
		else
			cp -f ${CB_SYSTEMD}/redis-rspamd.service ${SYSTEMDDIR}/redis-rspamd.service
		fi
		chmod 644 ${SYSTEMDDIR}/redis-rspamd.service
		systemctl daemon-reload
		systemctl enable --now redis-rspamd
	fi

	#disable greylisting by default, as no redis server back-end (yet?).
	if [ ! -e /etc/rspamd/local.d/greylist.conf ]; then
		if [ ! -d /etc/rspamd/local.d ]; then
			mkdir /etc/rspamd/local.d
			chmod 755 /etc/rspamd/local.d
		fi
		
		echo "enabled = false;" > /etc/rspamd/local.d/greylist.conf
	fi

	#copy custom configs here? TODO
	#end custom configs

	echo "Enabling rspamd in systemd..."
	if [ -e ${SYSTEMDDIR}/rspamd.service ]; then
		systemctl enable rspamd.service
		if [ -e ${SYSTEMDDIR}/spamassassin.service ]; then
			systemctl stop spamassassin.service
			systemctl disable spamassassin.service
			rm -f ${SYSTEMDDIR}/spamassassin.service
			systemctl daemon-reload
		fi		
	fi
	
	set_service spamd delete
	
	if [ -e /usr/bin/spamd ]; then
		doRemoveSpamassassin
	fi

	pkill -x -9 spamd >/dev/null 2>&1
	
	cd ${WORKDIR}

	mkdir -p /var/log/rspamd
	
	if [ ! -d /etc/rspamd/local.d ]; then
		mkdir -p /etc/rspamd/local.d
		chmod 755 /etc/rspamd/local.d
	fi

	echo 'servers = "/var/lib/rspamd/.redis/redis.sock";' > /etc/rspamd/local.d/redis.conf

	#set permissions
	if [ -e /etc/rspamd/local.d/settings.conf ]; then
		if ! grep -m1 -q ".include \"\$CONFDIR/directadmin-users.conf\"" /etc/rspamd/local.d/settings.conf; then
			echo ".include \"\$CONFDIR/directadmin-users.conf\"" >> /etc/rspamd/local.d/settings.conf
		fi
	else
		echo ".include \"\$CONFDIR/directadmin-users.conf\"" > /etc/rspamd/local.d/settings.conf
	fi

	#listen on UDS instead of localhost TCP/IP
	if [ -e /etc/rspamd/local.d/worker-normal.inc ]; then
		sed -i '/bind_socket =/d' /etc/rspamd/local.d/worker-normal.inc
		echo 'bind_socket = "localhost:11333";' >> /etc/rspamd/local.d/worker-normal.inc
	else
		echo 'bind_socket = "localhost:11333";' > /etc/rspamd/local.d/worker-normal.inc
	fi

	#listen on UDS instead of localhost TCP/IP
	if [ -e /etc/rspamd/local.d/worker-controller.inc ]; then
		sed -i '/bind_socket =/d' /etc/rspamd/local.d/worker-controller.inc
		echo 'bind_socket = "/var/run/rspamd/rspamd_controller.sock mode=0600 owner=_rspamd";' >> /etc/rspamd/local.d/worker-controller.inc
	else
		echo 'bind_socket = "/var/run/rspamd/rspamd_controller.sock mode=0600 owner=_rspamd";' > /etc/rspamd/local.d/worker-controller.inc
	fi

	#listen on UDS instead of localhost TCP/IP
	if [ -e /etc/rspamd/local.d/worker-proxy.inc ]; then
		sed -i '/bind_socket =/d' /etc/rspamd/local.d/worker-proxy.inc
		echo 'bind_socket = "/var/run/rspamd/rspamd_proxy.sock mode=0600 owner=_rspamd";' >> /etc/rspamd/local.d/worker-proxy.inc
	else
		echo 'bind_socket = "/var/run/rspamd/rspamd_proxy.sock mode=0600 owner=_rspamd";' > /etc/rspamd/local.d/worker-proxy.inc
	fi

	#prevent: cfg; rspamd_config_read: failed to load config: ucl parser error: cannot open file /etc/rspamd/directadmin-users.conf: No such file or directory
	if [ ! -e /etc/rspamd/directadmin-users.conf ]; then
		touch /etc/rspamd/directadmin-users.conf
	fi
	mkdir -p /etc/rspamd/users.d
	chown _rspamd:_rspamd /etc/rspamd/local.d/settings.conf /etc/rspamd/users.d /etc/rspamd/directadmin-users.conf /etc/rspamd

	# generate user prefs
	"${DA_BIN}" taskq --run 'action=rewrite&value=rspamd'

	update_csf_conf

	echo "Restarting rspamd."
	control_service rspamd restart

	set_service rspamd ON

# Not needed, as we load it elsewhere
# 	if ! grep -m1 -q '^\.include_if_exists /etc/exim.spamd.conf' /etc/exim.conf; then
# 		if grep -m1 -q '^#\.include_if_exists /etc/exim.spamd.conf' /etc/exim.conf; then
# 			perl -pi -e 's|#\.include_if_exists /etc/exim\.spamd\.conf|.include_if_exists /etc/exim.clamav.conf|g' /etc/exim.conf
# 		else
# 			perl -pi -e 's|\.include_if_exists /etc/exim\.clamav\.conf|.include_if_exists /etc/exim.spamd.conf\n  .include_if_exists /etc/exim.clamav.conf|g' /etc/exim.conf
# 		fi
# 	fi
# 	
# 	if ! grep -m1 -q '^\.include_if_exists /etc/exim.spamd.load.conf' /etc/exim.conf; then
# 		if grep -m1 -q '^#\.include_if_exists /etc/exim.spamd.load.conf' /etc/exim.conf; then
# 			perl -pi -e 's|#\.include_if_exists /etc/exim\.spamd\.load\.conf|.include_if_exists /etc/exim.spamd.load.conf|g' /etc/exim.conf
# 		else
# 			perl -pi -e 's|\.include_if_exists /etc/exim\.clamav\.conf|.include_if_exists /etc/exim.spamd.conf\n  .include_if_exists /etc/exim.spamd.load.conf|g' /etc/exim.conf
# 		fi
# 	fi
# 
# 	echo "Enabling rspamd in /etc/exim.spamd.load.conf..."
# 	echo 'spamd_address = 127.0.0.1 11333 retry=20s variant=rspamd' > /etc/exim.spamd.load.conf
# 
# 	cp -fv ${SPAMD_CONF} /etc/exim.spamd.conf

	echo "Restarting exim."
	control_service exim restart

	ldconfig

	setupLogrotate rspamd
	
	writeLog "Rspamd has been installed successfully."
}

doNetdata() {
	curl ${CURL_CONNECT_OPTIONS} -o netdata.sh https://my-netdata.io/kickstart-static64.sh && bash ./netdata.sh --dont-wait --disable-telemetry && rm -f netdata.sh

	if [ -e /opt/netdata/etc/netdata/netdata.conf ] && [ ! -e /etc/netdata/netdata.conf ]; then
		NETDATA_CONF=/opt/netdata/etc/netdata/netdata.conf
	else
		NETDATA_CONF=/etc/netdata/netdata.conf
	fi

	if [ -s ${WORKDIR}/custom/netdata/netdata.conf ]; then
		cp -pf ${WORKDIR}/custom/netdata/netdata.conf ${NETDATA_CONF}
	else
		printf "[web]\nbind to = unix:/var/run/netdata/netdata.sock\nweb files owner = root\nweb files group = netdata\n[global]\nrun as user = netdata\nprocess scheduling policy = keep\nOOM score = keep\n" > ${NETDATA_CONF}
	fi

	if [ -s /usr/lib/systemd/system/netdata.service ]; then
		if grep -m1 -q '^RuntimeDirectoryMode=0775$' /usr/lib/systemd/system/netdata.service; then
			perl -pi -e 's|^RuntimeDirectoryMode=0775$|RuntimeDirectoryMode=0700|g' /usr/lib/systemd/system/netdata.service
			systemctl daemon-reload
		fi
	fi

	if [ "${CLOUDLINUX_OPT}" = "yes" ]; then
		usermod -a -G clsupergid netdata
	fi
	pkill -x netdata
	sleep 10
	control_service netdata start
	set_service netdata ON
}

do_remove_rspamd() {
	if [ "${SPAMD_OPT}" = "rspamd" ]; then
		do_exit 1 "Cannot remove Rspamd because it is enabled in options.conf."
	fi

	if distro_is_debian; then
		apt-get -y purge rspamd
	else
		yum -y remove rspamd
	fi
	
	if [ -e ${SYSTEMDDIR}/rspamd.service ]; then
		echo "Disabling rspamd in systemd..."
		systemctl disable rspamd.service
		remove_file ${SYSTEMDDIR}/rspamd.service
		systemctl daemon-reload
	fi	
	
	if [ -d /etc/rspamd ]; then
		remove_directory /etc/rspamd
	fi
	
	echo "Rspamd has been successfully removed"
	writeLog "Rspamd removed"
}

####################################################

doclamav() {
	if [ "${CLAMAV_OPT}" = "no" ]; then
		do_exit 1 "ClamAV is not set in options.conf."
	fi

	if [ -e /usr/local/sbin/clamd ] || [ -e /usr/local/lib64/libfreshclam.so.2 ]; then
		doRemoveClamav
	fi

	echo "Installing clamav..."

	install_rpms clamav-server clamav-data clamav-update clamav-filesystem clamav clamav-scanner-systemd clamav-devel clamav-lib clamav-server-systemd
	install_debs clamav clamav-daemon clamav-freshclam

	PATH_TO_UPLOADSCAN=/usr/local/bin/pureftpd_uploadscan.sh
	PATH_TO_RUNAV=/usr/local/bin/runav.pl
	if [ -s "${PATH_TO_UPLOADSCAN}" ] && grep -q '/usr/local/bin/clamdscan' "${PATH_TO_UPLOADSCAN}"; then
			perl -pi -e 's#/usr/local/bin/clamdscan#/usr/bin/clamdscan#g' "${PATH_TO_UPLOADSCAN}"
			control_service pure-ftpd restart
	fi
	if [ -s "${PATH_TO_RUNAV}" ] && grep -q '/usr/local/bin/clamdscan' "${PATH_TO_RUNAV}"; then
			perl -pi -e 's#/usr/local/bin/clamdscan#/usr/bin/clamdscan#g' "${PATH_TO_RUNAV}"
	fi
	if distro_is_debian; then
		CLAMD_CONF=/etc/clamav/clamd.conf
		FRESHCLAM_CONF=/etc/clamav/freshclam.conf
	fi
	if distro_is_rhel; then
		CLAMD_CONF=/etc/clamd.d/scan.conf
		FRESHCLAM_CONF=/etc/freshclam.conf
	fi

	# Hotfix for old clamav removal bug, it deletes
	# /lib/systemd/system/clamav-freshclam.service file which is owned
	# by clamav-update package.
	if distro_is_rhel && [ ! -f /usr/lib/systemd/system/clamav-freshclam.service ]; then
		# We check `/usr/lib/...` instead of `/lib/...` because package
		# provides file in `/usr/lib/...` but system has
		# `/lib` -> `/usr/libs` symlink.
		rm -f /etc/freshclam.conf # To make sure we get fresh one on package reinstall
		reinstall_rpms clamav-update
	fi
	if distro_is_debian && [ ! -f /lib/systemd/system/clamav-freshclam.service ]; then
		rm -f /etc/clamav/freshclam.conf # To make sure we get fresh one on package reinstall
		reinstall_debs clamav-freshclam
	fi

	if ! grep -q '^TCPSocket' ${CLAMD_CONF}; then
		echo 'TCPSocket 3310' >> ${CLAMD_CONF}
	fi
	if ! grep -q '^TCPAddr' ${CLAMD_CONF}; then
		echo 'TCPAddr 127.0.0.1' >> ${CLAMD_CONF}
	fi
	if ! grep -q '^LocalSocket' ${CLAMD_CONF}; then
		perl -pi -e 's|^LocalSocket|#LocalSocket|' ${CLAMD_CONF}
	fi

	if ! grep -q '^DatabaseMirror' ${FRESHCLAM_CONF}; then
		echo 'DatabaseMirror database.clamav.net' >> ${FRESHCLAM_CONF}
	fi
	if ! grep -q '^NotifyClamd' ${FRESHCLAM_CONF}; then
		echo "NotifyClamd ${CLAMD_CONF}" >> ${FRESHCLAM_CONF}
	fi
	if ! grep -q '^Checks' ${FRESHCLAM_CONF}; then
		echo 'Checks 24' >> ${FRESHCLAM_CONF}
	fi

	echo "Enabling clamd in systemd..."
	if distro_is_debian; then
		systemctl enable clamav-daemon
		systemctl enable clamav-freshclam
		set_service clamav-daemon ON
		set_service clamav-freshclam ON
	fi
	if distro_is_rhel; then
		systemctl enable clamd@scan
		systemctl enable clamav-freshclam
		set_service clamd@scan ON
		set_service clamav-freshclam ON
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "Restarting freshclam."
	control_service clamav-freshclam restart

	echo "Restarting clamd."
	if distro_is_debian; then
		control_service clamav-daemon restart
	fi
	if distro_is_rhel; then
		control_service clamd@scan restart
	fi

	if [ "${CLAMAV_EXIM_OPT}" = "yes" ] && [ "${EXIMCONF_OPT}" = "yes" ]; then
		doEximConf
	fi

	echo "Done ClamAV."
	writeLog "ClamAV installed"
}

doRemoveClamav() {
	echo "Removing clamav..."

	find /usr/local/lib/ -name 'libclamunrar.*' -type f -delete
	find /usr/local/lib/ -name 'libclamunrar_iface.*' -type f -delete
	find /usr/local/lib/ -name 'libclammspack.*' -type f -delete
	find /usr/local/lib/ -name 'libclamav.*' -type f -delete
	find /usr/local/lib/ -name 'libfreshclam.*' -type f -delete
	find /usr/local/lib64/ -name 'libclamunrar.*' -type f -delete
	find /usr/local/lib64/ -name 'libclamunrar_iface.*' -type f -delete
	find /usr/local/lib64/ -name 'libclammspack.*' -type f -delete
	find /usr/local/lib64/ -name 'libclamav.*' -type f -delete
	find /usr/local/lib64/ -name 'libfreshclam.*' -type f -delete
	remove_file /usr/local/bin/clamav-config
	remove_file /usr/local/lib/pkgconfig/libclamav.pc
	remove_file /usr/local/lib64/pkgconfig/libclamav.pc
	remove_file /usr/local/include/clamav.h
	remove_file /usr/local/include/clamav-types.h
	remove_file /usr/local/include/clamav-version.h
	remove_file /usr/local/include/libfreshclam.h
	remove_file /usr/local/bin/clamconf
	remove_file /usr/local/sbin/clamd
	remove_file /lib/systemd/system/clamav-daemon.service
	remove_file /lib/systemd/system/clamav-daemon.socket
	remove_file /usr/local/bin/clamdscan
	remove_file /usr/local/sbin/clamonacc
	remove_file /lib/systemd/system/clamav-clamonacc.service
	remove_file /usr/local/bin/clamscan
	remove_file /usr/local/bin/sigtool
	remove_file /usr/local/bin/clambc
	remove_file /usr/local/bin/clamsubmit
	remove_file /usr/local/bin/freshclam
	remove_file /lib/systemd/system/clamav-freshclam.service
	remove_file /usr/local/bin/clamdtop
	remove_file /etc/clamd.conf.sample
	remove_file /etc/freshclam.conf.sample
	remove_file /usr/local/share/man/man1/clamscan.1
	remove_file /usr/local/share/man/man1/freshclam.1
	remove_file /usr/local/share/man/man1/sigtool.1
	remove_file /usr/local/share/man/man1/clamdscan.1
	remove_file /usr/local/share/man/man1/clamconf.1
	remove_file /usr/local/share/man/man1/clamdtop.1
	remove_file /usr/local/share/man/man1/clamsubmit.1
	remove_file /usr/local/share/man/man1/clambc.1
	remove_file /usr/local/share/man/man5/clamd.conf.5
	remove_file /usr/local/share/man/man5/clamav-milter.conf.5
	remove_file /usr/local/share/man/man5/freshclam.conf.5
	remove_file /usr/local/share/man/man8/clamd.8
	remove_file /usr/local/share/man/man8/clamav-milter.8
	remove_file /usr/local/share/man/man8/clamonacc.8
	remove_directory /usr/local/share/doc/ClamAV
	ldconfig

	echo "Removing clamav/freshclam from services.status..."
	set_service clamd delete
	set_service freshclam delete

	if [ -e ${SYSTEMDDIR}/clamd.service ]; then
		echo "Removing clamd systemd script..."
		systemctl stop clamd.service
		systemctl disable clamd.service
		rm -f ${SYSTEMDDIR}/clamd.service
		systemctl daemon-reload
	fi

	if [ -e ${SYSTEMDDIR}/freshclam.service ]; then
		echo "Removing freshclam systemd script..."
		systemctl stop freshclam.service
		systemctl disable freshclam.service
		rm -f ${SYSTEMDDIR}/freshclam.service
		systemctl daemon-reload
	fi

	echo "Removing ClamAV configuration file /etc/clamd.conf..."
	rm -f /etc/clamd.conf

	echo "Removing Freshclam configuration file /etc/freshclam.conf..."
	rm -f /etc/freshclam.conf

	EXIMRESTART=0
	if [ -e /etc/exim.clamav.load.conf ] || [ -e /etc/exim.clamav.conf ]; then
		EXIMRESTART=1
		echo "Disabling ClamAV in exim.conf..."
		rm -f /etc/exim.clamav.load.conf
		rm -f /etc/exim.clamav.conf
	fi

	#Remove ClamAV Database
	echo "Removing ClamAV Database: /usr/local/share/clamav..."
	rm -rf /usr/local/share/clamav

	#Rempove symlinks of /usr/bin binaries to /usr/local/bin
	echo "Removing ClamAV symlinks from /usr/bin..."
	if [ -L /usr/bin/clamav-config ]; then
		rm -f /usr/bin/clamav-config
	fi
	if [ -L /usr/bin/clambc ]; then
		rm -f /usr/bin/clambc
	fi
	if [ -L /usr/bin/clamconf ]; then
		rm -f /usr/bin/clamconf
	fi
	if [ -L /usr/bin/clamdscan ]; then
		rm -f /usr/bin/clamdscan
	fi
	if [ -L /usr/bin/clamscan ]; then
		rm -f /usr/bin/clamscan
	fi
	if [ -L /usr/bin/freshclam ]; then
		rm -f /usr/bin/freshclam
	fi
	if [ -L /usr/bin/clamd ]; then
		rm -f /usr/sbin/clamd
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	if [ "${EXIMRESTART}" = "1" ]; then
		echo "Restarting exim..."
		control_service exim restart
	fi

	echo "ClamAV has been successfully removed."
	writeLog "ClamAV removed"
}

####################################################

doPhp() {
	doPhp_build ${PHP1_RELEASE_OPT} ${PHP1_MODE_OPT}
	if [ "${PHP2_RELEASE_OPT}" != "no" ]; then
		doPhp_build ${PHP2_RELEASE_OPT} ${PHP2_MODE_OPT}
	fi
	if [ "${PHP3_RELEASE_OPT}" != "no" ]; then
		doPhp_build ${PHP3_RELEASE_OPT} ${PHP3_MODE_OPT}
	fi
	if [ "${PHP4_RELEASE_OPT}" != "no" ]; then
		doPhp_build ${PHP4_RELEASE_OPT} ${PHP4_MODE_OPT}
	fi
	if [ -x /usr/share/i360-php/native_da.hook ]; then
		/usr/share/i360-php/native_da.hook --install-i360
	fi
	if [ "${WEBSERVER_OPT}" = "openlitespeed" ] || [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		#Reload detached lsphp processes
		touch /usr/local/lsws/admin/tmp/.lsphp_restart.txt
	fi
	writeLog "PHP built"
}

####################################################

doRemovePhp() {
	if [ "$1" = "" ]; then
		do_exit 1 "No arguments given (PHP release), exiting..."
	fi
	REMOVE_SHORTRELEASE=`echo $1 | tr -d '.'`

	if [ "${PHP1_RELEASE_OPT}" = "$1" ] || [ "${PHP2_RELEASE_OPT}" = "$1" ] || [ "${PHP3_RELEASE_OPT}" = "$1" ] || [ "${PHP4_RELEASE_OPT}" = "$1" ]; then
		do_exit 1 "Cannot remove PHP $1, because you have it set in options.conf file."
	fi

	if [ ! -d /usr/local/php${REMOVE_SHORTRELEASE} ]; then
		do_exit 1 "/usr/local/php${REMOVE_SHORTRELEASE} does not exist, cannot remove..."
	fi

	echo "Removing /usr/local/php${REMOVE_SHORTRELEASE}"
	rm -rf /usr/local/php${REMOVE_SHORTRELEASE}

	remove_file /var/log/php-fpm${REMOVE_SHORTRELEASE}.log

	ldconfig

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	echo "PHP $1 has been successfully removed"
	writeLog "PHP $1 removed"
}

####################################################
doFtpCleanup() {
	if grep -q "^pure-ftpd" ${SERVICES} 2>/dev/null || grep -q "^proftpd" ${SERVICES} 2>/dev/null; then
		return
	fi
	#Clean up FTP env
	#Get out of here! We don't want any of this (wu-ftpd)!
	if distro_is_debian; then
		dpkg -r --force-all gadmin-proftpd gforge-ftp-proftpd gproftpd proftpd-basic proftpd-doc proftpd-mod-ldap proftpd-mod-mysql proftpd-mod-pgsql pure-ftpd pure-ftpd-common 2> /dev/null
		dpkg -P gadmin-proftpd gforge-ftp-proftpd gproftpd proftpd-basic proftpd-doc proftpd-mod-ldap proftpd-mod-mysql proftpd-mod-pgsql pure-ftpd pure-ftpd-common 2> /dev/null
	fi
	if distro_is_rhel; then
		rpm -e --nodeps wu-ftp 2> /dev/null
		rpm -e --nodeps wu-ftpd 2> /dev/null
		rpm -e --nodeps anonftp 2> /dev/null
		rpm -e --nodeps pure-ftpd 2> /dev/null
		rpm -e --nodeps vsftpd 2> /dev/null
		rpm -e --nodeps psa-proftpd 2> /dev/null
		rpm -e --nodeps psa-proftpd-xinetd 2> /dev/null
		rpm -e --nodeps psa-proftpd-start 2> /dev/null
		rm -f /etc/xinetd.d/proftpd
		rm -f /etc/xinetd.d/wu-ftpd.rpmsave
		rm -f /etc/xinetd.d/wu-ftpd
		rm -f /etc/xinetd.d/ftp_psa
		rm -f /etc/xinetd.d/gssftp
		rm -f /etc/xinetd.d/xproftpd
	fi
	if [ -x /usr/local/sbin/pure-ftpd ]; then
		if ! grep -q "^pure-ftpd" ${SERVICES} 2>/dev/null; then
			pkill -x -9 pure-ftpd 2> /dev/null > /dev/null
			rm -f /usr/local/sbin/pure-ftpd 2> /dev/null > /dev/null
		fi
	fi
	#while we're doing it, lets get rid of pop stuff too
	rm -f /etc/xinetd.d/pop*

	#in case they it still holds port 21
	if [ -s /usr/lib/systemd/system/xinetd.service ]; then
			systemctl restart xinetd.service
	fi
}
####################################################

doProftpd() {
	if [ "${FTPD_OPT}" != "proftpd" ]; then
		do_exit 1 "You cannot install ProFTPD, because you do not have it set in options.conf file."
	fi

	doFtpCleanup
	addUserGroup ftp ftp
	addToAccess ftp

	ensureBuildPackages
	install_debs libssl-dev
	install_rpms openssl-devel
	safeDownloadWithMove "${WORKDIR}/proftpd-${PROFTPD_VER}.tar.gz" "${PROFTPD_DOWNLOADURL}"

	# Setting a new temp dir (in case /tmp is noexec,nosuid)
	cd ${WORKDIR}
	FILE=${WORKDIR}/proftpd-${PROFTPD_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE} --no-same-owner
	chown -R root:root proftpd-${PROFTPD_VER}
	cd proftpd-${PROFTPD_VER}

	# Backup ProFTPD config
	if [ -e /etc/proftpd.conf ]; then
		cp -pf /etc/proftpd.conf /etc/proftpd.conf.old
	fi

	cp -pf ${WORKDIR}/${PROFTPD_CONF} /etc/proftpd.conf

	if [ -s /etc/proftpd.sftp.conf ] && ! grep -m1 -q '^Include /etc/proftpd.sftp.conf' /etc/proftpd.conf; then
		echo 'Include /etc/proftpd.sftp.conf' >> /etc/proftpd.conf
	elif [ ! -s /etc/proftpd.sftp.conf ] && grep -m1 -q '^Include /etc/proftpd.sftp.conf' /etc/proftpd.conf; then
		sed -i '/^Include /etc/proftpd.sftp.conf/d' /etc/proftpd.conf
	fi

	if [ -d /usr/local/directadmin/data/admin/ips ]; then
		IP="`grep -r -l -m1 '^status=server$' /usr/local/directadmin/data/admin/ips | cut -d/ -f8`"
	fi
	if [ "${IP}" = "" ]; then
		IP="`grep -im1 ${HOSTNAME} /etc/hosts | awk '{print $1}'`"
		if [ "${IP}" = "" ]; then
			echo "Unable to detect your server IP in /etc/hosts. Please enter it: "
			read IP
		fi
	fi
	if [ "${IP}" = "" ]; then
		echo "Unable to detect your server IP. Exiting..."
		do_exit 0
	fi

	if [ "`echo ${IP} | grep -m1 -c ':'`" -gt 0 ]; then
		IP="[${IP}]"
	fi

	echo "Using $IP for your server IP"

	if [ -e /etc/proftpd.conf ]; then
		if [ "`grep -m1 -c '|IP|' /etc/proftpd.conf`" -gt "0" ]; then
			perl -pi -e "s/\|IP\|/${IP}/" /etc/proftpd.conf
		fi
		if [ "`grep -m1 -c '|SERVER_IP|' /etc/proftpd.conf`" -gt "0" ]; then
			perl -pi -e "s/\|SERVER_IP\|/${IP}/" /etc/proftpd.conf
		fi
	fi

	if [ -e /etc/proftpd.sftp.conf ]; then
		if [ "`grep -m1 -c '|IP|' /etc/proftpd.sftp.conf`" -gt "0" ]; then
			perl -pi -e "s/\|IP\|/${IP}/" /etc/proftpd.sftp.conf
		fi
		if [ "`grep -m1 -c '|SERVER_IP|' /etc/proftpd.sftp.conf`" -gt "0" ]; then
			perl -pi -e "s/\|SERVER_IP\|/${IP}/" /etc/proftpd.sftp.conf
		fi
	fi

	echo "Configuring proftpd-${PROFTPD_VER}..."
	"${configure_scripts_active[proftpd]}"

	echo "Done. Making proftpd-${PROFTPD_VER}..."
	echo "Trying to make ProFTPD..."
	if ! make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing proftpd-${PROFTPD_VER}..."
	make install

	if [ ! -e /etc/proftpd.passwd ]; then
		touch /etc/proftpd.passwd
		chmod 640 /etc/proftpd.passwd
	fi
	if [ ! -d /var/log/proftpd ]; then
		mkdir -p /var/log/proftpd
	fi
	if [ ! -e /etc/proftpd.vhosts.conf ]; then
		touch /etc/proftpd.vhosts.conf
	fi

	if [ ! -e /etc/exim.cert ] || [ ! -e /etc/exim.key ]; then
		create_da_conf_certs || return 1
		install_file /usr/local/directadmin/conf/cacert.pem.combined /etc/exim.cert 600 mail:mail || return 1
		install_file /usr/local/directadmin/conf/cakey.pem           /etc/exim.key  600 mail:mail || return 1
	fi

	echo "Enabling proftpd in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/proftpd.service ]; then
		cp -f ${CB_CUST_SYSTEMD}/proftpd.service ${SYSTEMDDIR}/proftpd.service
	else
		cp -f ${CB_SYSTEMD}/proftpd.service ${SYSTEMDDIR}/proftpd.service
	fi
	chmod 644 ${SYSTEMDDIR}/proftpd.service
	if distro_is_debian; then
		perl -pi -e 's#/usr/bin/mkdir#/bin/mkdir#' ${SYSTEMDDIR}/proftpd.service
	fi
	systemctl daemon-reload

	if [ -e ${SYSTEMDDIR}/proftpd.service ]; then
		systemctl enable proftpd.service
		if [ -e ${SYSTEMDDIR}/pure-ftpd.service ]; then
			systemctl stop pure-ftpd.service
			systemctl disable pure-ftpd.service
			rm -f ${SYSTEMDDIR}/pure-ftpd.service
			if [ -e ${SYSTEMDDIR}/pure-certd.service ]; then
				systemctl stop pure-certd.service
				systemctl disable pure-certd.service
				rm -f ${SYSTEMDDIR}/pure-certd.service
			fi
			if [ -e ${SYSTEMDDIR}/pure-uploadscript.service ]; then
				systemctl stop pure-uploadscript.service
				systemctl disable pure-uploadscript.service
				rm -f ${SYSTEMDDIR}/pure-uploadscript.service 
			fi
			systemctl daemon-reload
		fi
	fi
	mkdir -p /run/proftpd

	pkill -x -9 pure-ftpd >/dev/null 2>&1

	echo "Done proftpd."
	writeLog "Proftpd ${PROFTPD_VER} installed"

	# Linking configs
	rm -f /usr/local/etc/proftpd.conf
	ln -sf /etc/proftpd.conf /usr/local/etc/proftpd.conf

	perl -pi -e 's/DisplayFirstChdir/DisplayChdir/' /etc/proftpd.conf

	#setup the directadmin.conf
	setVal pureftp 0 ${DACONF_FILE}

	set_service pure-ftpd delete
	set_service proftpd ON

	pkill -x pure-ftpd >/dev/null 2>&1

	if [ "${PROFTPD_UPLOADSCAN_OPT}" = "yes" ] && [ "${CLAMAV_OPT}" = "yes" ]; then
		if [ ! -e /usr/bin/clamdscan ]; then
			doclamav
		fi
		if [ ! -e /usr/bin/clamdscan ]; then
			do_exit 1 "Cannot enable upload scan in ProFTPd because there is no ClamAV (/usr/bin/clamdscan) on the system."
		fi
		echo "Enabling ProFTPd ClamAV module for upload scanning"
		MOD_CLAMAV_VER=${versions_txt["mod_clamav"]}
		safeDownloadWithMove "${WORKDIR}/proftpd-${PROFTPD_VER}/mod_clamav-${MOD_CLAMAV_VER}.tar.gz" "${WEBPATH}/mod_clamav-${MOD_CLAMAV_VER}.tar.gz"
		if ! grep -m1 -q '^Include /etc/proftpd.clamav.conf' /etc/proftpd.conf; then
			perl -pi -e 's#</Global>#</Global>\n\nInclude /etc/proftpd.clamav.conf#' /etc/proftpd.conf
		fi
		tar xzf mod_clamav-${MOD_CLAMAV_VER}.tar.gz mod_clamav-${MOD_CLAMAV_VER}/mod_clamav.c mod_clamav-${MOD_CLAMAV_VER}/mod_clamav.h --strip-components=1
		/usr/bin/prxs -c -i -d mod_clamav.c
		echo -n '' > /etc/proftpd.clamav.conf
		echo '<IfModule mod_dso.c>' >> /etc/proftpd.clamav.conf
		echo 'LoadModule mod_clamav.c' >> /etc/proftpd.clamav.conf
		echo '</IfModule>' >> /etc/proftpd.clamav.conf
		echo '<IfModule mod_clamav.c>' >> /etc/proftpd.clamav.conf
		echo 'ClamAV on' >> /etc/proftpd.clamav.conf
		echo 'ClamServer 127.0.0.1' >> /etc/proftpd.clamav.conf
		echo 'ClamPort 3310' >> /etc/proftpd.clamav.conf
		echo 'ClamMaxSize 5 Mb' >> /etc/proftpd.clamav.conf
		echo '</IfModule>' >> /etc/proftpd.clamav.conf
	else
		echo '' > /etc/proftpd.clamav.conf
	fi

	doSslConfigurationFtp

	setupLogrotate proftpd

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	cd ${WORKDIR}
	echo "Restarting ProFTPd."
	control_service proftpd restart
}

####################################################

doRemoveProftpd() {
	if [ "${FTPD_OPT}" = "proftpd" ]; then
		do_exit 1 "Cannot remove Pure-FTPd, because it is enabled in options.conf file."
	fi

	echo "Disabling proftpd in services.status"
	set_service proftpd delete

	control_service proftpd stop

	echo "Disabling proftpd in systemd..."

	systemctl disable proftpd.service
	rm -f ${SYSTEMDDIR}/proftpd.service
	systemctl daemon-reload

	remove_directory /etc/logrotate.d/proftpd
	remove_directory /usr/include/proftpd
	remove_directory /usr/log/proftpd


	remove_file /usr/lib/pkgconfig/proftpd.pc
	remove_file /usr/lib64/pkgconfig/proftpd.pc

	remove_file /etc/ftpusers
	remove_file /etc/pam.d/proftpd
	remove_file /etc/proftpd.conf
	remove_file /usr/bin/ftpasswd
	remove_file /usr/bin/ftpcount
	remove_file /usr/bin/ftpdctl
	remove_file /usr/bin/ftpmail
	remove_file /usr/bin/ftpquota
	remove_file /usr/bin/ftptop
	remove_file /usr/bin/ftpwho
	remove_file /usr/bin/prxs
	remove_file /usr/share/man/man5/proftpd.conf.5
	remove_file /usr/share/man/man8/proftpd.8
	remove_file /usr/share/man/man8/proftpd.8.gz
	remove_file /usr/share/locale/bg_BG/LC_MESSAGES/proftpd.mo
	remove_file /usr/share/locale/en_US/LC_MESSAGES/proftpd.mo
	remove_file /usr/share/locale/fr_FR/LC_MESSAGES/proftpd.mo
	remove_file /usr/share/locale/it_IT/LC_MESSAGES/proftpd.mo
	remove_file /usr/share/locale/ja_JP/LC_MESSAGES/proftpd.mo
	remove_file /usr/share/locale/ko_KR/LC_MESSAGES/proftpd.mo
	remove_file /usr/share/locale/ru_RU/LC_MESSAGES/proftpd.mo
	remove_file /usr/share/locale/zh_CN/LC_MESSAGES/proftpd.mo
	remove_file /usr/share/locale/zh_TW/LC_MESSAGES/proftpd.mo
	remove_file /usr/local/etc/proftpd.conf
	remove_file /usr/sbin/in.proftpd
	remove_file /usr/sbin/proftpd
	remove_file /usr/sbin/ftpscrub
	remove_file /usr/sbin/ftpshut
	remove_file /etc/proftpd.clamav.conf
	remove_file /etc/proftpd.vhosts.conf

	ldconfig

	echo "ProFTPd has been successfully removed"
	writeLog "Proftpd removed"
	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi
}

####################################################

doPureftpd() {
	if [ "${FTPD_OPT}" != "pureftpd" ]; then
		do_exit 1 "You cannot install Pure-FTPd, because you do not have it set in options.conf file."
	fi

	doFtpCleanup

	ensureBuildPackages
	install_debs libssl-dev
	install_rpms openssl-devel

	addUserGroup ftp ftp
	addToAccess ftp

	safeDownloadWithMove "${WORKDIR}/pure-ftpd-${PUREFTPD_VER}.tar.gz" "${PUREFTPD_DOWNLOADURL}"

	cd ${WORKDIR}
	FILE=${WORKDIR}/pure-ftpd-${PUREFTPD_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE} --no-same-owner
	chown -R root:root pure-ftpd-${PUREFTPD_VER}
	cd pure-ftpd-${PUREFTPD_VER}

	patch -p0 < ${WORKDIR}/patches/pure-ftpd-logjam.patch

	perl -pi -e 's|/etc/ssl/private|/etc|g' ./src/ftpd.h

	# add --without-capabilities on LXC containers to fix "Unable to switch capabilities"
	DISABLE_CAPABILITIES=false
	if [ -e /proc/1/environ ]; then
		if cat /proc/1/environ | tr '\0' '\n' | grep -q ^container=lxc; then
			DISABLE_CAPABILITIES=true
		fi
	fi

	if ${DISABLE_CAPABILITIES}; then
		echo "Adding --without-capabilities, to solve \"Unable to switch capabilities\" on LXC containers..."
		perl -pi -e 's|\./configure \\|./configure --without-capabilities \|g' "${configure_scripts_active[pureftpd]}"
	fi
	echo "Configuring pure-ftpd-${PUREFTPD_VER}..."
	"${configure_scripts_active[pureftpd]}"

	echo "Done. Making pure-ftpd-${PUREFTPD_VER}..."
	echo "Trying to make Pure-FTPd..."
	if ! make -j ${CPU_CORES}; then
		do_exit 1 "*** The make has failed. Exiting..."
	fi
	echo "Installing pure-ftpd-${PUREFTPD_VER}..."
	make install

	if [ ! -e /etc/proftpd.passwd ]; then
		touch /etc/proftpd.passwd
		chmod 640 /etc/proftpd.passwd
	fi

	if [ ! -e /etc/pure-ftpd.pem ]; then
		create_da_conf_certs || return 1
		install_file <(cat /usr/local/directadmin/conf/cakey.pem /usr/local/directadmin/conf/cacert.pem.combined) /etc/pure-ftpd.pem 600 root:root || return 1
	fi

	if grep -m1 -q -- "----------" /etc/pure-ftpd.pem; then
		perl -pi -e 's|----------|-----\n-----|g' /etc/pure-ftpd.pem
	fi

	if [ ! -s /etc/pure-ftpd-dhparams.pem ]; then
		ensure_dhparam /etc/pure-ftpd-dhparams.pem
	fi

	chmod 600 /etc/pure-ftpd-dhparams.pem
	chmod 600 /etc/pure-ftpd.pem

	echo "Copying ${PUREFTPD_CONF} to /etc/pure-ftpd.conf..."
	cp -f ${WORKDIR}/${PUREFTPD_CONF} /etc/pure-ftpd.conf

	PATH_TO_UPLOADSCAN=/usr/local/bin/pureftpd_uploadscan.sh


	PATH_TO_PURE_CERTD=/usr/local/bin/pureftpd_sni.sh

	echo "Enabling pure-certd script for SNI certificates..."
	if ! grep -m1 -q 'ExtCert                      /var/run/pure-certd.sock' /etc/pure-ftpd.conf; then
		echo 'ExtCert                      /var/run/pure-certd.sock' >> /etc/pure-ftpd.conf
	fi
	cp -f ${PUREFTPD_PURE_CERTD_SCRIPT} ${PATH_TO_PURE_CERTD}
	chmod 711 ${PATH_TO_PURE_CERTD}
	echo "Enabling pure-certd in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/pure-certd.service ]; then
		cp -f ${CB_CUST_SYSTEMD}/pure-certd.service ${SYSTEMDDIR}/pure-certd.service
	else
		cp -f ${CB_SYSTEMD}/pure-certd.service ${SYSTEMDDIR}/pure-certd.service
	fi
	chmod 644 ${SYSTEMDDIR}/pure-certd.service
	systemctl daemon-reload
	if [ -e ${SYSTEMDDIR}/pure-certd.service ]; then
		systemctl start pure-certd.service
	fi

	echo "Enabling pure-ftpd in systemd..."
	if [ -e ${CB_CUST_SYSTEMD}/pure-ftpd.service ]; then
		cp -f ${CB_CUST_SYSTEMD}/pure-ftpd.service ${SYSTEMDDIR}/pure-ftpd.service
	else
		cp -f ${CB_SYSTEMD}/pure-ftpd.service ${SYSTEMDDIR}/pure-ftpd.service
	fi
	chmod 644 ${SYSTEMDDIR}/pure-ftpd.service
	
	if [ "${PUREFTPD_UPLOADSCAN_OPT}" = "yes" ]; then

		if [ ! -e /usr/bin/clamdscan ] && [ "${CLAMAV_OPT}" = "yes" ]; then
			doclamav
		fi
		if [ ! -e /usr/bin/clamdscan ] && [ "${CLAMAV_OPT}" = "yes" ]; then
			do_exit 1 "Cannot enable upload scan in Pure-FTPd because there is no ClamAV (/usr/bin/clamdscan) on the system."
		fi
		echo "Enabling PureFTPd upload scanning script..."
		install_custom_file pureftpd/pureftpd_uploadscan.sh "${PATH_TO_UPLOADSCAN}" 711 root:root || return 1
		perl -pi -e 's|^CallUploadScript             no|CallUploadScript             yes|' /etc/pure-ftpd.conf
		echo "Enabling pure-uploadscript in systemd..."
		install_custom_file systemd/pure-uploadscript.service /etc/systemd/system/pure-uploadscript.service 644 root:root || return 1

		mkdir -p ${SYSTEMDDIR}/pure-ftpd.service.d
		echo -e "[Unit]\nRequires=pure-uploadscript.service\nAfter=pure-uploadscript.service" > ${SYSTEMDDIR}/pure-ftpd.service.d/pure-uploadscan.conf
		
	else
		rm -f ${SYSTEMDDIR}/pure-ftpd.service.d/pure-uploadscan.conf
		rm -f ${PATH_TO_UPLOADSCAN}
		perl -pi -e 's|^CallUploadScript             yes|CallUploadScript             no|' /etc/pure-ftpd.conf
		if [ -e ${SYSTEMDDIR}/pure-uploadscript.service ]; then
			echo "Disabling pure-uploadscript in systemd..."
			systemctl stop pure-uploadscript.service
			rm -f ${SYSTEMDDIR}/pure-uploadscript.service
		fi
	fi

	systemctl daemon-reload

	if [ -e ${SYSTEMDDIR}/pure-ftpd.service ]; then
		systemctl enable pure-ftpd.service
		if [ -e ${SYSTEMDDIR}/proftpd.service ]; then
			systemctl stop proftpd.service
			systemctl disable proftpd.service
			rm -f ${SYSTEMDDIR}/proftpd.service
			systemctl daemon-reload
		fi
	fi

	doSslConfigurationFtp

	pkill -x -9 proftpd >/dev/null 2>&1

	echo "Done pure-ftpd."
	writeLog "Pure-ftpd ${PUREFTPD_VER} installed"

	#setup the directadmin.conf
	setVal pureftp 1 ${DACONF_FILE}

	pkill -x proftpd >/dev/null 2>&1

	doRestartDA

	set_service proftpd delete
	set_service pure-ftpd ON

	pkill -x proftpd >/dev/null 2>&1

	pure-pw mkdb /etc/pureftpd.pdb -f /etc/proftpd.passwd

	setupLogrotate pure-ftpd

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	cd ${WORKDIR}
	echo "Restarting Pure-FTPd."
	control_service pure-ftpd restart
}

####################################################

doRemovePureftpd() {
	if [ "${FTPD_OPT}" = "pureftpd" ]; then
		do_exit 1 "Cannot remove Pure-FTPd, because it is enabled in options.conf file."
	fi

	safeDownloadWithMove "${WORKDIR}/pure-ftpd-${PUREFTPD_VER}.tar.gz" "${PUREFTPD_DOWNLOADURL}"

	echo "Disabling pure-ftpd in services.status"
	set_service pure-ftpd delete

	cd ${WORKDIR}
	FILE=${WORKDIR}/pure-ftpd-${PUREFTPD_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE} --no-same-owner
	chown -R root:root pure-ftpd-${PUREFTPD_VER}
	cd pure-ftpd-${PUREFTPD_VER}

	echo "Configuring pure-ftpd-${PUREFTPD_VER} for removal..."
	"${configure_scripts_active[pureftpd]}"

	echo "Done. Removing pure-ftpd-${PUREFTPD_VER}..."
	make uninstall

	if [ -e /etc/pure-ftpd.pem ]; then
		echo "Removing /etc/pure-ftpd.pem..."
		rm -f /etc/pure-ftpd.pem
	fi

	if [ -e /usr/local/bin/pureftpd_uploadscan.sh ]; then
		echo "Removing /usr/local/bin/pureftpd_uploadscan.sh..."
		rm -f /usr/local/bin/pureftpd_uploadscan.sh
	fi

	control_service pure-ftpd stop

	echo "Disabling pure-ftpd in systemd..."

	systemctl disable pure-ftpd.service
	rm -f ${SYSTEMDDIR}/pure-ftpd.service
	if [ -e ${SYSTEMDDIR}/pure-certd.service ]; then
		systemctl stop pure-certd.service
		systemctl disable pure-certd.service
		rm -f ${SYSTEMDDIR}/pure-certd.service
	fi
	if [ -e ${SYSTEMDDIR}/pure-uploadscript.service ]; then
		systemctl stop pure-uploadscript.service
		systemctl disable pure-uploadscript.service
		rm -f ${SYSTEMDDIR}/pure-uploadscript.service 
	fi
	systemctl daemon-reload

	rm -f /usr/libexec/pureftpd_startscript

	if [ -e /etc/pureftpd.pdb ]; then
		echo "Removing pure-ftpd password database: /etc/pureftpd.pdb..."
		rm -f /etc/pureftpd.pdb
	fi

	if [ -e /etc/logrotate.d/pure-ftpd ]; then
		echo "Removing /etc/logrotate.d/pure-ftpd..."
		rm -f /etc/logrotate.d/pure-ftpd
	fi

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	cd ${WORKDIR}
	
	writeLog "Pure-ftpd removed"
}

####################################################

doNoFtpd() {
	echo "No ftpd server set.  Adding basic ftp:ftp account setup."
	addUserGroup ftp ftp
	addToAccess ftp
}

####################################################

doRemoveNghttp2() {
	NGHTTP2_VER=1.48.0
	safeDownloadWithMove "${WORKDIR}/nghttp2-${NGHTTP2_VER}.tar.gz" "${WEBPATH}/nghttp2-${NGHTTP2_VER}.tar.gz"

	cd ${WORKDIR}
	FILE=${WORKDIR}/nghttp2-${NGHTTP2_VER}.tar.gz
	checkFile ${FILE}
	echo "Extracting ${FILE}..."

	tar xzf ${FILE} --no-same-owner
	cd nghttp2-${NGHTTP2_VER}

	echo "Configuring nghttp2-${NGHTTP2_VER} for removal..."
	./configure

	echo "Done. Removing nghttp2-${NGHTTP2_VER}..."
	make uninstall

	if ! ${EXEC_CL_COMMANDS_ONCE}; then
		cagefsctl_update
	else
		CL_COMPONENT_UPDATE=true
	fi

	cd ${WORKDIR}
	
	writeLog "nghttp2 removed"
}

####################################################

doUpdateDA() {
	/usr/local/directadmin/directadmin update 2>/dev/null

	writeLog "DirectAdmin update requested"
}

####################################################

checkSecurity() {
	MYSQL_IS_EOL=false
	if [ -e /usr/bin/mysql ]; then
		MYSQLV=`mysql_main`
		if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
			MYSQL_NAME="MySQL"
		else
			MYSQL_NAME="MariaDB"
		fi
		if [ "${MYSQLV}" = "5.5" ] || [ "${MYSQLV}" = "10.0" ] || [ "${MYSQLV}" = "10.1" ]; then
			MYSQL_IS_EOL=true
		fi
	fi
	LIST_JSON_SECURITY=false

	if ${MYSQL_IS_EOL}; then
		LIST_JSON_SECURITY=true
	fi

	#0 update items
	#1 show available updates
	#2 just webapps N/A here.
	#json similar to #1, but in json format.
	VERSIONS=$1

	if [ "${VERSIONS}" = "2" ]; then
		return;
	fi

	if [ "${VERSIONS}" = "0" ]; then
		#found cases where bind9.service boot of named, and named.serivce both running,
		#so bind9 instance never gets reloaded, so randomly serves stale data.
		ensure_not_debian_bind9_boot
	fi
	
	if [ "${VERSIONS}" = "json" ] && ${LIST_JSON_SECURITY}; then
		printf "\t\"security\": {\n"
	fi
	
	SECURITY_ITEM_ADDED=0

	if ${MYSQL_IS_EOL}; then
		if [ "${VERSIONS}" = "json" ]; then
			if [ "${SECURITY_ITEM_ADDED}" -eq 1 ]; then
				echo ","
			fi
			SECURITY_ITEM_ADDED=1
			printf "\t\t\"${MYSQL_NAME} EOL\": {\n"
				printf "\t\t\t\"name\": \"${MYSQL_NAME} is EOL\",\n"
				printf "\t\t\t\"description\": \"${MYSQL_NAME} version on the system is end of life, please upgrade\",\n"
				printf "\t\t\t\"url\": \"https://endoflife.software/applications/databases\"\n"
			printf "\t\t}"
		elif [ "${VERSIONS}" = "1" ]; then
			echo "${boldon}Security update is available.${boldoff}: ${MYSQL_NAME}: https://endoflife.software/applications/databases"
			echo ""
		fi
	fi

	if [ "${VERSIONS}" = "json" ] && ${LIST_JSON_SECURITY}; then
		printf "\n\t},\n"
	fi

}

####################################################

ensure_not_debian_bind9_boot() {
		if ! distro_is_debian; then
			return;
		fi

		if [ ! -e /lib/systemd/system/bind9.service ] || [ ! -e /etc/systemd/system/named.service ]; then
			return;
		fi
		
		if [ -h /lib/systemd/system/bind9.service ]; then
			return;
		fi
		
		if [ ! -s ${SERVICES} ]; then
			return;
		fi
		
		NAMED_ON=`grep -c 'named=ON' ${SERVICES}`
		if [ "${NAMED_ON}" != "1" ]; then
			return
		fi
		
		B9ON=`systemctl is-enabled bind9.service`
		if [ "${B9ON}" != "enabled" ]; then
			return;
		fi

		NAMEDON=`systemctl is-enabled named.service`
		if [ "${NAMEDON}" != "enabled" ]; then
			return;
		fi
		
		#only applies if named was already running as we don't want to start it up later, if it was never supposed to be running.
		NAMED_COUNT=`ps ax | grep -v grep | grep -c named`
		if [ "${NAMED_COUNT}" = "0" ]; then
			return;
		fi
				
		echo "${boldon}Both bind9.service and named.service are enabled. This could lead to random stale dns data being serviced. Disabling bind9.service${boldoff}"
		writeLog "disabling bind9 as both it and named were enabled."

		control_service bind9 stop
		control_service named stop
		pkill -x -9 named
		sleep 1
		systemctl disable bind9.service
		control_service named start
		sleep 1
		NAMED_COUNT=`ps ax | grep -v grep | grep -c named`

		SUBJECT="bind9.service disabled, named.service still enabled"
		MESSAGE="CustomBuild has noticed both bind9.service and named.service were enabled."$'\n'"This could lead to bind9 serving stale data as it is never reloaded."$'\n'"The bind9.service boot script has been disabled, and named.service has been left as it was."$'\n'"CustomBuild does see a new named process, you can likely disregard this message."
		
		if [ "${NAMED_COUNT}" = "0" ]; then
			#double check that.
			sleep 5;
			NAMED_COUNT=`ps ax | grep -v grep | grep -c named`
			if [ "${NAMED_COUNT}" = "0" ]; then
				#yikes, its broken.
				SUBJECT="bind9.service has been disabled but there is an issue with named starting up."
				MESSAGE="CustomBuild has noticed both bind9.service and named.service were enabled."$'\n'"This could lead to bind9 serving stale data as it is never reloaded."$'\n'"The bind9.service boot script has been disabled, and named.service has been left as it was."$'\n'"However CustomBuild does not see a new named process, so investigation of /var/log/messages might be need if it's not running."
			fi			
		fi

		send_da_message "${SUBJECT}" "${MESSAGE}"
}

####################################################

doVersions() {
	cd ${WORKDIR}

	if [ "$2" = "full" ]; then
		if distro_is_debian; then
			apt-get update
			apt-get -y upgrade
		elif distro_is_rhel; then
			yum -y update
		fi
		doUpdateDA
	fi

	VERSIONS=$1

	if [ "${CLOUDLINUX_OPT}" = "yes" ] && [ "${VERSIONS}" = "2" ]; then
		#Skip executing CL commands like "cagefsctl --force update" on every component update
		EXEC_CL_COMMANDS_ONCE=true
	fi

	WEBAPPS_UPDATED=false

	if [ "${VERSIONS}" = "1" ]; then
		if [ -s ${VERSIONS_FILE_CUSTOM} ]; then
			echo -n "${boldon}NOTE${boldoff}: Some custom versions are set in ${VERSIONS_FILE_CUSTOM}, this may prevent showing the actual latest version of the software: "
			cat ${VERSIONS_FILE_CUSTOM} | cut -d: -f1,2 | perl -p0 -e 's|:| (|g' | perl -p0 -e 's|\n|), |g' | perl -p0 -e 's|, $||g'
			echo ""
			echo ""
		fi
	fi

	if [ "${VERSIONS}" = "json" ]; then
		echo "{"
	fi

	if [ -e "${DA_BIN}" ]; then
		local current
		local offered
		current=$("${DA_BIN}" version | awk '{print $2, "build", $3}')
		current=${current##v.}
		offered=$("${DA_BIN}" update --check | awk '{print $3, "build", $4}')
		offered=${offered##v}
		
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of DirectAdmin: ${offered}"
			echo "Installed version of DirectAdmin: ${current}"
			echo ""
		fi
		if [ "${current}" != "${offered}" ]; then
			if [ "${DA_CRON}" != "true" ] && [ "${VERSIONS}" = "0" ]; then
				doUpdateDA
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}DirectAdmin ${current} to ${offered} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf '\t"update_da": {\n'
				printf '\t\t"name": "DirectAdmin",\n'
				printf '\t\t"current": "%s",\n' "${current}"
				printf '\t\t"offered": "%s"\n' "${offered}"
				printf '\t},\n'
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ -x /usr/bin/bwrap ] && [ -s /usr/bin/jailshell ] && [ "${CLOUDLINUX_OPT}" != "yes" ]; then
		local current
		local offered
		current=$(set -o pipefail; grep -m 1 '^#VERSION=' /usr/bin/jailshell | cut -d = -f 2 || echo 0)
		offered=$(set -o pipefail; grep -m 1 '^#VERSION=' "$(path_to_custom_file jailshell.sh)" | cut -d = -f 2 || echo 0)
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of Jailshell: ${offered}"
			echo "Installed version of Jailshell: ${current}"
			echo ""
		fi
		if [ "${offered}" != "${current}" ]; then
			if [ "${VERSIONS}" = "0" ] || [ "${VERSIONS}" = "2" ]; then
				echo "${boldon}Updating Jailshell${boldoff}"
				doJailshell
				WEBAPPS_UPDATED=true
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}Jailshell ${current} to ${offered} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf '\t"jailshell": {\n'
				printf '\t\t"name": "Jailshell",\n'
				printf '\t\t"current": "%s",\n' "${current}"
				printf '\t\t"offered": "%s"\n' "${offered}"
				printf '\t},\n'
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "litespeed" ] && [ "${LITESPEED_VER}" != "0" ]; then
		if [ -e /usr/local/lsws/bin/lshttpd ]; then
			LITESPEEDV="`/usr/local/lsws/bin/lshttpd -v | cut -d/ -f2 | awk '{print $1}'`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of LiteSpeed: ${LITESPEED_VER}"
				echo "Installed version of LiteSpeed: ${LITESPEEDV}"
				echo ""
			fi
			if [ "${LITESPEED_VER}" != "${LITESPEEDV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating LiteSpeed${boldoff}"
					doLiteSpeed
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}LiteSpeed ${LITESPEEDV} to ${LITESPEED_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"litespeed\": {\n"
					printf "\t\t\"name\": \"LiteSpeed\",\n"
					printf "\t\t\"current\": \"${LITESPEEDV}\",\n"
					printf "\t\t\"offered\": \"${LITESPEED_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ "${WEBSERVER_OPT}" = "openlitespeed" ] && [ "${OPENLITESPEED_VER}" != "0" ]; then
		if [ -e /usr/local/lsws/bin/lshttpd ]; then
			OPENLITESPEEDV="`/usr/local/lsws/bin/lshttpd -v | head -n1 | cut -d/ -f2 | awk '{print $1}'`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of OpenLiteSpeed: ${OPENLITESPEED_VER}"
				echo "Installed version of OpenLiteSpeed: ${OPENLITESPEEDV}"
				echo ""
			fi
			if [ "${OPENLITESPEED_VER}" != "${OPENLITESPEEDV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating OpenLiteSpeed${boldoff}"
					doOpenLiteSpeed
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}OpenLiteSpeed ${OPENLITESPEEDV} to ${OPENLITESPEED_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"openlitespeed\": {\n"
					printf "\t\t\"name\": \"OpenLiteSpeed\",\n"
					printf "\t\t\"current\": \"${OPENLITESPEEDV}\",\n"
					printf "\t\t\"offered\": \"${OPENLITESPEED_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi


	if [ "${APACHE2_VER}" != "0" ]; then
		if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			if [ -e /usr/sbin/httpd ]; then
				APACHEV="`/usr/sbin/httpd -v | grep -m1 'Server version:' | awk '{ print $3 }' | cut -d/ -f2`"
				if [ "${VERSIONS}" = "1" ]; then
					echo "Latest version of Apache: ${APACHE2_VER}"
					echo "Installed version of Apache: ${APACHEV}"
					echo ""
				fi
				if [ "${APACHE2_VER}" != "${APACHEV}" ]; then
					if [ "${VERSIONS}" = "0" ]; then
						echo "${boldon}Updating Apache${boldoff}"
						doApache2
					elif [ "${VERSIONS}" = "1" ]; then
						echo "${boldon}Apache ${APACHEV} to ${APACHE2_VER} update is available.${boldoff}"
						echo ""
					elif [ "${VERSIONS}" = "json" ]; then
						printf "\t\"apache\": {\n"
						printf "\t\t\"name\": \"Apache\",\n"
						printf "\t\t\"current\": \"${APACHEV}\",\n"
						printf "\t\t\"offered\": \"${APACHE2_VER}\"\n"
						printf "\t},\n"
					fi
					EXIT_CODE=$((EXIT_CODE+1))
				fi
			fi
		fi
	fi

	NGINX_UPDATE_AVAILABLE=0
	if [ "${NGINX_VER}" != "0" ]; then
		if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
			if [ -e /usr/sbin/nginx ]; then
				NGINXV="`/usr/sbin/nginx -v 2>&1 | grep -m1 'nginx version:' | cut -d'/' -f2`"
				if [ "${VERSIONS}" = "1" ]; then
					echo "Latest version of Nginx: ${NGINX_VER}"
					echo "Installed version of Nginx: ${NGINXV}"
					echo ""
				fi
				if [ "${NGINX_VER}" != "${NGINXV}" ]; then
					NGINX_UPDATE_AVAILABLE=1
					if [ "${VERSIONS}" = "0" ]; then
						echo "${boldon}Updating Nginx${boldoff}"
						doNginx
					elif [ "${VERSIONS}" = "1" ]; then
						echo "${boldon}Nginx ${NGINXV} to ${NGINX_VER} update is available.${boldoff}"
						echo ""
					elif [ "${VERSIONS}" = "json" ]; then
						printf "\t\"nginx\": {\n"
						printf "\t\t\"name\": \"Nginx\",\n"
						printf "\t\t\"current\": \"${NGINXV}\",\n"
						printf "\t\t\"offered\": \"${NGINX_VER}\"\n"
						printf "\t},\n"
					fi
					EXIT_CODE=$((EXIT_CODE+1))
				fi
			fi
		fi
	fi

	if [ "${MODSECURITY_OPT}" = "yes" ] && [ "${MODSECURITY_RULESET_OPT}" = "owasp" ] && [ "${OWASP_RULES_VER}" != "0" ]; then
		OWASP_RULESV=0
		if [ -e /etc/modsecurity.d/owasp_rules_version ]; then
			OWASP_RULESV=`cat /etc/modsecurity.d/owasp_rules_version`
		fi
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of OWASP ModSecurity Rule Set: ${OWASP_RULES_VER}"
			echo "Installed version of OWASP ModSecurity Rule Set: ${OWASP_RULESV}"
			echo ""
		fi
		if [ "${OWASP_RULES_VER}" != "${OWASP_RULESV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating OWASP ModSecurity Rule Set${boldoff}"
				doModSecurityRules
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}OWASP ModSecurity Rule Set ${OWASP_RULESV} to ${OWASP_RULES_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"modsecurity_rules\": {\n"
				printf "\t\t\"name\": \"OWASP ModSecurity Rule Set\",\n"
				printf "\t\t\"current\": \"${OWASP_RULESV}\",\n"
				printf "\t\t\"offered\": \"${OWASP_RULES_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${MODSECURITY_OPT}" = "yes" ] && [ "${MODSECURITY_RULESET_OPT}" = "comodo" ]; then
		if [ "${CWAF_RULES_VER}" != "0" ]; then
			CWAF_RULESV=0
			if [ -e /usr/local/cwaf/rules/rules.dat ]; then
				CWAF_RULESV=`cat /usr/local/cwaf/rules/rules.dat`
			fi
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of Comodo ModSecurity Rule Set: ${CWAF_RULES_VER}"
				echo "Installed version of Comodo ModSecurity Rule Set: ${CWAF_RULESV}"
				echo ""
			fi
			if [ "${CWAF_RULES_VER}" != "${CWAF_RULESV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating Comodo ModSecurity Rule Set${boldoff}"
					doModSecurityRules
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}Comodo ModSecurity Rule Set ${CWAF_RULESV} to ${CWAF_RULES_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"modsecurity_rules\": {\n"
					printf "\t\t\"name\": \"Comodo ModSecurity Rule Set\",\n"
					printf "\t\t\"current\": \"${CWAF_RULESV}\",\n"
					printf "\t\t\"offered\": \"${CWAF_RULES_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ "${FTPD_OPT}" = "proftpd" ] && [ "${PROFTPD_VER}" != "0" ]; then
		if [ -e $PROFTPD_PREFIX/sbin/proftpd ]; then
			PROFTPDV="`$PROFTPD_PREFIX/sbin/proftpd -v 2>&1 | awk '{ print $3 }'`"
			if [ "$PROFTPDV" = "Version" ]; then
				PROFTPDV="`$PROFTPD_PREFIX/sbin/proftpd -v 2>&1 | awk '{ print $4 }'`"
			fi
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of ProFTPD: ${PROFTPD_VER}"
				echo "Installed version of ProFTPD: ${PROFTPDV}"
				echo ""
			fi
			if [ "${PROFTPD_VER}" != "${PROFTPDV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating ProFTPD${boldoff}"
					doProftpd
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}ProFTPD ${PROFTPDV} to ${PROFTPD_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"proftpd\": {\n"
					printf "\t\t\"name\": \"ProFTPd\",\n"
					printf "\t\t\"current\": \"${PROFTPDV}\",\n"
					printf "\t\t\"offered\": \"${PROFTPD_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ "${FTPD_OPT}" = "pureftpd" ] && [ "${PUREFTPD_VER}" != "0" ]; then
		if [ -e /usr/sbin/pure-ftpd ]; then
			PUREFTPDV="`/usr/sbin/pure-ftpd -h | grep -m1 pure-ftpd | awk '{print $2}' | cut -dv -f2`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of Pure-FTPD: ${PUREFTPD_VER}"
				echo "Installed version of Pure-FTPd: ${PUREFTPDV}"
				echo ""
			fi
			if [ "${PUREFTPD_VER}" != "${PUREFTPDV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating Pure-FTPd${boldoff}"
					doPureftpd
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}Pure-FTPD ${PUREFTPDV} to ${PUREFTPD_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"pureftpd\": {\n"
					printf "\t\t\"name\": \"Pure-FTPd\",\n"
					printf "\t\t\"current\": \"${PUREFTPDV}\",\n"
					printf "\t\t\"offered\": \"${PUREFTPD_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ "${REDIS_OPT}" = "yes" ]; then
		REDISV=0
		if [ -x /usr/local/bin/redis-server ]; then
			REDISV="`/usr/local/bin/redis-server -v | grep -o -m1 'v=[^ ]*' | cut -d= -f2`"
		fi
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of Redis: ${REDIS_VER}"
			echo "Installed version of Redis: ${REDISV}"
			echo ""
		fi
		if [ "${REDIS_VER}" != "${REDISV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating Redis${boldoff}"
				doRedis
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}Redis ${REDISV} to ${REDIS_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"redis\": {\n"
				printf "\t\t\"name\": \"Redis\",\n"
				printf "\t\t\"current\": \"${REDISV}\",\n"
				printf "\t\t\"offered\": \"${REDIS_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${IMAGICK_OPT}" = "yes" ] && [ "${IMAGEMAGICK_VER}" != "0" ]; then
			IMAGEMAGICKV=0
			if [ -x /usr/local/bin/magick ]; then
				IMAGEMAGICKV="`/usr/local/bin/magick -version | head -n1 | awk '{print $3}'`"
			fi
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of ImageMagick: ${IMAGEMAGICK_VER}"
				echo "Installed version of ImageMagick: ${IMAGEMAGICKV}"
				echo ""
			fi
			if [ "${IMAGEMAGICK_VER}" != "${IMAGEMAGICKV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating ImageMagick${boldoff}"
					doImageMagick
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}ImageMagick ${IMAGEMAGICKV} to ${IMAGEMAGICK_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"imagemagick\": {\n"
					printf "\t\t\"name\": \"ImageMagick\",\n"
					printf "\t\t\"current\": \"${IMAGEMAGICKV}\",\n"
					printf "\t\t\"offered\": \"${IMAGEMAGICK_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
	fi

	if [ "${IMAGICK_OPT}" = "yes" ] && [ "${IMAGICK_VER}" != "0" ] && [ -x /usr/local/bin/php ]; then
			IMAGICKV=0
			if /usr/local/bin/php -i | grep -m1 -q 'imagick module version'; then
				IMAGICKV="`/usr/local/bin/php -i | grep -m1 'imagick module version' | awk '{print $5}'`"
			fi
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of imagick: ${IMAGICK_VER}"
				echo "Installed version of imagick: ${IMAGICKV}"
				echo ""
			fi
			if [ "${IMAGICK_VER}" != "${IMAGICKV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating imagick${boldoff}"
					doIMagick
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}Imagick ${IMAGICKV} to ${IMAGICK_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"imagick\": {\n"
					printf "\t\t\"name\": \"imagick\",\n"
					printf "\t\t\"current\": \"${IMAGICKV}\",\n"
					printf "\t\t\"offered\": \"${IMAGICK_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
	fi

	if [ "${WEBSERVER}" = "nginx" ] || [ "${WEBSERVER}" = "nginx_apache" ]; then
		if [ "${MODSECURITY_OPT}" = "yes" ]  && [ "${LIBMODSECURITY_VER}" != "0" ]; then
			if [ -s /usr/local/modsecurity/lib/pkgconfig/modsecurity.pc ]; then
				LIBMODSECURITYV=`grep 'Version: ' /usr/local/modsecurity/lib/pkgconfig/modsecurity.pc | awk '{print $2}'`
			else
				LIBMODSECURITYV=0
			fi
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of LibModSecurity: ${LIBMODSECURITYV}"
				echo "Installed version of LibModSecurity: ${LIBMODSECURITY_VER}"
				echo ""
			fi
			if [ "${LIBMODSECURITYV}" != "${LIBMODSECURITY_VER}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating LibModSecurity${boldoff}"
					doLibModSecurity
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}LibModSecurity ${LIBMODSECURITYV} to ${LIBMODSECURITY_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"libmodsecurity\": {\n"
					printf "\t\t\"name\": \"LibModSecurity\",\n"
					printf "\t\t\"current\": \"${LIBMODSECURITYV}\",\n"
					printf "\t\t\"offered\": \"${LIBMODSECURITY_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		
			# Check ModSecurity connector version
			if nginx -V 2>&1 | grep -q -o -m1 'modsecurity-nginx-v[^ ]*'; then
				MODSECURITY_NGINX_CONNECTORV=`nginx -V 2>&1 | grep -o -m1 'modsecurity-nginx-v[^ ]*' | cut -d- -f3`
				if [ "${VERSIONS}" = "1" ]; then
					echo "Latest version of ModSecurity Nginx Connector: ${MODSECURITY_NGINX_CONNECTORV}"
					echo "Installed version of ModSecurity Nginx Connector: ${MODSECURITY_NGINX_CONNECTOR_VER}"
					echo ""
				fi
				if [ "${MODSECURITY_NGINX_CONNECTORV}" != "${MODSECURITY_NGINX_CONNECTOR_VER}" ]; then
					if [ "${VERSIONS}" = "0" ]; then
						echo "${boldon}Updating ModSecurity Nginx Connector${boldoff}"
						doModSecurityConnector 1
					elif [ "${VERSIONS}" = "1" ]; then
						echo "${boldon}ModSecurity Nginx Connector ${MODSECURITY_NGINX_CONNECTORV} to ${MODSECURITY_NGINX_CONNECTOR_VER} update is available.${boldoff}"
						echo ""
					elif [ "${VERSIONS}" = "json" ]; then
						printf "\t\"modsecurity_connector\": {\n"
						printf "\t\t\"name\": \"ModSecurity Nginx Connector\",\n"
						printf "\t\t\"current\": \"${MODSECURITY_NGINX_CONNECTORV}\",\n"
						printf "\t\t\"offered\": \"${MODSECURITY_NGINX_CONNECTOR_VER}\"\n"
						printf "\t},\n"
					fi
					EXIT_CODE=$((EXIT_CODE+1))
				fi
			fi
		fi
	fi

	if [ -x /usr/local/bin/wp ]; then
		WPV="`/usr/local/bin/wp --version --allow-root | cut -d" " -f2`"
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of WP-CLI: ${WP_VER}"
			echo "Installed version of WP-CLI: ${WPV}"
			echo ""
		fi
		if [ "${WP_VER}" != "${WPV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating WP-CLI${boldoff}"
				doWP
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}WP-CLI ${WPV} to ${WP_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"wp\": {\n"
				printf "\t\t\"name\": \"wp-cli\",\n"
				printf "\t\t\"current\": \"${WPV}\",\n"
				printf "\t\t\"offered\": \"${WP_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ -x /usr/local/bin/imapsync ]; then
		IMAPSYNCV="`/usr/local/bin/imapsync --version`"
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of Imapsync: ${IMAPSYNC_VER}"
			echo "Installed version of Imapsync: ${IMAPSYNCV}"
			echo ""
		fi
		if [ "${IMAPSYNC_VER}" != "${IMAPSYNCV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating Imapsync${boldoff}"
				doImapsync
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}Imapsync ${IMAPSYNCV} to ${IMAPSYNC_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"imapsync\": {\n"
				printf "\t\t\"name\": \"Imapsync\",\n"
				printf "\t\t\"current\": \"${IMAPSYNCV}\",\n"
				printf "\t\t\"offered\": \"${IMAPSYNC_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ -s ${STRINGS} ]; then
		if [ -x /usr/local/bin/composer ]; then
			COMPOSERV="`strings /usr/local/bin/composer | grep -m1 'const VERSION = ' | cut -d"'" -f2`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of composer: ${COMPOSER_VER}"
				echo "Installed version of composer: ${COMPOSERV}"
				echo ""
			fi
			if [ "${COMPOSER_VER}" != "${COMPOSERV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating composer${boldoff}"
					doComposer
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}Composer ${COMPOSERV} to ${COMPOSER_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"composer\": {\n"
					printf "\t\t\"name\": \"composer\",\n"
					printf "\t\t\"current\": \"${COMPOSERV}\",\n"
					printf "\t\t\"offered\": \"${COMPOSER_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi

		if [ "${CLOUDLINUX_OPT}" = "yes" ] && [ "${PHP1_MODE_OPT}" = "lsphp" ] && [ "${MOD_LSAPI_VER}" != "0" ]; then
			if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
				if [ -s /usr/lib/apache/mod_lsapi.so ]; then
					MODLSAPIV="`${STRINGS} /usr/lib/apache/mod_lsapi.so | grep -m1 'version' | awk '{print $3}' | cut -d: -f1 | grep -o '.*[0-9][^a-z]'`"
					if [ "${VERSIONS}" = "1" ]; then
						echo "Latest version of mod_lsapi: ${MOD_LSAPI_VER}"
						echo "Installed version of mod_lsapi: ${MODLSAPIV}"
						echo ""
					fi
					if [ "${MODLSAPIV}" != "${MOD_LSAPI_VER}" ]; then
						if [ "${VERSIONS}" = "0" ]; then
							echo "${boldon}Updating mod_lsapi${boldoff}"
							doModLsapi 1
						elif [ "${VERSIONS}" = "1" ]; then
							echo "${boldon}mod_lsapi ${MODLSAPIV} to ${MOD_LSAPI_VER} update is available.${boldoff}"
							echo ""
						elif [ "${VERSIONS}" = "json" ]; then
							printf "\t\"mod_lsapi\": {\n"
							printf "\t\t\"name\": \"mod_lsapi\",\n"
							printf "\t\t\"current\": \"${MODLSAPIV}\",\n"
							printf "\t\t\"offered\": \"${MOD_LSAPI_VER}\"\n"
							printf "\t},\n"
						fi
						EXIT_CODE=$((EXIT_CODE+1))
					fi
				fi
			fi
		fi

		if [ "${CLOUDLINUX_OPT}" = "yes" ] && [ "${MOD_PROCTITLE_VER}" != "0" ]; then
			if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
				if [ -s /usr/lib/apache/mod_proctitle.so ]; then
					MODPROCTITLEV="`${STRINGS} /usr/lib/apache/mod_proctitle.so | grep -m1 'version' | awk '{print $3}' | cut -d. -f1,2`"
					if [ "${VERSIONS}" = "1" ]; then
						echo "Latest version of mod_proctitle: ${MODPROCTITLEV}"
						echo "Installed version of mod_proctitle: ${MOD_PROCTITLE_VER}"
						echo ""
					fi
					if [ "${MODPROCTITLEV}" != "${MOD_PROCTITLE_VER}" ]; then
						if [ "${VERSIONS}" = "0" ]; then
							echo "${boldon}Updating mod_proctitle${boldoff}"
							doModProctitle 1
						elif [ "${VERSIONS}" = "1" ]; then
							echo "${boldon}mod_proctitle ${MODPROCTITLEV} to ${MOD_PROCTITLE_VER} update is available.${boldoff}"
							echo ""
						elif [ "${VERSIONS}" = "json" ]; then
							printf "\t\"mod_proctitle\": {\n"
							printf "\t\t\"name\": \"mod_proctitle\",\n"
							printf "\t\t\"current\": \"${MODPROCTITLEV}\",\n"
							printf "\t\t\"offered\": \"${MOD_PROCTITLE_VER}\"\n"
							printf "\t},\n"
						fi
						EXIT_CODE=$((EXIT_CODE+1))
					fi
				fi
			fi
		fi

		if [ "${CLOUDLINUX_OPT}" = "yes" ] && [ "${MOD_HOSTINGLIMITS_VER}" != "0" ]; then
			if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
				if [ -s /usr/lib/apache/mod_hostinglimits.so ]; then
					MODHOSTINGLIMITSV="`${STRINGS} /usr/lib/apache/mod_hostinglimits.so | grep -m1 'version' | awk '{print $3}' | cut -d. -f1,2`"
					if [ "${VERSIONS}" = "1" ]; then
						echo "Latest version of mod_hostinglimits: ${MODHOSTINGLIMITSV}"
						echo "Installed version of mod_hostinglimits: ${MOD_HOSTINGLIMITS_VER}"
						echo ""
					fi
					if [ "${MODHOSTINGLIMITSV}" != "${MOD_HOSTINGLIMITS_VER}" ]; then
						if [ "${VERSIONS}" = "0" ]; then
							echo "${boldon}Updating mod_hostinglimits${boldoff}"
							doModHostingLimits 1
						elif [ "${VERSIONS}" = "1" ]; then
							echo "${boldon}mod_hostinglimits ${MODHOSTINGLIMITSV} to ${MOD_HOSTINGLIMITS_VER} update is available.${boldoff}"
							echo ""
						elif [ "${VERSIONS}" = "json" ]; then
							printf "\t\"mod_hostinglimits\": {\n"
							printf "\t\t\"name\": \"mod_hostinglimits\",\n"
							printf "\t\t\"current\": \"${MODHOSTINGLIMITSV}\",\n"
							printf "\t\t\"offered\": \"${MOD_HOSTINGLIMITS_VER}\"\n"
							printf "\t},\n"
						fi
						EXIT_CODE=$((EXIT_CODE+1))
					fi
				fi
			fi
		fi

		if [ "${MODSECURITY_OPT}" = "yes" ] && [ "${WEBSERVER_OPT}" = "apache" ] && [ "${MODSECURITY_VER}" != "0" ]; then
			if [ -s /usr/lib/apache/mod_security2.so  ]; then
				MODSECURITYV="`${STRINGS} /usr/lib/apache/mod_security2.so | grep -m1 'ModSecurity for Apache/' | cut -d/ -f2 | awk '{print $1}'`"
				if ! ${STRINGS} /usr/lib/apache/mod_security2.so | grep -m1 -q 'libyajl'; then
					MODSECURITYV="0"
				fi
			else
				MODSECURITYV="0"
			fi
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of ModSecurity: ${MODSECURITYV}"
				echo "Installed version of ModSecurity: ${MODSECURITY_VER}"
				echo ""
			fi
			if [ "${MODSECURITYV}" != "${MODSECURITY_VER}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating ModSecurity${boldoff}"
					doModSecurity
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}ModSecurity ${MODSECURITYV} to ${MODSECURITY_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"modsecurity\": {\n"
					printf "\t\t\"name\": \"ModSecurity\",\n"
					printf "\t\t\"current\": \"${MODSECURITYV}\",\n"
					printf "\t\t\"offered\": \"${MODSECURITY_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ -e /usr/local/bin/curl ]; then
		CURLV="`/usr/local/bin/curl --version | grep -m1 'libcurl' | awk '{ print $2}'`"
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of curl: OS"
			echo "Installed version of curl: ${CURLV}"
			echo ""
		fi
		if [ "OS" != "${CURLV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating cURL${boldoff}"
				doMigrateToSystemCurl
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}cURL ${CURLV} to OS update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"doMigrateToSystemCurl\": {\n"
				printf "\t\t\"name\": \"cURL\",\n"
				printf "\t\t\"current\": \"${CURLV}\",\n"
				printf "\t\t\"offered\": \"OS\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${AWSTATS_OPT}" = "yes" ] && [ "${AWSTATS_VER}" != "0" ]; then
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of AWstats: ${AWSTATS_VER}"
		fi
		AWSTATSV=0
		if [ -e /usr/local/awstats ]; then
			AWSTATSV="`ls -ld /usr/local/awstats | cut -d\> -f2 | cut -d- -f2`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Installed version of AWstats: ${AWSTATSV}"
				echo ""
			fi
		fi

		if [ "${AWSTATS_VER}" != "${AWSTATSV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating AWstats.${boldoff}"
				doawstats
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}AWstats ${AWSTATSV} to ${AWSTATS_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"awstats\": {\n"
				printf "\t\t\"name\": \"AWstats\",\n"
				printf "\t\t\"current\": \"${AWSTATSV}\",\n"
				printf "\t\t\"offered\": \"${AWSTATS_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${DOVECOT_OPT}" = "yes" ] && [ "${DOVECOT_VER}" != "0" ]; then
		if [ -e /usr/sbin/dovecot ]; then
			DOVECOTV="`/usr/sbin/dovecot --version | cut -d\  -f1`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of dovecot: ${DOVECOT_VER}"
				echo "Installed version of dovecot: ${DOVECOTV}"
				echo ""
			fi
			if [ "${DOVECOT_VER}" != "${DOVECOTV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating Dovecot${boldoff}"
					doDovecot
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}Dovecot ${DOVECOTV} to ${DOVECOT_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"dovecot\": {\n"
					printf "\t\t\"name\": \"Dovecot\",\n"
					printf "\t\t\"current\": \"${DOVECOTV}\",\n"
					printf "\t\t\"offered\": \"${DOVECOT_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ "${DOVECOT_CONF_OPT}" = "yes" ]; then
		COUNT=0
		if [ -e /etc/dovecot/dovecot.conf ]; then
			COUNT=`head -n1 /etc/dovecot/dovecot.conf | grep -c '^#'`
		fi
		if [ "${COUNT}" -gt 0 ]; then
			DOVECOT_CONFV="`head -n1 /etc/dovecot/dovecot.conf | cut -d'#' -f2`"
		else
			DOVECOT_CONFV=0
		fi

		if [ "${DOVECOT_CONFV}" = "" ]; then
			DOVECOT_CONFV=0
		fi

		COUNT=0
		if [ -e ${DOVECTCONFFILE} ]; then
			COUNT=`head -n1 ${DOVECTCONFFILE} | grep -c '^#'`
		fi
		if [ "${COUNT}" -gt 0 ]; then
			DOVECOT_CONF_VER="`head -n1 ${DOVECTCONFFILE} | cut -d'#' -f2`"
		else
			DOVECOT_CONF_VER=0
		fi

		if [ "${DOVECOT_CONF_VER}" != "0" ]; then
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of dovecot.conf: ${DOVECOT_CONF_VER}"
				echo "Installed version of dovecot.conf: ${DOVECOT_CONFV}"
				echo ""
			fi
			if [ "${DOVECOT_CONF_VER}" != "${DOVECOT_CONFV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating dovecot.conf${boldoff}"
					doDovecotConf
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}dovecot.conf ${DOVECOT_CONFV} to ${DOVECOT_CONF_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"dovecot_conf\": {\n"
					printf "\t\t\"name\": \"dovecot.conf\",\n"
					printf "\t\t\"current\": \"${DOVECOT_CONFV}\",\n"
					printf "\t\t\"offered\": \"${DOVECOT_CONF_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ "${EXIM_OPT}" = "yes" ] && [ "${EXIM_VER}" != "0" ]; then
		if [ -e /usr/sbin/exim ]; then
			EXIMV="`exim_version`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of Exim: ${EXIM_VER}"
				echo "Installed version of Exim: ${EXIMV}"
				echo ""
			fi
			if [ "${EXIM_VER}" != "${EXIMV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating Exim${boldoff}"
					doExim
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}Exim ${EXIMV} to ${EXIM_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"exim\": {\n"
					printf "\t\t\"name\": \"Exim\",\n"
					printf "\t\t\"current\": \"${EXIMV}\",\n"
					printf "\t\t\"offered\": \"${EXIM_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ -x /usr/local/bin/lego ]; then
		LEGOV="`/usr/local/bin/lego -v 2>/dev/null | awk '{print $3}'`"
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of lego: ${LEGO_VER}"
			echo "Installed version of lego: ${LEGOV}"
			echo ""
		fi
		if [ "${LEGO_VER}" != "${LEGOV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating lego${boldoff}"
				doLego
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}Lego ${LEGOV} to ${LEGO_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"lego\": {\n"
				printf "\t\t\"name\": \"lego\",\n"
				printf "\t\t\"current\": \"${LEGOV}\",\n"
				printf "\t\t\"offered\": \"${LEGO_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${EXIMCONF_OPT}" = "yes" ]; then
		local current
		local offered
		current=$(exim_conf_version)
		offered=$(set -o pipefail; head -n 1 "$(path_to_custom_file exim/exim.conf)" | awk '{ print $6 }' || echo 0)
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of exim.conf: ${offered}"
			echo "Installed version of exim.conf: ${current}"
			echo ""
		fi
		if [ "${offered}" != "${current}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating exim.conf${boldoff}"
				if ! doEximConf; then
					echo "Failed to update exim.conf" 1>&2
				fi
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}exim.conf ${current} to ${offered} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf '\t"exim_conf": {\n'
				printf '\t\t"name": "exim.conf",\n'
				printf '\t\t"current": "%s",\n' "${current}"
				printf '\t\t"offered": "%s"\n' "${offered}"
				printf '\t},\n'
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${EXIMCONF_OPT}" = "yes" ] && [ "${BLOCKCRACKING_OPT}" = "yes" ] && [ "${BLOCKCRACKING_VER}" != "0" ]; then
		COUNT=0
		if [ -e /etc/exim.blockcracking/README.txt ]; then
			COUNT=`head -n1 /etc/exim.blockcracking/README.txt | grep -c '^#'`
		fi
		if [ "${COUNT}" -gt 0 ]; then
			BLOCKCRACKINGV="`head -n1 /etc/exim.blockcracking/README.txt | cut -d'#' -f2`"
		else
			BLOCKCRACKINGV=0
		fi
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of BlockCracking: ${BLOCKCRACKING_VER}"
			echo "Installed version of BlockCracking: ${BLOCKCRACKINGV}"
			echo ""
		fi
		if [ "${BLOCKCRACKING_VER}" != "${BLOCKCRACKINGV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating BlockCracking${boldoff}"
				doBlockCracking
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}BlockCracking ${BLOCKCRACKINGV} to ${BLOCKCRACKING_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"blockcracking\": {\n"
				printf "\t\t\"name\": \"BlockCracking\",\n"
				printf "\t\t\"current\": \"${BLOCKCRACKINGV}\",\n"
				printf "\t\t\"offered\": \"${BLOCKCRACKING_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${EXIMCONF_OPT}" = "yes" ] && [ "${EASY_SPAM_FIGHTER_OPT}" = "yes" ] && [ "${EASY_SPAM_FIGHTER_VER}" != "0" ]; then
		COUNT=0
		if [ -e /etc/exim.easy_spam_fighter/README.txt ]; then
			COUNT=`head -n1 /etc/exim.easy_spam_fighter/README.txt | grep -c '^#'`
		fi
		if [ "${COUNT}" -gt 0 ]; then
			EASY_SPAM_FIGHTERV="`head -n1 /etc/exim.easy_spam_fighter/README.txt | cut -d'#' -f2`"
		else
			EASY_SPAM_FIGHTERV=0
		fi
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of Easy Spam Fighter: ${EASY_SPAM_FIGHTER_VER}"
			echo "Installed version of Easy Spam Fighter: ${EASY_SPAM_FIGHTERV}"
			echo ""
		fi
		if [ "${EASY_SPAM_FIGHTER_VER}" != "${EASY_SPAM_FIGHTERV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating Easy Spam Fighter${boldoff}"
				doEasySpamFighter
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}Easy Spam Fighter ${EASY_SPAM_FIGHTERV} to ${EASY_SPAM_FIGHTER_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"easy_spam_fighter\": {\n"
				printf "\t\t\"name\": \"Easy Spam Fighter\",\n"
				printf "\t\t\"current\": \"${EASY_SPAM_FIGHTERV}\",\n"
				printf "\t\t\"offered\": \"${EASY_SPAM_FIGHTER_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${SPAMD_OPT}" = "spamassassin" ] && [ "${SPAMASSASSIN_VER}" != "0" ]; then
		if [ -e /usr/bin/spamd ]; then
			SPAMASSASSINV=`/usr/bin/spamd --version | grep -m1 'version' | awk '{print $4}'`
		else
			SPAMASSASSINV=0
		fi
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of SpamAssassin: ${SPAMASSASSIN_VER}"
			echo "Installed version of SpamAssassin: ${SPAMASSASSINV}"
			echo ""
		fi
		if [ "${SPAMASSASSIN_VER}" != "${SPAMASSASSINV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating SpamAssassin.${boldoff}"
				dospamassassin
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}SpamAssassin ${SPAMASSASSINV} to ${SPAMASSASSIN_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"spamassassin\": {\n"
				printf "\t\t\"name\": \"SpamAssassin\",\n"
				printf "\t\t\"current\": \"${SPAMASSASSINV}\",\n"
				printf "\t\t\"offered\": \"${SPAMASSASSIN_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi
	if [ "${SPAMD_OPT}" = "rspamd" ]; then
		local current
		local offered

		current=$(rspamd_conf_version)
		offered=$(set -o pipefail; head -n 1 "$(path_to_custom_file rspamd/connect.conf)" | cut -s -d '#' -f 2 || echo 0)

		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of Rspamd Config: ${offered}"
			echo "Installed version of Rspamd Config: ${current}"
			echo ""
		fi
		if [ "${offered}" != "${current}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating Rspamd Config${boldoff}"
				do_rspamd_conf withrestart
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}Rspamd Config ${current} to ${offered} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf '\t"rspamd_conf": {\n'
				printf '\t\t"name": "Rspamd Config",\n'
				printf '\t\t"current": "%s",\n' "${current}"
				printf '\t\t"offered": "%s"\n' "${offered}"
				printf '\t},\n'
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${CLAMAV_OPT}" = "yes" ]; then
		if [ -e /usr/local/sbin/clamd ] || [ -e /usr/local/lib64/libfreshclam.so.2 ]; then
			if [ -e /usr/local/sbin/clamd ]; then
				CLAMAVV=`/usr/local/sbin/clamd --version | cut -d/ -f1 | awk '{print $2}'`
			else
				CLAMAVV=0
			fi
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of ClamAV: OS"
				echo "Installed version of ClamAV: ${CLAMAVV}"
				echo ""
			fi
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating ClamAV.${boldoff}"
				doclamav
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}ClamAV ${CLAMAVV} to OS update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"clamav\": {\n"
				printf "\t\t\"name\": \"ClamAV\",\n"
				printf "\t\t\"current\": \"${CLAMAVV}\",\n"
				printf "\t\t\"offered\": \"OS\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${MYSQL_INST_OPT}" != "no" ] && [ -e $MYSQL_BIN ] && [ "${MYSQL_VER}" != "0" ] && [ "${MARIADB_VER}" != "0" ]; then
		if [ "${MYSQL_INST_OPT}" = "mysql" ]; then
			MYSQLV="`mysql_version`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of ${MYSQLNAME}: ${MYSQL_VER}"
				echo "Installed version of ${MYSQLNAME}: ${MYSQLV}"
				echo ""
			fi
			if [ "${MYSQL_VER}" != "${MYSQLV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating ${MYSQLNAME}.${boldoff}"
					doMySQL
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}${MYSQLNAME} ${MYSQLV} to ${MYSQL_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"mysql\": {\n"
					printf "\t\t\"name\": \"${MYSQLNAME}\",\n"
					printf "\t\t\"current\": \"${MYSQLV}\",\n"
					printf "\t\t\"offered\": \"${MYSQL_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		else
			MYSQLV="`$MYSQL_BIN --version | awk '{ print $5 }' | cut -d , -f1 | cut -d- -f1`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of ${MYSQLNAME}: ${MARIADB_VER}"
				echo "Installed version of ${MYSQLNAME}: ${MYSQLV}"
				echo ""
			fi
			if [ "${MARIADB_VER}" != "${MYSQLV}" ]; then
				if [ "${VERSIONS}" = "0" ]; then
					echo "${boldon}Updating ${MYSQLNAME}.${boldoff}"
					doMySQL
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}${MYSQLNAME} ${MYSQLV} to ${MARIADB_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"mysql\": {\n"
					printf "\t\t\"name\": \"${MYSQLNAME}\",\n"
					printf "\t\t\"current\": \"${MYSQLV}\",\n"
					printf "\t\t\"offered\": \"${MARIADB_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	for php_release in `echo ${PHP1_RELEASE_SET}`; do
		php_shortrelease="`echo ${php_release} | tr -d '.'`"
		PHP_VER_VAR=PHP${php_shortrelease}_VER
		PHP_VER=${!PHP_VER_VAR}
		HAVE_FPM_CGI_VAR=HAVE_FPM${php_shortrelease}_CGI
		HAVE_FCGID_VAR=HAVE_FCGID${php_shortrelease}
		HAVE_LSPHP_VAR=HAVE_LSPHP${php_shortrelease}
		HAVE_FPM_CGI=${!HAVE_FPM_CGI_VAR}
		HAVE_FCGID=${!HAVE_FCGID_VAR}
		HAVE_LSPHP=${!HAVE_LSPHP_VAR}

		if [ "${PHP_VER}" != "0" ]; then
			if [ "${HAVE_FPM_CGI}" = "yes" ] || [ "${HAVE_FCGID}" = "yes" ] || [ "${HAVE_LSPHP}" = "yes" ]; then
				if [ -e /usr/local/php${php_shortrelease}/bin/php${php_shortrelease} ]; then
					PHPV="`/usr/local/php${php_shortrelease}/bin/php${php_shortrelease} -r 'echo phpversion();'`"
				elif [ -e /usr/local/bin/php ] && [ ! -L /usr/local/bin/php ]; then
					PHPV="`/usr/local/bin/php -r 'echo phpversion();'`"
				else
					PHPV=0
				fi
				if [ -z "${PHPV}" ]; then
					PHPV=0
				fi
				#Checks for general build-in PHP extensions, they have no updates, so, just let them appear after showing up
				if [ -x /usr/local/php${php_shortrelease}/bin/php-config ]; then
					EXTENSION_INT_EXT_DIR=`/usr/local/php${php_shortrelease}/bin/php-config --extension-dir`
					#check php-imap
					if [ "${PHP_IMAP_OPT}" = "yes" ] && [ ! -s ${EXTENSION_INT_EXT_DIR}/imap.so ]; then
						if [ "${VERSIONS}" = "1" ]; then
							echo "Latest version of PHP-IMAP ${php_release}: ${PHP_VER}"
							echo "Installed version of PHP-IMAP ${php_release}: 0"
							echo ""
						fi
						if [ "${VERSIONS}" = "0" ]; then
							echo "${boldon}Updating PHP-IMAP ${php_release}${boldoff}"
							doPHPImap ${php_release}
						elif [ "${VERSIONS}" = "1" ]; then
							echo "${boldon}PHP-IMAP ${php_release}: 0 to ${PHP_VER} update is available.${boldoff}"
							echo ""
						elif [ "${VERSIONS}" = "json" ]; then
							printf "\t\"php_imap ${php_release}\": {\n"
							printf "\t\t\"name\": \"PHP-IMAP ${php_release}\",\n"
							printf "\t\t\"current\": \"0\",\n"
							printf "\t\t\"offered\": \"${PHP_VER}\"\n"
							printf "\t},\n"
						fi
						EXIT_CODE=$((EXIT_CODE+1))
					fi
					#check php-bz2
					if [ "${PHP_BZ2_OPT}" = "yes" ] && [ ! -s ${EXTENSION_INT_EXT_DIR}/bz2.so ]; then
						if [ "${VERSIONS}" = "1" ]; then
							echo "Latest version of PHP-Bz2 ${php_release}: ${PHP_VER}"
							echo "Installed version of PHP-Bz2 ${php_release}: 0"
							echo ""
						fi
						if [ "${VERSIONS}" = "0" ]; then
							echo "${boldon}Updating PHP-Bz2 ${php_release}${boldoff}"
							doPHPBz2 ${php_release}
						elif [ "${VERSIONS}" = "1" ]; then
							echo "${boldon}PHP-Bz2 ${php_release}: 0 to ${PHP_VER} update is available.${boldoff}"
							echo ""
						elif [ "${VERSIONS}" = "json" ]; then
							printf "\t\"php_bz2 ${php_release}\": {\n"
							printf "\t\t\"name\": \"PHP-Bz2 ${php_release}\",\n"
							printf "\t\t\"current\": \"0\",\n"
							printf "\t\t\"offered\": \"${PHP_VER}\"\n"
							printf "\t},\n"
						fi
						EXIT_CODE=$((EXIT_CODE+1))
					fi
					#check php-xmlrpc
					if [ "${PHP_XMLRPC_OPT}" = "yes" ] && [ ! -s ${EXTENSION_INT_EXT_DIR}/xmlrpc.so ]; then
						if [ "${VERSIONS}" = "1" ]; then
							echo "Latest version of PHP-XMLRPC ${php_release}: ${PHP_VER}"
							echo "Installed version of PHP-XMLRPC ${php_release}: 0"
							echo ""
						fi
						if [ "${VERSIONS}" = "0" ]; then
							echo "${boldon}Updating PHP-XMLRPC ${php_release}${boldoff}"
							doPHPXmlrpc ${php_release}
						elif [ "${VERSIONS}" = "1" ]; then
							echo "${boldon}PHP-XMLRPC ${php_release}: 0 to ${PHP_VER} update is available.${boldoff}"
							echo ""
						elif [ "${VERSIONS}" = "json" ]; then
							printf "\t\"php_xmlrpc ${php_release}\": {\n"
							printf "\t\t\"name\": \"PHP-XMLRPC ${php_release}\",\n"
							printf "\t\t\"current\": \"0\",\n"
							printf "\t\t\"offered\": \"${PHP_VER}\"\n"
							printf "\t},\n"
						fi
						EXIT_CODE=$((EXIT_CODE+1))
					fi
					#check php-gmp
					if [ "${PHP_GMP_OPT}" = "yes" ] && [ ! -s ${EXTENSION_INT_EXT_DIR}/gmp.so ]; then
						if [ "${VERSIONS}" = "1" ]; then
							echo "Latest version of PHP-GMP ${php_release}: ${PHP_VER}"
							echo "Installed version of PHP-GMP ${php_release}: 0"
							echo ""
						fi
						if [ "${VERSIONS}" = "0" ]; then
							echo "${boldon}Updating PHP-GMP ${php_release}${boldoff}"
							doPHPGmp ${php_release}
						elif [ "${VERSIONS}" = "1" ]; then
							echo "${boldon}PHP-GMP ${php_release}: 0 to ${PHP_VER} update is available.${boldoff}"
							echo ""
						elif [ "${VERSIONS}" = "json" ]; then
							printf "\t\"php_gmp ${php_release}\": {\n"
							printf "\t\t\"name\": \"PHP-GMP ${php_release}\",\n"
							printf "\t\t\"current\": \"0\",\n"
							printf "\t\t\"offered\": \"${PHP_VER}\"\n"
							printf "\t},\n"
						fi
						EXIT_CODE=$((EXIT_CODE+1))
					fi
					#check php-readline
					if [ "${PHP_READLINE_OPT}" = "yes" ] && [ ! -s ${EXTENSION_INT_EXT_DIR}/readline.so ]; then
						if [ "${VERSIONS}" = "1" ]; then
							echo "Latest version of PHP-readline ${php_release}: ${PHP_VER}"
							echo "Installed version of PHP-readline ${php_release}: 0"
							echo ""
						fi
						if [ "${VERSIONS}" = "0" ]; then
							echo "${boldon}Updating PHP-readline ${php_release}${boldoff}"
							doPHPReadline ${php_release}
						elif [ "${VERSIONS}" = "1" ]; then
							echo "${boldon}PHP-readline ${php_release}: 0 to ${PHP_VER} update is available.${boldoff}"
							echo ""
						elif [ "${VERSIONS}" = "json" ]; then
							printf "\t\"php_readline ${php_release}\": {\n"
							printf "\t\t\"name\": \"PHP-readline ${php_release}\",\n"
							printf "\t\t\"current\": \"0\",\n"
							printf "\t\t\"offered\": \"${PHP_VER}\"\n"
							printf "\t},\n"
						fi
						EXIT_CODE=$((EXIT_CODE+1))
					fi
					#check php-ldap
					if [ "${PHP_LDAP_OPT}" = "yes" ] && [ ! -s ${EXTENSION_INT_EXT_DIR}/ldap.so ]; then
						if [ "${VERSIONS}" = "1" ]; then
							echo "Latest version of PHP-LDAP ${php_release}: ${PHP_VER}"
							echo "Installed version of PHP-LDAP ${php_release}: 0"
							echo ""
						fi
						if [ "${VERSIONS}" = "0" ]; then
							echo "${boldon}Updating PHP-LDAP ${php_release}${boldoff}"
							doPHPLDAP ${php_release}
						elif [ "${VERSIONS}" = "1" ]; then
							echo "${boldon}PHP-LDAP ${php_release}: 0 to ${PHP_VER} update is available.${boldoff}"
							echo ""
						elif [ "${VERSIONS}" = "json" ]; then
							printf "\t\"php_ldap ${php_release}\": {\n"
							printf "\t\t\"name\": \"PHP-LDAP ${php_release}\",\n"
							printf "\t\t\"current\": \"0\",\n"
							printf "\t\t\"offered\": \"${PHP_VER}\"\n"
							printf "\t},\n"
						fi
						EXIT_CODE=$((EXIT_CODE+1))
					fi
				fi
				if [ "${VERSIONS}" = "1" ]; then
					echo "Latest version of PHP ${php_release}: ${PHP_VER}"
					echo "Installed version of PHP ${php_release}: ${PHPV}"
					echo ""
				fi
				FPM_SECURITY_PATCH=false
				if [ "${HAVE_FPM_CGI}" = "yes" ]; then
					if [ "${php_release}" = "5.6" ] || [ "${php_release}" = "7.0" ] || [ "${php_release}" = "7.1" ] || [ "${php_release}" = "7.2" ]; then
						if ! /usr/local/php${php_shortrelease}/bin/php${php_shortrelease} -i 2>&1 | grep -m1 -q 'PHP-FPM security patch'; then
							FPM_SECURITY_PATCH=true
						fi
					fi
				fi
				if [ "${PHP_VER}" != "${PHPV}" ] || ${FPM_SECURITY_PATCH}; then
					local php_mode
					if [ "${HAVE_FPM_CGI}" = "yes" ]; then
						php_mode=php-fpm
					elif [ "${HAVE_FCGID}" = "yes" ]; then
						php_mode=fastcgi
					elif [ "${HAVE_LSPHP}" = "yes" ]; then
						php_mode=lsphp
					fi
					if [ "${VERSIONS}" = "0" ]; then
						echo "${boldon}Updating PHP ${php_release}${boldoff}"
						doPhp_build "${php_release}" "${php_mode}"
					elif [ "${VERSIONS}" = "1" ]; then
						echo "${boldon}PHP ${php_release}: ${PHPV} to ${PHP_VER} update is available.${boldoff}"
						echo ""
					elif [ "${VERSIONS}" = "json" ]; then
						printf "\t\"php_expert ${php_release} ${php_mode}\": {\n"
						printf "\t\t\"name\": \"PHP ${php_release}\",\n"
						printf "\t\t\"current\": \"${PHPV}\",\n"
						printf "\t\t\"offered\": \"${PHP_VER}\"\n"
						printf "\t},\n"
					fi
					EXIT_CODE=$((EXIT_CODE+1))
				fi
			fi
		fi
	done

	if [ "${ROUNDCUBE_OPT}" = "yes" ] && [ "${ROUNDCUBE_VER}" != "0" ]; then
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of RoundCube: ${ROUNDCUBE_VER}"
		fi
		ROUNDCUBEV=0
		if [ -e ${WWWDIR}/roundcube ]; then
			ROUNDCUBEV="`roundcube_version`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Installed version of RoundCube: ${ROUNDCUBEV}"
				echo ""
			fi
		fi
		if [ "${ROUNDCUBE_VER}" != "${ROUNDCUBEV}" ] && [ "${PHP1_RELEASE_OPT}" != "5.3" ]; then
			if [ "${VERSIONS}" = "0" ] || [ "${VERSIONS}" = "2" ]; then
				echo "${boldon}Updating RoundCube.${boldoff}"
				doroundcube
				WEBAPPS_UPDATED=true
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}RoundCube ${ROUNDCUBEV} to ${ROUNDCUBE_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"roundcube\": {\n"
				printf "\t\t\"name\": \"RoundCube\",\n"
				printf "\t\t\"current\": \"${ROUNDCUBEV}\",\n"
				printf "\t\t\"offered\": \"${ROUNDCUBE_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${UNIT_OPT}" = "yes" ] && [ "${UNIT_VER}" != "0" ]; then
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of Nginx Unit: ${UNIT_VER}"
		fi
		UNITV=0
		if [ -x /usr/sbin/unitd ]; then
			UNITV="`/usr/sbin/unitd --version 2>&1 | grep '^unit version:' | awk '{print $3}'`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Installed version of Nginx Unit: ${UNITV}"
				echo ""
			fi
		fi

		if [ "${UNIT_VER}" != "${UNITV}" ]; then
			if [ "${VERSIONS}" = "0" ]; then
				echo "${boldon}Updating Nginx Unit.${boldoff}"
				doNginxUnit
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}AWstats ${UNITV} to ${UNIT_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"unit\": {\n"
				printf "\t\t\"name\": \"Nginx Unit\",\n"
				printf "\t\t\"current\": \"${UNITV}\",\n"
				printf "\t\t\"offered\": \"${UNIT_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi
	
	if [ "${PHPMYADMIN_OPT}" = "yes" ] && [ "${PHPMYADMIN_VER}" != "0" ]; then
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of phpMyAdmin: ${PHPMYADMIN_VER}"
		fi
		PHPMYADMINV=0
		if [ -e ${WWWDIR}/phpMyAdmin ]; then
			PHPMYADMINV="`ls -ld ${WWWDIR}/phpMyAdmin | cut -d\> -f2 | cut -d- -f2,3,4`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Installed version of phpMyAdmin: ${PHPMYADMINV}"
				echo ""
			fi
		fi
		# phpMyAdmin does not support PHP 5.3 & PHP 5.4 anymore so there will be no updates available for them
		if [ "${PHP1_RELEASE_OPT}" != "5.3" ] && [ "${PHP1_RELEASE_OPT}" != "5.4" ]; then
			if [ "${PHPMYADMIN_VER}" != "${PHPMYADMINV}" ]; then
				if [ "${VERSIONS}" = "0" ] || [ "${VERSIONS}" = "2" ]; then
					echo "${boldon}Updating phpMyAdmin.${boldoff}"
					dophpMyAdmin
					WEBAPPS_UPDATED=true
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}phpMyAdmin ${PHPMYADMINV} to ${PHPMYADMIN_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"phpmyadmin\": {\n"
					printf "\t\t\"name\": \"phpMyAdmin\",\n"
					printf "\t\t\"current\": \"${PHPMYADMINV}\",\n"
					printf "\t\t\"offered\": \"${PHPMYADMIN_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ "${IONCUBE_OPT}" = "yes" ] && [ "${IONCUBE_VER}" != "0" ] && [ -x /usr/local/bin/php ]; then
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of ionCube: ${IONCUBE_VER}"
		fi
		IONCUBEV=0
		PHP_BIN=/usr/local/bin/php
		PHP_SUPPORTS_IONCUBE=true
		if [ "${PHP1_RELEASE_OPT}" = "8.0" ] && [ "${PHP2_RELEASE_OPT}" != "no" ]; then
			PHP2_BIN_VAR=PHP_BIN_PHP${PHP2_SHORTRELEASE}
			PHP_BIN=${!PHP2_BIN_VAR}
			PHP_SUPPORTS_IONCUBE=true
		elif [ "${PHP1_RELEASE_OPT}" = "8.0" ] && [ "${PHP2_RELEASE_OPT}" = "no" ]; then
			PHP_SUPPORTS_IONCUBE=false
		fi
		if ${PHP_SUPPORTS_IONCUBE}; then
			if ${PHP_BIN} -v | grep ionCube | grep -m1 -q -o ' v[^,]*'; then
				IONCUBEV="`${PHP_BIN} -v | grep ionCube | grep -m1 -o ' v[^,]*' | cut -dv -f2`"
				if [ "${VERSIONS}" = "1" ]; then
					echo "Installed version of ionCube: ${IONCUBEV}"
					echo ""
				fi
			fi
			if [ "${IONCUBE_VER}" != "${IONCUBEV}" ]; then
				if [ "${VERSIONS}" = "0" ] || [ "${VERSIONS}" = "2" ]; then
					echo "${boldon}Updating ionCube loader.${boldoff}"
					doIoncube
					WEBAPPS_UPDATED=true
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}ionCube loader ${IONCUBEV} to ${IONCUBE_VER} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf "\t\"ioncube\": {\n"
					printf "\t\t\"name\": \"ionCube\",\n"
					printf "\t\t\"current\": \"${IONCUBEV}\",\n"
					printf "\t\t\"offered\": \"${IONCUBE_VER}\"\n"
					printf "\t},\n"
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	fi

	if [ "${PHP_SNUFFLEUPAGUS_OPT}" = "yes" ] && [ "${SNUFFLEUPAGUS_VER}" != "0" ] && [ -x /usr/local/bin/php ]; then
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of snuffleupagus: ${SNUFFLEUPAGUS_VER}"
		fi
		SNUFFLEUPAGUSV=0
		if /usr/local/bin/php -i | grep -m1 'snuffleupagus support' -A1 | tail -n1 | grep -m1 -q -o '[0-9.]*' 2>/dev/null; then
			SNUFFLEUPAGUSV="`/usr/local/bin/php -i | grep -m1 'snuffleupagus support' -A1 | tail -n1 | grep -m1 -o '[0-9.]*' 2>/dev/null`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Installed version of snuffleupagus: ${SNUFFLEUPAGUSV}"
				echo ""
			fi
		fi
		if [ "${SNUFFLEUPAGUS_VER}" != "${SNUFFLEUPAGUSV}" ]; then
			if [ "${VERSIONS}" = "0" ] || [ "${VERSIONS}" = "2" ]; then
				echo "${boldon}Updating snuffleupagus.${boldoff}"
				doSnuffleupagus
				WEBAPPS_UPDATED=true
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}Snuffleupagus ${SNUFFLEUPAGUSV} to ${SNUFFLEUPAGUS_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"php_snuffleupagus\": {\n"
				printf "\t\t\"name\": \"Snuffleupagus\",\n"
				printf "\t\t\"current\": \"${SNUFFLEUPAGUSV}\",\n"
				printf "\t\t\"offered\": \"${SNUFFLEUPAGUS_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	if [ "${PHP_REDIS_OPT}" = "yes" ] && [ "${PHPREDIS_VER}" != "0" ] && [ -x /usr/local/bin/php ]; then
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of PHP-Redis: ${PHPREDIS_VER}"
		fi
		PHPREDISV=0
		if /usr/local/bin/php -i | grep -m1 -q 'Redis Version' 2>/dev/null; then
			PHPREDISV="`/usr/local/bin/php -i | grep -m1 'Redis Version' | awk '{print $4}' 2>/dev/null`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Installed version of PHP-Redis: ${PHPREDISV}"
				echo ""
			fi
		fi
		if [ "${PHPREDIS_VER}" != "${PHPREDISV}" ]; then
			if [ "${VERSIONS}" = "0" ] || [ "${VERSIONS}" = "2" ]; then
				echo "${boldon}Updating PHP-Redis.${boldoff}"
				doPHPRedis
				WEBAPPS_UPDATED=true
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}PHP-Redis ${PHPREDISV} to ${PHPREDIS_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"php_redis\": {\n"
				printf "\t\t\"name\": \"PHP-Redis\",\n"
				printf "\t\t\"current\": \"${PHPREDISV}\",\n"
				printf "\t\t\"offered\": \"${PHPREDIS_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi

	local php_version
	for php_version in "${!options_conf_php[@]}"; do
		local vv=${php_version//./}
		if [ "${PHP_IGBINARY_OPT}" = "yes" ] && php_supports_igbinary_extension "${vv}"; then
			local offered
			local current
			offered=${versions_txt[igbinary]}
			current=$("/usr/local/php${vv}/bin/php" -i 2> /dev/null | awk '/igbinary version/ {print $4}')
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of igbinary: ${offered}"
				echo "Installed version of igbinary: ${current}"
				echo ""
			fi
			if [ "${offered}" != "${current}" ]; then
				if [ "${VERSIONS}" = "0" ] || [ "${VERSIONS}" = "2" ]; then
					echo "${boldon}Updating igbinary.${boldoff}"
					command_php_igbinary "${php_version}"
					WEBAPPS_UPDATED=true
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}Igbinary (PHP ${php_version}) ${current} to ${offered} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf '\t"php_igbinary %s": {\n' "${php_version}"
					printf '\t\t"name": "Igbinary (PHP %s)",\n' "${php_version}"
					printf '\t\t"current": "%s",\n' "${current}"
					printf '\t\t"offered": "%s"\n' "${offered}"
					printf '\t},\n'
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
		if [ "${PHP_PHALCON_OPT}" = "yes" ]; then
			local offered
			if php_supports_phalcon5_extension "${vv}"; then
				offered=${versions_txt[phalcon5]}
			elif php_supports_phalcon4_extension "${vv}"; then
				offered=${versions_txt[phalcon]}
			else
				# Special care needs to be taken, this must be the last software checked in this loop, if there are more software checks continue here will skip them
				continue
			fi
			current=$(
				"/usr/local/php${vv}/bin/php" -r "echo (new Phalcon\Support\Version())->get();" 2>/dev/null \
				|| "/usr/local/php${vv}/bin/php" -r "echo Phalcon\Version::get();" 2>/dev/null \
				|| echo 0
			)
			if [ "${VERSIONS}" = "1" ]; then
				echo "Latest version of phalcon (PHP ${php_version}): ${offered}"
				echo "Installed version of phalcon (PHP ${php_version}): ${current}"
				echo ""
			fi
			if [ "${offered}" != "${current}" ]; then
				if [ "${VERSIONS}" = "0" ] || [ "${VERSIONS}" = "2" ]; then
					echo "${boldon}Updating phalcon.${boldoff}"
					command_php_phalcon "${php_version}"
					WEBAPPS_UPDATED=true
				elif [ "${VERSIONS}" = "1" ]; then
					echo "${boldon}phalcon (PHP ${php_version}) ${current} to ${offered} update is available.${boldoff}"
					echo ""
				elif [ "${VERSIONS}" = "json" ]; then
					printf '\t"php_phalcon %s": {\n' "${php_version}"
					printf '\t\t"name": "phalcon (PHP %s)",\n' "${php_version}"
					printf '\t\t"current": "%s",\n' "${current}"
					printf '\t\t"offered": "%s"\n' "${offered}"
					printf '\t},\n'
				fi
				EXIT_CODE=$((EXIT_CODE+1))
			fi
		fi
	done

	if [ "${SQUIRRELMAIL_OPT}" = "yes" ] && [ "${SQUIRRELMAIL_VER}" != "0" ]; then
		if [ "${VERSIONS}" = "1" ]; then
			echo "Latest version of SquirrelMail: ${SQUIRRELMAIL_VER}"
		fi
		SQUIRRELMAILV=0
		if [ -e ${WWWDIR}/squirrelmail ]; then
			SQUIRRELMAILV="`ls -ld ${WWWDIR}/squirrelmail | cut -d\> -f2 | cut -d- -f2,3`"
			if [ "${VERSIONS}" = "1" ]; then
				echo "Installed version of SquirrelMail: ${SQUIRRELMAILV}"
				echo ""
			fi
		fi
		if [ "${SQUIRRELMAIL_VER}" != "${SQUIRRELMAILV}" ]; then
			if [ "${VERSIONS}" = "0" ] || [ "${VERSIONS}" = "2" ]; then
				echo "${boldon}Updating SquirrelMail.${boldoff}"
				doSquirrelmail
				WEBAPPS_UPDATED=true
			elif [ "${VERSIONS}" = "1" ]; then
				echo "${boldon}SquirrelMail ${SQUIRRELMAILV} to ${SQUIRRELMAIL_VER} update is available.${boldoff}"
				echo ""
			elif [ "${VERSIONS}" = "json" ]; then
				printf "\t\"squirrelmail\": {\n"
				printf "\t\t\"name\": \"SquirrelMail\",\n"
				printf "\t\t\"current\": \"${SQUIRRELMAILV}\",\n"
				printf "\t\t\"offered\": \"${SQUIRRELMAIL_VER}\"\n"
				printf "\t},\n"
			fi
			EXIT_CODE=$((EXIT_CODE+1))
		fi
	fi
	
	checkSecurity ${VERSIONS}
	
	if [ "${VERSIONS}" = "1" ]; then
		echo "If you want to update all the available versions run: ${boldon}$0 update_versions${boldoff}"
	elif [ "${VERSIONS}" = "0" ]; then
		#update_versions 0 for success, reset to 0 from count. Compile failures would have already exited.
		EXIT_CODE=0
	elif [ "${VERSIONS}" = "json" ]; then
		echo "}"
	fi

	if ${EXEC_CL_COMMANDS_ONCE} && [ "${VERSIONS}" != "2" ]; then
		cagefsctl_update
	elif ${WEBAPPS_UPDATED} && [ "${CLOUDLINUX_OPT}" = "yes" ] && [ "${VERSIONS}" = "2" ]; then
		cagefsctl_update
	fi
}

doVersions_ajax() {
	echo "HTTP/1.1 200 OK"
	echo "Content-Type: text/plain"
	echo ""

	COUNT=`doVersions 1 | grep -c 'is available'`
	if [ "${COUNT}" -gt 0 ]; then
		echo "document.getElementById(\"cb_updates\").innerHTML=\"${COUNT}\";"
		echo "document.getElementById(\"cb_updates\").style.visibility=\"visible\";"
	fi
}

####################################################

doRemoveSuggest() {
	REMOVAL_MODE=$1

	if [ "${REMOVAL_MODE}" = "json" ]; then
		echo "{"
	fi

	if [ -e /usr/sbin/httpd ]; then
		if [ "${WEBSERVER_OPT}" != "apache" ] && [ "${WEBSERVER_OPT}" != "nginx_apache" ] && [ "${WEBSERVER_OPT}" != "litespeed" ] && [ "${WEBSERVER_OPT}" != "openlitespeed" ] && [ "${APACHE2_VER}" != "0" ]; then
			if [ "${WEBSERVER_OPT}" = "nginx" ]; then
				if [ "${REMOVAL_MODE}" = "1" ]; then
					echo "Apache installed, but not enabled in options.conf: './build remove_apache'"
				elif [ "${REMOVAL_MODE}" = "0" ]; then
					doRemoveApache2
				elif [ "${REMOVAL_MODE}" = "json" ]; then
					printf "\t\"remove_apache\": {\n"
					printf "\t\t\"name\": \"Apache\"\n"
					printf "\t},\n"
				fi
			fi
		fi
	fi

	if [ -e /usr/sbin/unitd ] && [ "${UNIT_OPT}" != "yes" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "Nginx Unit installed, but not enabled in options.conf: './build remove_unit'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemoveUnit
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_unit\": {\n"
			printf "\t\t\"name\": \"Nginx Unit\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -e /usr/sbin/nginx ]; then
		if [ "${WEBSERVER_OPT}" != "nginx" ] && [ "${WEBSERVER_OPT}" != "nginx_apache" ] && [ "${NGINX_VER}" != "0" ]; then
			if [ "${REMOVAL_MODE}" = "1" ]; then
				echo "Nginx installed, but not enabled in options.conf: './build remove_nginx'"
			elif [ "${REMOVAL_MODE}" = "0" ]; then
				doRemoveNginx
			elif [ "${REMOVAL_MODE}" = "json" ]; then
				printf "\t\"remove_nginx\": {\n"
				printf "\t\t\"name\": \"Nginx\"\n"
				printf "\t},\n"
			fi
		fi
	fi

	if [ -d /usr/local/lsws ]; then
		if [ "${WEBSERVER_OPT}" != "litespeed" ] && [ "${WEBSERVER_OPT}" != "openlitespeed" ] && [ "${LITESPEED_VER}" != "0" ]; then
			if [ "${REMOVAL_MODE}" = "1" ]; then
				echo "LiteSpeed installed, but not enabled in options.conf: './build remove_litespeed'"
			elif [ "${REMOVAL_MODE}" = "0" ]; then
				doRemoveLiteSpeed
			elif [ "${REMOVAL_MODE}" = "json" ]; then
				printf "\t\"remove_litespeed\": {\n"
				printf "\t\t\"name\": \"LiteSpeed\"\n"
				printf "\t},\n"
			fi
		fi
	fi

	for php_release in `echo ${PHP1_RELEASE_SET}`; do
		php_shortrelease="`echo ${php_release} | tr -d '.'`"
		if [ -d /usr/local/php${php_shortrelease} ] && [ "${PHP1_RELEASE_OPT}" != "${php_release}" ] && [ "${PHP2_RELEASE_OPT}" != "${php_release}" ]  && [ "${PHP3_RELEASE_OPT}" != "${php_release}" ] && [ "${PHP4_RELEASE_OPT}" != "${php_release}" ]; then
			PHP_REMOVAL_VERSION_NUMBER=${versions_txt["php${php_shortrelease}"]}
			if [ "${PHP_REMOVAL_VERSION_NUMBER}" != "0" ]; then
				if [ "${REMOVAL_MODE}" = "1" ]; then
					echo "PHP ${php_release} installed, but not enabled in options.conf: './build remove_php ${php_release}'"
				elif [ "${REMOVAL_MODE}" = "0" ]; then
					doRemovePhp ${php_release}
				elif [ "${REMOVAL_MODE}" = "json" ]; then
					printf "\t\"remove_php ${php_release}\": {\n"
					printf "\t\t\"name\": \"PHP ${php_release}\"\n"
					printf "\t},\n"
				fi
			fi
		fi
	done

	if [ -e  /usr/sbin/dovecot ]  && [ "${DOVECOT_OPT}" != "yes" ] && [ "${DOVECOT_VER}" != "0" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "Dovecot installed, but not enabled in options.conf: './build remove_dovecot'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemoveDovecot
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_dovecot\": {\n"
			printf "\t\t\"name\": \"Dovecot\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -e /usr/sbin/proftpd ] && [ "${FTPD_OPT}" != "proftpd" ] && [ "${PROFTPD_VER}" != "0" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "ProFTPd installed, but not enabled in options.conf: './build remove_proftpd'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemoveProftpd
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_proftpd\": {\n"
			printf "\t\t\"name\": \"ProFTPd\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -e /usr/sbin/pure-ftpd ] && [ "${FTPD_OPT}" != "pureftpd" ] && [ "${PUREFTPD_VER}" != "0" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "Pure-FTPd installed, but not enabled in options.conf: './build remove_pureftpd'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemovePureftpd
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_pureftpd\": {\n"
			printf "\t\t\"name\": \"Pure-FTPd\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -d /etc/exim.easy_spam_fighter ] && [ "${EASY_SPAM_FIGHTER_OPT}" != "yes" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "Easy Spam Fighter installed, but not enabled in options.conf: './build remove_easy_spam_fighter'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemoveEasySpamFighter
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_easy_spam_fighter\": {\n"
			printf "\t\t\"name\": \"Easy Spam Fighter\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -d /etc/exim.blockcracking ] && [ "${BLOCKCRACKING_OPT}" != "yes" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "BlockCracking installed, but not enabled in options.conf: './build remove_blockcracking'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemoveBlockCracking
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_blockcracking\": {\n"
			printf "\t\t\"name\": \"BlockCracking\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -e /usr/local/bin/rspamd ] && [ "${SPAMD_OPT}" != "rspamd" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "Rspamd installed, but not enabled in options.conf: './build remove_rspamd'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			do_remove_rspamd
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_rspamd\": {\n"
			printf "\t\t\"name\": \"Rspamd\"\n"
			printf "\t},\n"
		fi
	fi
	
	if [ -d /etc/exim/rspamd ] && [ "${SPAMD_OPT}" != "rspamd" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "Rspamd_conf installed, but not enabled in options.conf: './build remove_rspamd_conf'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			do_remove_rspamd_conf
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_rspamd_conf\": {\n"
			printf "\t\t\"name\": \"Rspamd Conf\"\n"
			printf "\t},\n"
		fi
	fi	

	if [ -e /usr/bin/spamd ] && [ "${SPAMD_OPT}" != "spamassassin" ] && [ "${SPAMASSASSIN_VER}" != "0" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "SpamAssassin installed, but not enabled in options.conf: './build remove_spamassassin'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemoveSpamassassin
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_spamassassin\": {\n"
			printf "\t\t\"name\": \"SpamAssassin\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -e /usr/local/sbin/clamd ] && [ "${CLAMAV_OPT}" != "yes" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "ClamAV installed, but not enabled in options.conf: './build remove_clamav'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemoveClamav
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_clamav\": {\n"
			printf "\t\t\"name\": \"ClamAV\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -e /var/www/html/roundcube ] && [ "${ROUNDCUBE_OPT}" != "yes" ] && [ "${ROUNDCUBE_VER}" != "0" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "RoundCube webmail installed, but not enabled in options.conf: './build remove_roundcube'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemoveRoundcube
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_roundcube\": {\n"
			printf "\t\t\"name\": \"RoundCube\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -e /var/www/html/squirrelmail ] && [ "${SQUIRRELMAIL_OPT}" != "yes" ] && [ "${SQUIRRELMAIL_VER}" != "0" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "SquirrelMail webmail installed, but not enabled in options.conf: './build remove_squirrelmail'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemoveSquirrelmail
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_squirrelmail\": {\n"
			printf "\t\t\"name\": \"SquirrelMail\"\n"
			printf "\t},\n"
		fi
	fi

	if [ -e /var/www/html/phpMyAdmin ] && [ "${PHPMYADMIN_OPT}" != "yes" ] && [ "${PHPMYADMIN_VER}" != "0" ]; then
		if [ "${REMOVAL_MODE}" = "1" ]; then
			echo "phpMyAdmin installed, but not enabled in options.conf: './build remove_phpmyadmin'"
		elif [ "${REMOVAL_MODE}" = "0" ]; then
			doRemovephpMyAdmin
		elif [ "${REMOVAL_MODE}" = "json" ]; then
			printf "\t\"remove_phpmyadmin\": {\n"
			printf "\t\t\"name\": \"phpMyAdmin\"\n"
			printf "\t},\n"
		fi
	fi

	if [ "${REMOVAL_MODE}" = "1" ]; then
		echo ""
		echo "If you want to remove all the suggested programs above, run: ${boldon}$0 remove_items${boldoff}"
	elif [ "${REMOVAL_MODE}" = "json" ]; then
		echo "}"
	fi
}

####################################################

doAll() {
	if [ ! -d /usr/local/sysbk ]; then
		appendLdSoConf || return 1
		addYumExcludes || return 1

		#We need to have /etc/virtual ready for new installs of DA
		createEtcVirtual || return 1

		doSysbk || return 1
	fi

	command_bind || return 1

	if [ "${CSF_OPT}" = "yes" ]; then
		command_csf || return 1
	fi

	doMajordomo || return 1

	if [ "${WEBSERVER_OPT}" = "apache" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		doApache2 || return 1
		if [ "${HAVE_FCGID}" = "yes" ]; then
			doModFCGID || return 1
		fi
	fi
	if [ "${WEBSERVER_OPT}" = "litespeed" ]; then
		doLiteSpeed || return 1
	fi
	if [ "${WEBSERVER_OPT}" = "openlitespeed" ]; then
		doOpenLiteSpeed || return 1
	fi
	if [ "${WEBSERVER_OPT}" = "nginx" ] || [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		doNginx || return 1
	fi

	if [ "${WEBSERVER_OPT}" = "nginx_apache" ]; then
		doModAclr2 || return 1
	fi

	if [ "${MODSECURITY_OPT}" = "yes" ] && [ "${WEBSERVER_OPT}" != "nginx" ] && [ "${WEBSERVER_OPT}" != "nginx_apache" ] && [ "${MODSECURITY_VER}" != "0" ]; then
		doModSecurity || return 1
	fi

	if [ "${MODSECURITY_OPT}" = "yes" ] && [ "${WEBSERVER_OPT}" != "apache" ] && [ "${WEBSERVER_OPT}" != "litespeed" ] && [ "${WEBSERVER_OPT}" != "openlitespeed" ] && [ "${MODSECURITY_VER}" != "0" ]; then
		doLibModSecurity || return 1
	fi

	if [ "${CLOUDLINUX_OPT}" != "yes" ]; then
		SKIP_BRWAP=false
		if systemd-detect-virt | grep -m1 -q -E 'lxc|openvz'; then
			if [ -e /dev/.lxc/proc/self/uid_map ]; then
				if ! cat /dev/.lxc/proc/self/uid_map >/dev/null 2>&1; then
					SKIP_BRWAP=false
				else
					SKIP_BRWAP=true
				fi
			else
				SKIP_BRWAP=true
			fi
		fi
		if ! ${SKIP_BRWAP}; then
			doJailshell || return 1
		fi
	fi

	if [ "${MYSQL_INST_OPT}" != "no" ]; then
		doMySQL || return 1
	fi

	if [ "${EXIM_OPT}" = "yes" ] && [ "${EXIM_VER}" != "0" ]; then
		doExim || return 1
	fi

	if [ "${CLAMAV_OPT}" = "yes" ]; then
		doclamav || return 1
	fi

	doPhp n || return 1

	if [ "${IMAGICK_OPT}" != "no" ]; then
		doImageMagick || return 1
	fi

	if [ "${WEBALIZER_OPT}" = "yes" ] && [ "${WEBALIZER_VER}" != "0" ]; then
		doWebalizer || return 1
	fi

	if [ "${AWSTATS_OPT}" = "yes" ] && [ "${AWSTATS_VER}" != "0" ]; then
		doawstats || return 1
	fi

	if [ "${DOVECOT_OPT}" = "yes" ] && [ "${DOVECOT_VER}" != "0" ]; then
		doDovecot || return 1
	fi

	if [ "${FTPD_OPT}" = "proftpd" ] && [ "${PROFTPD_VER}" != "0" ]; then
		doProftpd || return 1
	fi

	if [ "${FTPD_OPT}" = "pureftpd" ] && [ "${PUREFTPD_VER}" != "0" ]; then
		doPureftpd || return 1
	fi
	
	if [ "${FTPD_OPT}" = "no" ]; then
		doNoFtpd || return 1
	fi

	if [ "${SPAMD_OPT}" = "spamassassin" ] && [ "${SPAMASSASSIN_VER}" != "0" ]; then
		dospamassassin || return 1
	fi
	
	if [ "${REDIS_OPT}" = "yes" ]; then
		doRedis || return 1
	fi

	if [ "${SPAMD_OPT}" = "rspamd" ] && [ "${SPAMASSASSIN_VER}" != "0" ]; then
		doRspamd || return 1
		do_rspamd_conf withrestart || return 1
	fi

	chown -R root:root ${WORKDIR}

	if [ "${UNIT_OPT}" = "yes" ] && [ "${UNIT_VER}" != "0" ]; then
		doNginxUnit || return 1
	fi

	if [ "${ROUNDCUBE_OPT}" = "yes" ] && [ "${ROUNDCUBE_VER}" != "0" ]; then
		doroundcube || return 1
	fi

	if [ "${PHPMYADMIN_OPT}" = "yes" ] && [ "${PHPMYADMIN_VER}" != "0" ]; then
		dophpMyAdmin || return 1
	fi

	if [ "${SQUIRRELMAIL_OPT}" = "yes" ] && [ "${SQUIRRELMAIL_VER}" != "0" ]; then
		doSquirrelmail || return 1
	fi

	if [ "${EXIMCONF_OPT}" = "yes" ]; then
		doEximConf || return 1
	fi

	if [ "${BLOCKCRACKING_OPT}" = "yes" ]; then
		doBlockCracking || return 1
	fi

	if [ "${EASY_SPAM_FIGHTER_OPT}" = "yes" ]; then
		doEasySpamFighter || return 1
	fi

	if [ "${PHP_INI_OPT}" = "yes" ]; then
		doPhpIni || return 1
	fi

	doWP || return 1

	doImapsync || return 1

	doLego || return 1

	if [ "${CRON_OPT}" = "yes" ] && [ "${SPAMD_OPT}" = "spamassassin" ]; then
		dospamassassinCron || return 1
	fi

	if [ -s /usr/local/directadmin/scripts/setup.txt ]; then
		if grep -m1 -q '^hostname=$' /usr/local/directadmin/scripts/setup.txt; then
			echo "Fixing empty hostname in /usr/local/directadmin/scripts/setup.txt..."
			perl -pi -e 's|^hostname=$|hostname=server.yourdirectadminserver.com|g' /usr/local/directadmin/scripts/setup.txt
		fi
		if grep -m1 -q '^ns1=ns1\.$' /usr/local/directadmin/scripts/setup.txt; then
			perl -pi -e 's|^ns1=ns1\.$|ns1=ns1.yourdirectadminserver.com|g' /usr/local/directadmin/scripts/setup.txt
		fi
		if grep -m1 -q '^ns2=ns2\.$' /usr/local/directadmin/scripts/setup.txt; then
			perl -pi -e 's|^ns2=ns2\.$|ns2=ns2.yourdirectadminserver.com|g' /usr/local/directadmin/scripts/setup.txt
		fi
		if grep -m1 -q '^email=admin@$' /usr/local/directadmin/scripts/setup.txt; then
			perl -pi -e 's|^email=admin@$|email=admin@yourdirectadminserver.com|g' /usr/local/directadmin/scripts/setup.txt
		fi
	fi
	printf "\n\n\n"
	echo "*************************************"
	echo "*				   *"
	echo "*   All parts have been installed   *"
	echo "*				   *"
	echo "*************************************"
	echo ""
	doGrubConf || return 1
}

doHook "$1" pre
case "$1" in
	# Software build commands
	all)                       enable_logging; doChecks; exec_with_lock clean_after command_all;;
	apache)                    enable_logging; doChecks; exec_with_lock clean_after doApache2;;
	majordomo)                 enable_logging; doChecks; exec_with_lock clean_after doMajordomo;;
	bind)                      enable_logging;           exec_with_lock             command_bind;;
	csf)                       enable_logging;           exec_with_lock clean_after command_csf;;
	csf_conf)                  enable_logging;           exec_with_lock             command_csf_conf;;
	sysbk)                     enable_logging;           exec_with_lock clean_after doSysbk;;
	litespeed)                 enable_logging; doChecks; exec_with_lock clean_after doLiteSpeed;;
	openlitespeed)             enable_logging; doChecks; exec_with_lock clean_after doOpenLiteSpeed;;
	litespeed_license)         enable_logging; doChecks; exec_with_lock clean_after doLiteSpeedLicense 1;;
	php_extensions)            enable_logging; doChecks; exec_with_lock clean_after doExtensionsSetup;;
	php_imagick|imagick)       enable_logging; doChecks; exec_with_lock clean_after doIMagick;;
	php_phalcon)               enable_logging; doChecks; exec_with_lock             command_php_phalcon "${@:2}";;
	php_psr)                   enable_logging; doChecks; exec_with_lock clean_after command_php_psr;;
	php_bz2)                   enable_logging; doChecks; exec_with_lock clean_after doPHPBz2;;
	php_imap)                  enable_logging; doChecks; exec_with_lock clean_after doPHPImap;;
	php_redis)                 enable_logging; doChecks; exec_with_lock clean_after doPHPRedis;;
	php_xmlrpc)                enable_logging; doChecks; exec_with_lock clean_after doPHPXmlrpc;;
	php_gmp)                   enable_logging; doChecks; exec_with_lock clean_after doPHPGmp;;
	php_readline)              enable_logging; doChecks; exec_with_lock clean_after doPHPReadline;;
	php_ldap)                  enable_logging; doChecks; exec_with_lock clean_after doPHPLDAP;;
	php_htscanner2)            enable_logging; doChecks; exec_with_lock clean_after doPHPHtscanner "$2" 1;;
	php_suhosin|suhosin)       enable_logging; doChecks; exec_with_lock clean_after doSuhosin;;
	php_snuffleupagus)         enable_logging; doChecks; exec_with_lock clean_after doSnuffleupagus;;
	php_igbinary)              enable_logging; doChecks; exec_with_lock             command_php_igbinary "${@:2}";;
	php_opcache|opcache)       enable_logging; doChecks; exec_with_lock clean_after doOpcache;;
	php_zend|zend)             enable_logging; doChecks; exec_with_lock clean_after doZend;;
	php_ioncube|ioncube)       enable_logging; doChecks; exec_with_lock clean_after doIoncube;;
	redis)                     enable_logging;           exec_with_lock clean_after doRedis;;
	imagemagick)               enable_logging; doChecks; exec_with_lock clean_after doImageMagick;;
	nginx)                     enable_logging; doChecks; exec_with_lock clean_after doNginx;;
	nginx_apache)              enable_logging; doChecks; exec_with_lock clean_after command_nginx_apache;;
	mod_lsapi)                 enable_logging; doChecks; exec_with_lock             doModLsapi 1;;
	mod_hostinglimits)         enable_logging; doChecks; exec_with_lock clean_after doModHostingLimits 1;;
	mod_proctitle)             enable_logging; doChecks; exec_with_lock clean_after doModProctitle 1;;
	modsecurity)               enable_logging; doChecks; exec_with_lock clean_after doLibModSecurity;;
	modsecurity_connector)     enable_logging; doChecks; exec_with_lock clean_after doModSecurityConnector 1;;
	libmodsecurity)            enable_logging; doChecks; exec_with_lock clean_after doLibModSecurity 1;;
	modsec-sdbm-util)          enable_logging; doChecks; exec_with_lock clean_after doModSecsdbmutil;;
	modsecurity_rules)         enable_logging; doChecks; exec_with_lock clean_after doModSecurityRules;;
	modsecurity_ruleset)       enable_logging; doChecks; exec_with_lock clean_after doModSecurityRules;;
	mod_aclr2)                 enable_logging; doChecks; exec_with_lock clean_after doModAclr2;;
	mod_htscanner2)            enable_logging; doChecks; exec_with_lock clean_after doModHtscanner;;
	mod_fcgid)                 enable_logging; doChecks; exec_with_lock clean_after doModFCGID;;
	phpMyAdmin|phpmyadmin|pma) enable_logging; doChecks; exec_with_lock clean_after dophpMyAdmin;;
	roundcube)                 enable_logging; doChecks; exec_with_lock clean_after doroundcube;;
	squirrelmail)              enable_logging; doChecks; exec_with_lock clean_after doSquirrelmail;;
	rewrite_confs)             enable_logging; doChecks; exec_with_lock clean_after doRewriteConfs;;
	secure_php)                enable_logging;           exec_with_lock clean_after secure_php;;
	awstats)                   enable_logging;           exec_with_lock clean_after doawstats;;
	unit)                      enable_logging;           exec_with_lock clean_after doNginxUnit;;
	unit_modules)              enable_logging;           exec_with_lock clean_after doNginxUnit_modules;;
	unit_module)               enable_logging;           exec_with_lock clean_after doNginxUnit_module "$2" "$3";;
	webalizer)                 enable_logging;           exec_with_lock clean_after doWebalizer;;
	proftpd)                   enable_logging; doChecks; exec_with_lock clean_after doProftpd;;
	pureftpd|pure-ftpd)        enable_logging; doChecks; exec_with_lock clean_after doPureftpd;;
	noftpd)                    enable_logging; doChecks; exec_with_lock clean_after doNoFtpd;;
	mysql)                     enable_logging; doChecks; exec_with_lock clean_after doMySQL;;
	mariadb)                   enable_logging; doChecks; exec_with_lock clean_after doMySQL;;
	compile_mysql_binary)      enable_logging;           exec_with_lock clean_after compile_mysql_binary;;
	setup_my_cnf)              enable_logging;           exec_with_lock clean_after setup_my_cnf;;
	exim)                      enable_logging; doChecks; exec_with_lock clean_after doExim;;
	eximconf|exim_conf)        enable_logging; doChecks; exec_with_lock clean_after doEximConf;;
	dovecotconf|dovecot_conf)  enable_logging; doChecks; exec_with_lock clean_after doDovecotConf;;
	grubconf|grub_conf)        enable_logging;           exec_with_lock clean_after doGrubConf;;
	blockcracking)             enable_logging; doChecks; exec_with_lock clean_after doBlockCracking;;
	easy_spam_fighter)         enable_logging; doChecks; exec_with_lock clean_after doEasySpamFighter;;
	rspamd_conf)               enable_logging; doChecks; exec_with_lock clean_after do_rspamd_conf withrestart;;
	php)                       enable_logging; doChecks; exec_with_lock clean_after doPhp;;
	php_expert)                enable_logging; doChecks; exec_with_lock clean_after doPhp_build "$2" "$3";;
	php_ini)                   enable_logging; doChecks; exec_with_lock clean_after doPhpIni;;
	dovecot)                   enable_logging; doChecks; exec_with_lock clean_after doDovecot;;
	xapian)                    enable_logging; doChecks; exec_with_lock clean_after doXapian;;
	fts-xapian)                enable_logging; doChecks; exec_with_lock clean_after doFTSXapian;;
	jailshell)                 enable_logging;           exec_with_lock clean_after doJailshell;;
	pigeonhole)                enable_logging; doChecks; exec_with_lock clean_after doPigeonhole;;
	spamassassin|spamd)        enable_logging; doChecks; exec_with_lock clean_after dospamassassin;;
	rspamd)                    enable_logging; doChecks; exec_with_lock clean_after doRspamd;;
	netdata)                   enable_logging;           exec_with_lock clean_after doNetdata;;
	spamassassin_cron)         enable_logging;           exec_with_lock clean_after dospamassassinCron;;
	clamav)                    enable_logging;           exec_with_lock clean_after doclamav;;
	csfpingore)                enable_logging;           exec_with_lock clean_after doCSFpignore;;
	composer)                  enable_logging;           exec_with_lock clean_after doComposer;;
	wp)                        enable_logging;           exec_with_lock clean_after doWP;;
	imapsync)                  enable_logging;           exec_with_lock clean_after doImapsync;;
	lego|letsencrypt)          enable_logging;           exec_with_lock clean_after doLego;;
	# Misc actions
	update)                                                                         doUpdateDA;;
	update_script)                                                                  doUpdateDA;;
	update_da)                                                                      doUpdateDA;;
	versions)                                  doChecks;                            doVersions 1;;
	versions_nobold)                           doChecks;                            BOLD_OPT=no; boldon=""; boldoff=""; doVersions 1;;
	update_versions)           enable_logging; doChecks; exec_with_lock clean_after doVersions 0 "$3";;
	update_versions_full)      enable_logging; doChecks; exec_with_lock clean_after doVersions 0 full;;
	update_full)               enable_logging; doChecks; exec_with_lock clean_after doVersions 0 full;;
	update_webapps)            enable_logging; doChecks; exec_with_lock clean_after doVersions 2;;
	clean)                     enable_logging;           exec_with_lock             command_clean;;
	clean_cache)               enable_logging;           exec_with_lock             command_clean_cache;;
	clean_old_webapps)         enable_logging;           exec_with_lock             doclean_old_webapps;;
	clean_old_tarballs)        enable_logging;           exec_with_lock             doclean_old_tarballs;;
	options)                   enable_logging; doChecks;                            options;;
	options_nobold)            enable_logging; doChecks;                            BOLD_OPT=no; boldon=""; boldoff=""; options;;
	create_options)            enable_logging;                                      create_options;;
	used_configs)              enable_logging;                                      used_configs;;
	deprecation_check)                                                              doDeprecationChecks ;;
	litespeed_license_migrate) enable_logging;                                      ${LSWS_HOME}/bin/lshttpd -r;;
	doMigrateToSystemCurl)     enable_logging;           exec_with_lock clean_after doMigrateToSystemCurl;;
	set)                                                                            command_set "$2" "$3";;
	set_php)                                                                        command_set_php "$2" "$3";;
	check_options)                             doChecks;;
	version)                                                                        showVersion;;
	set_service)                                                                    set_service "$2" "$3";;
	opt_help)                                                                       allSettings "$2";;
	gen_help)                                                                       generateHelp;;
	versions_ajax)                                                                  doVersions_ajax;;
	kill)                                                                           doKill;;
	mysql_backup|backup_mysql) enable_logging;           exec_with_lock clean_after doMySQLback;;
	get_timezone)                                                                   getTimezone;;
	check_download_urls)                                                            doCheckDownloadURLS;;
	cron)                                                                           doCron;;
	cron_execute)              enable_logging; doChecks;                            command_cron_execute;;
	install)                   enable_logging;           exec_with_lock             command_install;;
	# Software removal
	remove_nghttp2)            enable_logging;           exec_with_lock clean_after doRemoveNghttp2;;
	remove_unit)               enable_logging;           exec_with_lock clean_after doRemoveUnit;;
	remove_apache)             enable_logging;           exec_with_lock clean_after doRemoveApache2;;
	remove_nginx)              enable_logging;           exec_with_lock clean_after doRemoveNginx;;
	remove_litespeed)          enable_logging;           exec_with_lock clean_after doRemoveLiteSpeed;;
	remove_php)                enable_logging;           exec_with_lock clean_after doRemovePhp "$2";;
	remove_easy_spam_fighter)  enable_logging;           exec_with_lock clean_after doRemoveEasySpamFighter;;
	remove_blockcracking)      enable_logging;           exec_with_lock clean_after doRemoveBlockCracking;;
	remove_spamassassin)       enable_logging;           exec_with_lock clean_after doRemoveSpamassassin;;
	remove_rspamd)             enable_logging;           exec_with_lock clean_after do_remove_rspamd;;
	remove_rspamd_conf)        enable_logging;           exec_with_lock clean_after do_remove_rspamd_conf;;
	remove_dovecot)            enable_logging;           exec_with_lock clean_after doRemoveDovecot;;
	remove_proftpd)            enable_logging;           exec_with_lock clean_after doRemoveProftpd;;
	remove_pureftpd)           enable_logging;           exec_with_lock clean_after doRemovePureftpd;;
	remove_squirrelmail)       enable_logging;           exec_with_lock clean_after doRemoveSquirrelmail;;
	remove_phpmyadmin)         enable_logging;           exec_with_lock clean_after doRemovephpMyAdmin;;
	remove_roundcube)          enable_logging;           exec_with_lock clean_after doRemoveRoundcube;;
	remove_items)              enable_logging;           exec_with_lock clean_after doRemoveSuggest 0;;
	list_removals)                                                                  doRemoveSuggest 1;;
	# GUI plugin only commands
	settings_json)                                                                  allSettingsJSON;;
	versions_json)                                                                  doVersions json | perl -0p -e 's/\},\n\}/\}\n\}/';;
	list_configs_json)                                                              listConfigsJSON;;
	list_removals_json)                                                             doRemoveSuggest json | perl -0p -e 's/\},\n\}/\}\n\}/';;
	dump_build_software)                                                            command_dump_build_software;;
	dump_actions)                                                                   command_dump_actions;;
	# Obsolete commands
	plugin)                    true;;
	custombuild_plugin)        true;;
	update_data)               true;;
	set_fastest)               true;;
	set_fastest_quiet)         true;;
	* )                                                                             showHelp; exit 0;;
esac
doHook "$1" post

exit ${EXIT_CODE}
