#!/bin/bash
### Copyright 1999-2025. WebPros International GmbH. All rights reserved.
#

#
# Plesk script
#



#default values

product_default_conf()
{

PRODUCT_ROOT_D=/opt/psa
PRODUCT_RC_D=/etc/init.d
PRODUCT_ETC_D=/opt/psa/etc
PLESK_LIBEXEC_DIR=/usr/lib/plesk-9.0
HTTPD_VHOSTS_D=/var/www/vhosts
HTTPD_CONF_D=/etc/apache2
HTTPD_INCLUDE_D=/etc/apache2/conf-enabled
HTTPD_BIN=/usr/sbin/apache2
HTTPD_LOG_D=/var/log/apache2
HTTPD_SERVICE=apache2
QMAIL_ROOT_D=/var/qmail
PLESK_MAILNAMES_D=/var/qmail/mailnames
RBLSMTPD=/usr/sbin/rblsmtpd
NAMED_RUN_ROOT_D=/var/named/run-root
WEB_STAT=/usr/bin/webalizer
MYSQL_VAR_D=/var/lib/mysql
MYSQL_BIN_D=/usr/bin
MYSQL_SOCKET=/var/run/mysqld/mysqld.sock
PGSQL_DATA_D=/var/lib/postgresql/10/main
PGSQL_CONF_D=/etc/postgresql/10/main
PGSQL_BIN_D=/usr/lib/postgresql/10/bin
DUMP_D=/var/lib/psa/dumps
DUMP_TMP_D=/tmp
MAILMAN_ROOT_D=/usr/lib/mailman
MAILMAN_VAR_D=/var/lib/mailman
PYTHON_BIN=/usr/bin/python2
GPG_BIN=/usr/bin/gpg
TAR_BIN=/usr/lib/plesk-9.0/sw-tar
AWSTATS_ETC_D=/etc/awstats
AWSTATS_BIN_D=/usr/lib/cgi-bin
AWSTATS_TOOLS_D=/usr/share/awstats/tools
AWSTATS_DOC_D=/usr/share/awstats
OPENSSL_BIN=/usr/bin/openssl
LIB_SSL_PATH=/lib/libssl.so
LIB_CRYPTO_PATH=/lib/libcrypto.so
CLIENT_PHP_BIN=/opt/psa/bin/php-cli
SNI_SUPPORT=true
APS_DB_DRIVER_LIBRARY=/usr/lib/x86_64-linux-gnu/sw/libmysqlserver.so.2.0
SA_MAX_MAIL_SIZE=256000

}

### Copyright 1999-2025. WebPros International GmbH. All rights reserved.

# echo message to product log and console (always visible)
pp_echo()
{
    if [ -n "$product_log" ] ; then
        echo "$@" >> "$product_log" 2>&1
    fi
    echo "$@" >&2
}

# echo message to product log, also to console in debug mode
p_echo()
{
    if [ -n "$product_log" ] ; then
        echo "$@" >> "$product_log" 2>&1
    fi
    if [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" -o -z "$product_log" ] ; then
        echo "$@" >&2
    fi
}

# same as p_echo, but without new line
pnnl_echo()
{
	p_echo -n "$@"
}

int_err()
{
	report_problem "internal" "Internal error: $@"
	exit 1
}

echo_try()
{
	msg="$*"
	pnnl_echo " Trying to $msg... "
}

suc()
{
	p_echo "done"
}
### Copyright 1999-2025. WebPros International GmbH. All rights reserved.
reexec_with_clean_env()
{
	# Usage: call this function as 'reexec_with_clean_env "$@"' at the start of a script.
	#        Don't use with scripts that require sensitive environment variables.
	#        Don't put the call under any input/output redirection.
	# Purpose: make sure the script is executed with a sane environment.

	local lc="`get_default_locale`"
	export LANG="$lc" LC_MESSAGES="$lc" LC_ALL="$lc"
	export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
	umask 022

	PLESK_SCRIPT_COMMAND_LINE="$0 $*"
	[ -z "$PLESK_INSTALLER_ENV_CLEANED" ] || { unset PLESK_INSTALLER_ENV_CLEANED; return 0; }
	[ -n "$BASH" ] || exec /bin/bash "$0" "$@"

	# N.B.: the following code requires Bash. On Dash it would cause syntax error upon parse w/o eval.
	eval '
	local extra_vars=()                     # list of variables to preserve
	for var in "${!PLESK_@}"; do            # enumerate all PLESK_* variables
		extra_vars+=("$var=${!var}")
	done
	extra_vars+=("PLESK_INSTALLER_ENV_CLEANED=1")

	# Exec self with clean env except for extra_vars, shell opts, and arguments.
	exec /usr/bin/env -i "${extra_vars[@]}" /bin/bash ${-:+-$-} "$0" "$@" || {
		echo "Failed to reexec self ($0) with clean environment" >&2
		exit 91		# Just some relatively unique error code
	}
	'
}

get_default_locale()
{
	# Note that CentOS 7 typically doesn't have C.UTF-8
	for lc in "C.UTF-8" "en_US.UTF-8" "C"; do
		if [ -z "`LC_ALL=$lc locale 2>&1 >/dev/null`" ]; then
			echo "$lc"
			return 0
		fi
	done
	echo "C"
}

detect_vz()
{
	[ -z "$PLESK_VZ_RESULT" ] || return $PLESK_VZ_RESULT

	PLESK_VZ_RESULT=1
	PLESK_VZ=0
	PLESK_VE_HW_NODE=0
	PLESK_VZ_TYPE=

	local issue_file="/etc/issue"
	local vzcheck_file="/proc/self/status"
	[ -f "$vzcheck_file" ] || return 1

	local env_id=`sed -ne 's|^envID\:[[:space:]]*\([[:digit:]]\+\)$|\1|p' "$vzcheck_file"`
	[ -n "$env_id" ] || return 1
	if [ "$env_id" = "0" ]; then
		# Either VZ/OpenVZ HW node or unjailed CloudLinux
		PLESK_VE_HW_NODE=1
		return 1
	fi

	if grep -q "CloudLinux" "$issue_file" >/dev/null 2>&1 ; then
		return 1
	fi

	if [ -f "/proc/vz/veredir" ]; then
		PLESK_VZ_TYPE="vz"
	elif [ -d "/proc/vz" ]; then
		PLESK_VZ_TYPE="openvz"
	fi

	PLESK_VZ=1
	PLESK_VZ_RESULT=0
	return 0
}

# detects lxc and docker containers
detect_lxc()
{
	[ -z "$PLESK_LXC_RESULT" ] || return $PLESK_LXC_RESULT
	PLESK_LXC_RESULT=1
	PLESK_LXC=0
	if  { [ -f /proc/1/cgroup ] && grep -q 'docker\|lxc' /proc/1/cgroup; } || \
		{ [ -f /proc/1/environ ] && cat /proc/1/environ | tr \\0 \\n | grep -q "container=lxc"; };
	then
		PLESK_LXC_RESULT=0
		PLESK_LXC=1
	fi
	return "$PLESK_LXC_RESULT"
}

call_optional_function()
{
	local type_output="`LC_ALL=C type \"$1\" 2>/dev/null | head -n 1`"
	case "$type_output" in
		*function)
			"$@"
			;;
		*)
			return 0
			;;
	esac
}

problems_log_tail()
{
	[ -f "$product_problems_log" ] || return 0
	{
		tac "$product_problems_log" | awk '/^START/ { exit } { print }' | tac
	} 2>/dev/null
}

product_log_tail()
{
	[ -f "$product_log" ] || return 0
	{
		tac "$product_log" | awk '/^START/ { exit } { print }' | tac
	} 2>/dev/null
}

product_and_problems_log_tail()
{
	product_log_tail
	[ "$product_log" = "$product_problems_log" ] || problems_log_tail
}
### Copyright 1999-2025. WebPros International GmbH. All rights reserved.

construct_report_template()
{
	local severity="${1:-error}"
	local summary="$2"

	local update_ticket="`get_update_ticket`"

	set_error_report_source
	set_error_report_component
	set_error_report_params
	set_error_report_environment

	true construct_report_code construct_report_debug construct_report_message

cat <<-EOL
<?xml version="1.0" encoding="UTF-8" ?>
<error>
  <source>$report_source</source>
  <severity>$severity</severity>
  <datetime>`date --iso-8601=seconds`</datetime>

  <component>$report_component</component>
  <summary><![CDATA[`echo "$summary" | sed -e 's/\]\]>/] ]>/g'`]]></summary>
  <message encoding="base64">`construct_report_message | base64`</message>

  <additional_info>
    <component_params encoding="base64">$report_params</component_params>
    <code encoding="base64">`construct_report_code | base64`</code>
    <debug encoding="base64">`construct_report_debug | base64`</debug>
    <environment encoding="base64">$report_environment</environment>
    <update_ticket>$update_ticket</update_ticket>
  </additional_info>
</error>
EOL
}

construct_report_code()
{
	local call_level=${1:-5}
	local func_level=$[call_level - 1]
	local lineno_func=${BASH_LINENO[ $func_level ]}
	local script_name=${BASH_SOURCE[ $[func_level + 1] ]}

	echo "# Call of ${FUNCNAME[$func_level]}() from ${FUNCNAME[$[func_level + 1]]}() at `readlink -m $script_name`:${BASH_LINENO[$func_level]}"
	head -n $[lineno_func + 4] "$script_name" 2>/dev/null | tail -n 8
}

construct_report_debug()
{
	local call_level=${1:-5}
	call_level=$[call_level-1]

	# Generate calls stack trace.
	for i in `seq $call_level ${#FUNCNAME[@]}`; do
		[ "${FUNCNAME[$i]}" != "main" ] || break

		local func_call="`sed -n -e "${BASH_LINENO[$i]}p" "${BASH_SOURCE[$[i+1]]}" 2>/dev/null |
			sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'`"
		[ -n "$func_call" -a -z "${func_call##*${FUNCNAME[$i]}*}" ] || func_call="${FUNCNAME[$i]}"
		echo "#$[i - $call_level] `readlink -m ${BASH_SOURCE[$[i+1]]}`(${BASH_LINENO[$i]}): $func_call"
	done
}

construct_report_message()
{
	product_and_problems_log_tail

	echo ""
	if [ -n "$report_context" ]; then
		echo "Context: $report_context"
		echo ""
	fi
	if [ -n "$RP_LOADED_PATCHES" ]; then
		echo "Loaded runtime patches: $RP_LOADED_PATCHES"
		echo ""
	fi
}

# Construct report to send it to our errors tracker
construct_report()
{
	local severity="${1:-error}"
	local summary="$2"

	[ -n "$summary" ] || int_err "Unable to send error report. Some parameters are not defined."

	set_error_report_source
	get_product_versions

	construct_report_template "$severity" "$summary" \
		| $PRODUCT_ROOT_D/admin/bin/send-error-report --version "$product_this_version" $report_source >/dev/null 2>&1
}

# Use this function to report failed actions.
# Typical report should contain
# - reason or problem description (example: file copying failed)
# - how to resolve or investigate problem (example: check file permissions, free disk space)
# - how to re-run action (example: perform specific command, restart bootstrapper script, run installation again)
report_problem()
{
	local severity="${1:-error}"

	# Get first string of error as a summary of report
	shift

	local summary="$1"

	[ -n "$product_problems_log" ] || product_problems_log="/dev/stderr"

	p_echo
	if [ "0$problems_occured" -eq 0 ]; then
		echo "***** $process problem report *****" >> "$product_problems_log" 2>&1
	fi
	for problem_message in "$@"; do
		p_echo "$problem_message"
		if [ "$product_log" != "$product_problems_log" ]; then
			echo "$problem_message" >> "$product_problems_log" 2>&1
		fi
	done
	p_echo

	construct_report "$severity" "$summary"

	[ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" ] || \
		product_log_tail

	problems_occured=1
}

set_error_report_source()
{
	[ -z "$1" ] || report_source="$1"
	[ -n "$report_source" ] || {
		if [ -n "$PACKAGE_ID" -o -n "$PACKAGE_ACTION" -o -n "$PACKAGE_NAME" -o -n "$PACKAGE_VERSION" ]; then
			report_source="install"
		else
			report_source="backend"
		fi
	}
}

set_error_report_component()
{
	local component="$1"

	if [ "$report_source" = "install" ]; then
		[ -n "$report_component" ] || report_component="$PACKAGE_ID"
		return 0
	fi

	[ -z "$component" ] || report_component="$1"
	[ -n "$report_component" ] || report_component="`basename $0`"
}

set_error_report_params()
{
	if [ "$report_source" = "install" ]; then
		[ -n "$report_params" ] || report_params="`echo "$PACKAGE_ACTION of $PACKAGE_NAME $PACKAGE_VERSION" | base64`"
		return 0
	fi

	[ -z "$*" ] || report_params="`echo "$*" | base64`"
	[ -n "$report_params" ] || report_params="`echo "$PLESK_SCRIPT_COMMAND_LINE" | base64`"
}

detect_virtualization()
{
	detect_vz
	detect_lxc
	local is_docker="`[ -f "/.dockerenv" ] && echo yes || :`"
	local systemd_detect_virt_ct="`/usr/bin/systemd-detect-virt -c 2>/dev/null | grep -v '^none$' || :`"
	local systemd_detect_virt_vm="`/usr/bin/systemd-detect-virt -v 2>/dev/null | grep -v '^none$' || :`"
	local virt_what="`/usr/sbin/virt-what 2>/dev/null | xargs || :`"

	if [ -n "$is_docker" ]; then
		echo "docker $virt_what"
	elif [ "$PLESK_VZ" = "1" ]; then
		echo "${PLESK_VZ_TYPE:-virtuozzo}"
	elif [ "$PLESK_LXC" = "1" ]; then
		echo "lxc $virt_what"
	elif [ -n "$systemd_detect_virt_ct" ]; then
		echo "$systemd_detect_virt_ct $systemd_detect_virt_vm"
	elif [ -n "$virt_what" ]; then
		echo "$virt_what"
	elif [ -n "$systemd_detect_virt_vm" ]; then
		echo "$systemd_detect_virt_vm"
	fi
}

default_error_report_environment()
{
	local virtualization="`detect_virtualization`"

	if [ -n "$virtualization" ]; then
		echo "virtualization: $virtualization"
	fi
}

set_error_report_environment()
{
	[ -z "$*" ] || report_environment="`echo "$*" | base64`"
	[ -n "$report_environment" ] || report_environment="`default_error_report_environment | base64`"
}

get_update_ticket()
{
	[ -r $PRODUCT_ROOT_D/var/update_ticket ] && cat $PRODUCT_ROOT_D/var/update_ticket | awk '{$1=$1};1'
}
### Copyright 1999-2025. WebPros International GmbH. All rights reserved.

#
# Support for runtime patching of shell scripts (including utilities and package scripts).
#

# --- Service functions ---

# Load and apply a patch in a relatively safe way
rp_safe_load_patch()
{
	local patch_file="$1"
	echo_try "load shell patch '$patch_file'"
	/bin/sh -n "$RP_BASEDIR/$patch_file" && 
	{
		. "$RP_BASEDIR/$patch_file"
		RP_LOADED_PATCHES="$RP_LOADED_PATCHES $patch_file"
	} &&
	suc
}

# Apply patches specific to the current context (e.g., depending on utility basename or package name)
# This is currently not implemented. This may be overriden by "spark".
rp_patch_runtime_context_specific()
{
	:
}

# --- Main entry points ---

rp_patch_runtime()
{
	# List of loaded patch files
	RP_LOADED_PATCHES=

	local RP_BASEDIR="$PRODUCT_BOOTSTRAPPER_DIR/rp"
	[ -d "$RP_BASEDIR" ] || return 0

	if [ -r "$RP_BASEDIR/spark" ]; then
		rp_safe_load_patch "spark"
	fi

	call_optional_function rp_patch_runtime_context_specific "$@"
}

### Copyright 1999-2025. WebPros International GmbH. All rights reserved.

get_user_id()
{
	local name="$1"

	[ -n "$name" ] || int_err "Wrong value of argument 'name': $name"

	getent passwd "$name" 2>/dev/null | awk -F':' '{print $3}'
}
### Copyright 1999-2025. WebPros International GmbH. All rights reserved.
# vim:ft=sh

initial_conf()
{
	PRODNAME="psa"
	PRODUCT_NAME="psa"
	product=${PRODNAME}
	PRODUCT_FULL_NAME="Plesk"

	product_etc="/etc/${PRODNAME}"
	prod_conf_t="/etc/psa/psa.conf"

	support_contact="https://support.plesk.com/"

	conceived_os_vendor=Ubuntu
	conceived_os_version="18.04"

	clients_group="psacln"
	clients_GID="10001"

	services_group="psaserv"
	services_GID="10003"

	product_suff="saved_by_${product}".`date "+%m.%d;%H:%M"`
	product_suffo="saved_by_${product}"

	# plesk default password
	PRODUCT_DEFAULT_PASSWORD="setup"
}

read_conf()
{
	[ -n "$prod_conf_t" ] || prod_conf_t=/etc/psa/psa.conf

	if [ -s $prod_conf_t ]; then
		tmp_var=`perl -e 'undef $/; $_=<>; s/#.*$//gm;
		         s/^\s*(\S+)\s*/$1=/mg;
		         print' $prod_conf_t`
		eval $tmp_var
	else
		if ! is_product_installation; then
			p_echo "Unable to find product configuration file: $prod_conf_t. Default values will be used."
			return 1
		fi
	fi
	return 0
}

### Copyright 1999-2025. WebPros International GmbH. All rights reserved.
# vim:ft=sh:

#set_params

set_common_params()
{
	common_var=0

	PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
	LANG="`get_default_locale`"
	export PATH LANG
	unset GREP_OPTIONS
	umask 022
	ulimit -n 65535 2>/dev/null

	get_product_versions

	certificate_file="$PRODUCT_ETC_D/httpsd.pem"
	services="/etc/services"

	crontab="/usr/bin/crontab"

	SYSTEM_RC_D="/etc/init.d"
	PLESK_LIBEXEC_DIR="/usr/lib/plesk-9.0"
	PLESK_DB_DIR="/var/lib/plesk"
	PRODUCT_BOOTSTRAPPER_DIR="`printf "/opt/psa/bootstrapper/pp%s-bootstrapper" "$product_this_version"`"
	AUTOGENERATED_CONFIGS="#ATTENTION!\n#\n#DO NOT MODIFY THIS FILE BECAUSE IT WAS GENERATED AUTOMATICALLY,\n#SO ALL YOUR CHANGES WILL BE LOST THE NEXT TIME THE FILE IS GENERATED.\n"
	AUTOGENERATED_CONFIGS_UPGRADE="#ATTENTION!\n#\n#DO NOT MODIFY THIS FILE BECAUSE IT WAS GENERATED AUTOMATICALLY,\n#SO ALL YOUR CHANGES WILL BE LOST AFTER YOU UPGRADE PLESK.\n"
	PRODUCT_LOGS_D="/var/log/plesk"

	sendmail="/usr/sbin/sendmail"
	ps="ps axw"
	ifconfig="/sbin/ifconfig -a"

	machine="linux"
	if [ -f /etc/debian_version ]; then
		linux_distr="debian"
	else
		linux_distr="redhat"
	fi

	dummy_home="/"
	if [ -x /usr/sbin/nologin ]; then
		dummy_shell="/usr/sbin/nologin"
	else
		dummy_shell="/bin/false"
	fi

	rp_patch_runtime
}

get_product_versions()
{
	# Don't use global variables set elsewhere in this code. Use substitutions if needed.
	local prod_root_d="/opt/psa"

	product_name="psa"

	if [ -z "$product_this_version" ]; then
		# 1. Try to fetch version from file created by bootstrapper (should be 3-component).
		product_this_version="`cat "/var/lock/plesk-target-version" 2>/dev/null`"
		# 2. Fallback to $PRODUCT_ROOT_D/version (should be 3-component).
		if [ -z "$product_this_version" -a -r "$prod_root_d/version" ]; then
			product_this_version="`awk '{ print $1 }' "$prod_root_d/version"`"
		fi
		# 3. Fallback to hardcoded version (2-component). This may cause some other code to fail.
		if [ -z "$product_this_version" ]; then
			product_this_version="18.0"
			echo "Unable to determine \$product_this_version, will use less precise value '$product_this_version'" >&2
		fi
	fi

	product_version="$product_this_version"

	if [ -z "$product_prev_version" ]; then
		if [ -r "$prod_root_d/version.upg" ]; then
			product_prev_version=`awk '{ print $1 }' "$prod_root_d/version.upg"`
		elif [ -r "$prod_root_d/version" ]; then
			product_prev_version=`awk '{ print $1 }' "$prod_root_d/version"`
		else
			product_prev_version="$product_this_version"
		fi
	fi
}

# Clean installation of the product is being performed
is_product_installation()
{
	[ "X$do_upgrade" != "X1" -a ! -s "/opt/psa/version.upg" ]
}

### Copyright 1999-2025. WebPros International GmbH. All rights reserved.

# vim:ft=sh:

reexec_with_clean_env "$@"

prog="`basename $0`"

usage() {
cat << EOT
	Usage: $prog --domain-name domain --sys-user-login user [--webspace-name webspace] [--verbose]

		--domain-name		domain		upgrade specified domain. Mandatory.
		--sys-user-login	login		FTP system user login for specified domain. Mandatory.
		--webspace-name		webspace	Webspace name, if specified domain is addon (optional)
		--verbose						Be more verbose
EOT
	exit 1
}

while [ "$#" -gt 0 ]; do
	case "$1" in
		--domain-name)
			if [ "$#" -ge 2 ]; then
				domain="$2"
				shift 2
			else
				echo "Not enough arguments" >&2
				echo >&2
				usage
			fi
			;;
		--sys-user-login)
			if [ "$#" -ge 2 ]; then
				user="$2"
				shift 2
			else
				echo "Not enough arguments" >&2
				echo >&2
				usage
			fi
			;;
		--webspace-name)
			if [ "$#" -ge 2 ]; then
				webspace="$2"
				shift 2
			else
				echo "Not enough arguments" >&2
				echo >&2
				usage
			fi
			;;
		--verbose)
			verbose=1
			shift
			;;
		-h|--help)
			usage
			;;
		*)
			echo "Unknown argument '$1'"
			echo
			usage
		;;
	esac
done

if [ -z "$domain" -o -z "$user" ]; then
	echo "Either --sys-user-login or --domain-name not specified" >&2
	echo  >&2
	usage
fi

info()
{
	if [ -n "$verbose" -o -n "$PLESK_INSTALLER_VERBOSE" -o -n "$PLESK_INSTALLER_DEBUG" ]; then
		echo $@
	fi
}

remove_stale_symlink_if_exists()
{
	local domain=$1
	local entry=$2

	if [ -z "$domain" -o -z "$entry" ]; then
		echo "remove_stale_symlink: either domain or entry not specified" >&2
		return 1
	fi

	local path="./$domain/$entry"
	if [ -L "$path" -a ! -e "$path" ]; then
		info "Removing broken symlink to $entry directory"
		unlink "$path" || rc=1
	fi
}

update_vhost()
{
	rc=0
	local domain="$1"
	local user="$2"
	local webspace="$3"

	if [ -z "`get_user_id $user`" ]; then
		echo "User '$user' does not exist" >&2
		exit 1
	fi

	if [ ! -d "./system" ]; then
		info "Creating system directory"
		if ! mkdir ./system; then
			echo "Cannot create 'system' folder" >&2
			return 1
		fi
	fi

	# Main domain directory should have 0710 sysuser:psaserv
	if [ -d "./$domain" ]; then
		chown "$user:psaserv" "./$domain" || rc=1
		chmod 0710 "./$domain" || rc=1
		remove_stale_symlink_if_exists "$domain" ".plesk"
		remove_stale_symlink_if_exists "$domain" "logs"
	elif [ -z "$webspace" ]; then
		# if [ ! -d "./$domain" ] then this is likely a sub-domain on upgrade from Plesk 9 
		# (in which case ./system/$domain/logs/ was already created by CU during upgrade)
		# or already upgraded addon or sub-domain
		echo "Domain '$domain' directory does not exist and it is not an addon or sub-domain"
		exit 1
	fi


	# set correct permissions on error_docs
	if [ -d "./${domain}/error_docs" ]; then
		chown -R "$user:psacln" "./$domain/error_docs" || rc=1
	fi

	# set correct owner on anon anon_ftp/conf (root/psaserv -> $user/psaserv, actual at least for 11.0.9)
	if [ -d "./${domain}/anon_ftp/conf" ]; then
		chown "$user:psaserv" "./$domain/anon_ftp/conf" || rc=1
	fi

	# Create system area
	if [ ! -e "./system/$domain" ]; then
		info "Creating system/$domain directory"
		if ! mkdir "./system/$domain"; then
			echo "Cannot create ./system/$domain" >&2
			return 1
		fi
		chown root:psaserv ./system/$domain || rc=1
		chmod 0711 ./system/$domain || rc=1
	fi

	# pd/ should be in system area
	if [ ! -e "./system/$domain/pd" -a -e "./$domain/pd" ]; then
		info "Relocating pd directory with password files for protected directories"
		mv -f "./$domain/pd" "./system/$domain/pd" || rc=1
		chmod 0710 "./system/$domain/pd" || rc=1
		find  -P ./system/$domain/pd/ -maxdepth 1 -type f \
			-execdir chown root:psaserv {} \+ \
			-execdir chmod 0640 {} \+
	elif [ ! -e "./system/$domain/pd" -a -e "./$domain/.plesk/pd" ]; then
		info "Relocating pd directory with password files for protected directories (11.5.21)"
		mv -f "./$domain/.plesk/pd" "./system/$domain/pd" || rc=1
	elif [ ! -e "./system/$domain/pd" -a -e "./system/$domain/.plesk/pd" ]; then
		info "Relocating pd directory with password files for protected directories (11.5.22)"
		mv -f "./system/$domain/.plesk/pd" "./system/$domain/pd" || rc=1
	fi

	# logs/ should be in system area and have 0700 psaadm:root
	if [ -z "$webspace" -a -d "./$domain/logs" -a ! -L "./$domain/logs" -a -z "`find \"./$domain/logs\" -type f 2>/dev/null`" -a -n "`find \"./$domain/logs\" -mindepth 1 -type d 2>/dev/null`" ]; then
		# Workaround upgrade issue from Plesk 9.x due to subdomains upgrade (creates new domains) before running this script
		# The condition above assumes that no additional files are created by relink-vhost-logs utility (such as README)!
		rm -rf "./$domain/logs"
	fi

	if [ ! -e "./system/$domain/logs" -a ! -L "./system/$domain/logs" -a -d "./$domain/logs" ]; then
		info "Relocating logs directory (<< 11.5.22)"
		mv -f "./$domain/logs" "./system/$domain/logs" || rc=1
	fi

	if [ ! -e "./system/$domain/logs" -a ! -L "./system/$domain/logs" -a -d "./$domain/statistics/logs" -a ! -L "./$domain/statistics/logs" ]; then
		info "Relocating logs directory"
		mv -f "./$domain/statistics/logs" "./system/$domain/logs" || rc=1
	fi

	if [ -d "./system/$domain/logs" -a ! -L "./system/$domain/logs" ]; then
		chown psaadm:root ./system/$domain/logs
		chmod 0700 ./system/$domain/logs
	fi

	# statistics/ should be in system area
	local had_statistics="yes"; [ -e "./$domain/statistics" ] || had_statistics=

	if [ ! -e "./system/$domain/statistics" -a -e "./$domain/statistics" ]; then
		info "Relocating statistics directory"
		mv -f "./$domain/statistics" "./system/$domain/statistics" || rc=1
	elif [ ! -e "./system/$domain/statistics" -a -e "./$domain/.plesk/statistics" ]; then
		info "Relocating statistics directory (11.5.21)"
		mv -f "./$domain/.plesk/statistics" "./system/$domain/statistics" || rc=1
	elif [ ! -e "./system/$domain/statistics" -a -e "./system/$domain/.plesk/statistics" ]; then
		info "Relocating statistics directory (11.5.22)"
		mv -f "./system/$domain/.plesk/statistics" "./system/$domain/statistics" || rc=1
	fi
	# set new owner and permissions on statistics directory 
	if [ -d "./system/$domain/statistics" ]; then
	 	chmod 0550 "./system/$domain/statistics" || rc=1
		chown root:psaserv "./system/$domain/statistics" || rc=1
	fi

	# conf/ should be in system area
	local had_conf="yes"; [ -e "./$domain/conf" ] || had_conf=

	if [ ! -e "./system/$domain/conf" -a -e "./$domain/conf" ]; then
		info "Relocating conf directory"
		mv -f "./$domain/conf" "./system/$domain/conf" || rc=1
	elif [ ! -e "./system/$domain/conf" -a -e "./$domain/.plesk/conf" ]; then
		info "Relocating conf directory (11.5.21)"
		mv -f "./$domain/.plesk/conf" "./system/$domain/conf" || rc=1
	elif [ ! -e "./system/$domain/conf" -a -e "./system/$domain/.plesk/conf" ]; then
		info "Relocating conf directory (11.5.22)"
		mv -f "./system/$domain/.plesk/conf" "./system/$domain/conf" || rc=1
	fi

	# Compatibility symlinks to conf/ and statistics/ to support customized Apache configuration and other crazy stuff
	if [ -n "$had_conf" -a \( ! -e "./$domain/conf" -o -L "./$domain/conf" \) ]; then
		info "Creating compat symlink for $domain/conf"
		ln -snf "../system/$domain/conf" "./$domain/conf" || rc=1
	fi

	if [ -n "$had_statistics" -a \( ! -e "./$domain/statistics" -o -L "./$domain/statistics" \) ]; then
		info "Creating compat symlink for $domain/statistics"
		ln -snf "../system/$domain/statistics" "./$domain/statistics" || rc=1
	fi

	# etc/php.ini should be in system area
	if [ ! -e "./system/$domain/etc/php.ini" -a -f "./$domain/etc/php.ini" ]; then
		info "Relocating etc/php.ini file"
		mkdir "./system/$domain/etc"
		chown root:0 "./system/$domain/etc/"
		mv -f "./$domain/etc/php.ini" "./system/$domain/etc/php.ini" || rc=1
		rmdir "./$domain/etc" >/dev/null 2>&1
	fi

	# logs/ should be hardlinked from system area if this is a webspace (main domain)
	if [ -z "$webspace" -a \( ! -e "./$domain/logs" -o -L "./$domain/logs" \) -a -d "./system/$domain/logs" ]; then
		info "Hardlink logs from system area"
		unlink "./$domain/logs" >/dev/null 2>&1
		$PRODUCT_ROOT_D/admin/sbin/relink-vhost-logs --create --domain-name "$domain" --sys-user-login "$user" || rc=1
	fi

	# There should be convenience symlink statistics/logs in system area
	if [ ! -e "./system/$domain/statistics/logs" -o -L "./system/$domain/statistics/logs" ]; then
		info "Symlink statistics/logs for backward compatibility"
		ln -snf "../logs" "./system/$domain/statistics/logs"
	fi

	if [ -z "$webspace" ]; then
		# Atempt to remove .plesk for webspace if upgrade from 20, 21
		rmdir "./system/$domain/.plesk" "./$domain/.plesk" >/dev/null 2>&1
	fi

	[ -n "$webspace" ] || return $rc

	if [ ! -d "$webspace" ]; then
		pp_echo "Webspace '$webspace' directory does not exist"
		return 1
	fi

	if [ ! -d "./system/$webspace" ]; then
		pp_echo "Webspace '$webspace' system directory does not exist"
		return 1
	fi

	# Remove possible leftover symlinks
	unlink "./$domain/logs" >/dev/null 2>&1
	unlink "./system/$domain/logs" >/dev/null 2>&1

	# logs/ of addon or sub-domain should be in system area and have 0700 psaadm:root
	if [ ! -e "./system/$domain/logs" -a -d "./$webspace/logs/$domain" ]; then
		info "Relocating addon domain logs directory (11.5.21)"
		mv -f "./$webspace/logs/$domain" "./system/$domain/logs" || rc=1
		chown psaadm:root ./system/$domain/logs
		chmod 0700 ./system/$domain/logs

	elif [ ! -e "./system/$domain/logs" -a -e "./system/$webspace/logs/$domain" -a ! -L "./system/$webspace/logs/$domain" ]; then
		info "Relocating addon domain logs directory (11.5.22)"
		mv -f "./system/$webspace/logs/$domain" "./system/$domain/logs" || rc=1
	fi

	# logs/ of addon or sub-domain should be hardlinked from system area to ./domain.tld/logs/child-domain.tld/
	if [ \( ! -e "./$webspace/logs/$domain" -o -L "./$webspace/logs/$domain" \) -a -d "./system/$domain/logs" ]; then
		info "Hardlink logs from system area of addon domain into webspace"
		unlink "./system/$webspace/logs/$domain" >/dev/null 2>&1 # remove symlink created in previews before 11.5.29
		unlink "./$webspace/logs/$domain" >/dev/null 2>&1 # if logs/ is not a symlink already, but logs/$domain is
		$PRODUCT_ROOT_D/admin/sbin/relink-vhost-logs --create --domain-name "$domain" --sys-user-login "$user" --webspace-name "$webspace" || rc=1
	fi

	# Remove possible leftover empty .plesk directory and links
	unlink "./$domain/.plesk" >/dev/null 2>&1
	unlink "./system/$domain/.plesk" >/dev/null 2>&1
	rmdir "./system/$domain/.plesk" "./system/$webspace/.plesk/$domain" "./$webspace/.plesk/$domain" "./system/$webspace/.plesk" "./$webspace/.plesk" >/dev/null 2>&1

	return $rc
}

product_default_conf
initial_conf
set_common_params
read_conf

cd $HTTPD_VHOSTS_D

if [ -n "$webspace" ]; then
	info "Performing update of webspace $webspace first"
 	if ! update_vhost $webspace $user; then
		pp_echo "Failed to update parent webspace $webspace for domain $domain"
		exit 1
	fi
fi

if ! update_vhost $domain $user $webspace; then
	pp_echo "Failed to update domain $domain"
	exit 1
else
	pp_echo "Upgrade of domain $domain completed successfully"
fi
