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

#
# Plesk script
#



#default values

product_default_conf()
{

PRODUCT_ROOT_D=/usr/local/psa
PRODUCT_RC_D=/etc/rc.d/init.d
PRODUCT_ETC_D=/usr/local/psa/etc
PLESK_LIBEXEC_DIR=/usr/lib64/plesk-9.0
HTTPD_VHOSTS_D=/var/www/vhosts
HTTPD_CONF_D=/etc/httpd/conf
HTTPD_INCLUDE_D=/etc/httpd/conf.d
HTTPD_BIN=/usr/sbin/httpd
HTTPD_LOG_D=/var/log/httpd
HTTPD_SERVICE=httpd
QMAIL_ROOT_D=/var/qmail
PLESK_MAILNAMES_D=/var/qmail/mailnames
RBLSMTPD=/usr/sbin/rblsmtpd
NAMED_RUN_ROOT_D=/var/named/chroot
WEB_STAT=/usr/bin/webalizer
MYSQL_VAR_D=/var/lib/mysql
MYSQL_BIN_D=/usr/bin
MYSQL_SOCKET=/var/lib/mysql/mysql.sock
PGSQL_DATA_D=/var/lib/pgsql/data
PGSQL_CONF_D=/var/lib/pgsql/data
PGSQL_BIN_D=/usr/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/lib64/plesk-9.0/sw-tar
AWSTATS_ETC_D=/etc/awstats
AWSTATS_BIN_D=/usr/share/awstats/wwwroot/cgi-bin
AWSTATS_TOOLS_D=/usr/share/awstats/tools
AWSTATS_DOC_D=/usr/share/awstats/wwwroot
OPENSSL_BIN=/usr/bin/openssl
LIB_SSL_PATH=/lib/libssl.so
LIB_CRYPTO_PATH=/lib/libcrypto.so
CLIENT_PHP_BIN=/usr/local/psa/bin/php-cli
SNI_SUPPORT=true
APS_DB_DRIVER_LIBRARY=/usr/lib64/sw/libmysqlserver.so.2.0
SA_MAX_MAIL_SIZE=256000

}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.

#admin

set_admin_params()
{

	ADMIN_ROOT=$PRODUCT_ROOT_D/admin

	UTILS_DIR=$ADMIN_ROOT/sbin

	admin_user="${product}adm"
	admin_UID=8444
	admin_group="${product}adm"
	admin_GID=8444

	ADMIN_CERT="$ADMIN_ROOT/conf/httpsd.pem"
}

get_certificate()
{
	local dst="$1"
	local src="${certificate_file}"
# Check or generate new default certificate
	[ -s "$src" ] || generate_default_certificate
 	set_ac 0 0 0400 "${src}"
	cp -fp $src $dst
}

generate_default_certificate()
{
	# Currently I have no will to accurately rewrite the stuff below
	# so I just add support for (optional) file parameter. Actually
	# one need to accurately handle temporary files, directory creation
	# etc. Probably next time...
	local cert_file

	cert_file="${certificate_file}"
	if [ -s "$cert_file" ]; then
		p_echo "default certificate already exists"
		return
	fi

	# This var also can safely be made local. It's not used outside
	local OPENSSL_CNF is_temp_cnf rc

	OPENSSL_CNF=${PRODUCT_ROOT_D}/admin/conf/openssl.cnf
	OPENSSL_INPUT=${PRODUCT_ROOT_D}/admin/conf/openssl.input
	is_temp_cnf=0

	if [ ! -f "${OPENSSL_CNF}" ]; then
		# Well, base psa package isn't yet installed.
		# let's form a temporary config file
		OPENSSL_CNF=$(mktemp /tmp/openssl.cnf.XXXXXX)
		[ $? != 0 ] && die "Unable to create temporary file"
		cat >>${OPENSSL_CNF} <<EOF
[ req ]
attributes=req_attributes
distinguished_name=req_distinguished_name
default_md = sha256
x509_extensions = v3_ca

[ req_attributes ]
challengePassword               = A challenge password
unstructuredName                = An optional company name

[ req_distinguished_name ]
countryName             = Country Name
stateOrProvinceName     = State or Province Name
localityName            = Locality Name
organizationName        = Organisation Name
organizationalUnitName  = Organization Unit Name
commonName              = Common Name
emailAddress            = Email Address

[ v3_ca ]
extendedKeyUsage = serverAuth
EOF

		OPENSSL_INPUT=$(mktemp /tmp/openssl.input.XXXXXX)
		[ $? != 0 ] && die "Unable to create temporary file"
		cat >>${OPENSSL_INPUT} <<EOF
CH
.
Schaffhausen
Plesk
.
Plesk
info@plesk.com
.
.
.
EOF
		is_temp_cnf=1
	fi

	local cert_file_d=`dirname "${cert_file}"`
	[ -d "${cert_file_d}" ] || mkdir -p "${cert_file_d}"

	cat ${OPENSSL_INPUT} | openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
	-config ${OPENSSL_CNF} -set_serial `date +%s` -keyout "${cert_file}_" \
	-out "${cert_file}_" >> $product_log 2>&1

	# preserve exit code
	rc=$?

	if [ $rc -eq 0 ]; then
		cat "${cert_file}_" | sed -e 's/^\(-----END.*\)/\1\
/' > $cert_file
		set_ac 0 0 0400 "${cert_file}"
	fi
	# cleanup temporary files
	rm -f "${cert_file}_" ||:
	if [ "x$is_temp_cnf" = "x1" ]; then
		rm -f ${OPENSSL_CNF} ||:
		rm -f ${OPENSSL_INPUT} ||:
	fi
	return $rc
}

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

clean_panel_sessions()
{
# use subshell to catch die's inside db_do:
	(
	db_do "DELETE FROM sessions"
	db_do "DELETE FROM SessionContexts"
	)
}

### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
set_apache_params()
{
	apache_user="apache"
	apache_UID=80
	apache_group="apache"
	apache_GID=80

	apache_pid_file="$APACHE_ROOT/logs/httpd.pid"
	apache_lock_file="$APACHE_ROOT/logs/httpd.lock"
	product_lock_file="$HTTPD_CONF_D/cnf.lock"
	apache_service_name="httpd"

	apache_modules_d="/usr/lib64/httpd/modules"

	apache_service="$apache_service_name"

	apache_httpd_conf="$HTTPD_CONF_D/httpd.conf"

	apache_httpd_include="$HTTPD_INCLUDE_D/zz010_psa_httpd.conf"

	APACHE_ROOT="/usr"

	min_suexec_UID=10000
	max_suexec_UID=16000
	min_suexec_GID=$min_suexec_UID
	max_suexec_GID=$max_suexec_UID

	suexec_storage=/usr/lib64/plesk-9.0/suexec
	suexec=/usr/sbin/suexec
	suexec_dir="`dirname "$suexec"`"
	suexec_file="`basename "$suexec"`"

	rpm_httpd_bin=/usr/sbin/httpd
}

reconfigure_apache_if_needed()
{
	[ -n "$apache_need_reconfiguration" ] || return 0
	echo_try "reconfigure webserver(s) (reconfigure-all)"
	if httpdmng_reconfigure all ; then
		unset apache_need_reconfiguration
		suc
	else
		warn "webserver reconfiguration, maybe will attempt later"
	fi
}

httpdmng_reconfigure()
{
	local httpdmng_tool="${PRODUCT_ROOT_D}/admin/sbin/httpdmng"
	local what="$1"
	shift

	case "$what" in
		all|server|webmail) : ;;
		*) simply_die "Unexpected argument '$what' to httpdmng_reconfigure()" ;;
	esac

	if [ ! -x "$httpdmng_tool" ]; then
		p_echo "Unable to do 'httpdmng --reconfigure-$what': the utility is not yet on its place. Maybe will attempt later."
		return 1
	fi

	! "$httpdmng_tool" "--reconfigure-$what" -skip-removing -service-node local "$@" >> $product_log 2>&1 || return 0

	# There are 2 well known possible reasons of webserver templates reconfiguration failure:
	# 1. domain/server/webmail templates are well, but arbitrary domain unable to be configured due to  the some reasons,
	#	for example broken vhost structure
	# 2. broken domain/server/webmail templates


	# STEP 1. try to rollback to the default templates
	! httpdmng_reconfigure_rollback_to_default_templates "${what}" "$@" || return 0

	if [ "all" = "${what}" ]; then
	# STEP 2. ignore broken domains
		pp_echo "Warning: web server configuration is broken. We will try to repair it. This operation can take a lot of time, please do not interrupt the process."
		p_echo "Unable to rebuild web server configuration, possible there are broken domains"
		local inten="reconfigure web-server configurations skipping broken domains"
		echo_try "${inten}"
		if "$httpdmng_tool" "--reconfigure-$what" "-skip-broken" -service-node local "$@" >> $product_log 2>&1; then
			suc
			return 0
		else
	# STEP 3. try to rollback to the default templates, broken domains are ignored (possibly problem are in the server/webmail configs)
			warn "${inten}"
			! httpdmng_reconfigure_rollback_to_default_templates "${what}" "-skip-broken" -service-node local "$@" || return 0
		fi
	fi

	return 1
}

# NOTE: do not use function directly, it just helper for httpdmng_reconfigure !!!
# here we try to reconfigure webserver configs using default temnplates
httpdmng_reconfigure_rollback_to_default_templates()
{
	local template_d="${PRODUCT_ROOT_D}/admin/conf/templates"
	local inten="rebuild web server configs with default templates after reconfiguration failure"
	local tmp_d=
	local what="$1"
	shift

	[ -d "${template_d}/custom" ] || return 1
	p_echo "Unable to rebuild web server configuration with currently active default templates"
	echo_try "${inten}"

	if ! tmp_d=`mktemp -d "${template_d}/broken_templates_XXXXXXXX" 2>>$product_log`; then
		warn "${inten} - unable to create temporary directory for custom templates"
		return 1
	fi
	if ! mv -f "${template_d}/custom/"* "${tmp_d}"; then
		warn "${inten} - unable to move custom templates into ${tmp_d}"
		return 1
	fi
	rm -rf "${template_d}/custom"

	if ! "$httpdmng_tool" "--reconfigure-$what" -service-node local "$@" >> $product_log 2>&1; then
		warn "${inten} - using default templates does not solve the problem, restore custom ones"
		mv -f "${tmp_d}" "${template_d}/custom"
		return 1
	fi

	suc
	pp_echo "Custom templates which are breaking web server reconfiguration were moved to ${tmp_d}"
	cat <<EOF >"${tmp_d}/README"
This directory contains broken custom webserver templates which are breaking web server reconfiguration.
Custom templates were moved here on `date` during product update or upgrade.
EOF
}

read_apsc_connection_params_db()
{
	# Warning: password can be encrypted. Don't use it.
	apsc_db_name=`db_read_misc_attr "aps_database"`
	apsc_db_user=`db_read_misc_attr "aps_login"`
	apsc_db_passwd=`db_read_misc_attr "aps_password"`
	apsc_db_host=`db_read_misc_attr "aps_host"`
}

save_apsc_connection_params_db()
{
	local register_script="$PRODUCT_ROOT_D/admin/plib/scripts/register_apsc_database.php"
	[ -f "$register_script" ] || die 'can not find "register_apsc_database.php"'
	local dsn_apsc_host="`get_dsn apsc host`"
	local dsn_apsc_port="`get_dsn apsc port`"

	sw_engine_pleskrun "$register_script" --register \
		-host "${dsn_apsc_host:-localhost}" \
		-port "${dsn_apsc_port:-3306}" \
		-database "$apsc_db_name" \
		-login "$apsc_db_user" \
		-password "$apsc_db_passwd" >> "$product_log" 2>&1
}

check_apsc_installed()
{
	local db_name=`db_read_misc_attr "aps_database"`

	[ -n "$db_name" ] || return 1
	db_test_database "$db_name"
}

install_cron_backup()
{
	local backup_file_before_10_5_24="/etc/cron.d/plesk-backup-manager"
	local backup_file="/etc/cron.d/plesk-backup-manager-task"

	if [ -s "${backup_file_before_10_5_24}" ]; then
		mv -f "${backup_file_before_10_5_24}" "${backup_file}"
	else
		rm -f "${backup_file_before_10_5_24}"
	fi

	[ ! -s "${backup_file}" ] || return 0
	minutes=`get_random_number 15`

	cat >"${backup_file}" <<-EOF
$minutes,`expr $minutes + 15`,`expr $minutes + 30`,`expr $minutes + 45`	*	*	*	*	root [ -x $PRODUCT_ROOT_D/admin/sbin/backupmng ] && $PRODUCT_ROOT_D/admin/sbin/backupmng >/dev/null 2>&1
EOF
}

remove_cron_backup()
{
	rm -f "/etc/cron.d/plesk-backup-manager" "/etc/cron.d/plesk-backup-manager-task"
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
# vim:ft=sh:

#courier-imap

set_courier_imap_params()
{
	COURIERIMAP_CONFDIR="/etc/courier-imap"
	COURIERIMAP_PIDPATH="/run"
	IMAPD_CERT="/usr/share/imapd.pem"
	POP3D_CERT="/usr/share/pop3d.pem"
	COURIER_DHPARAMS="/usr/share/dhparams.pem"

	# Certificate paths for Courier-IMAP <= 3.0.8
	OLD_IMAPD_CERT="/usr/share/courier-imap/imapd.pem"
	OLD_POP3D_CERT="/usr/share/courier-imap/pop3d.pem"

	COURIER_DELIVER_QUOTA="/usr/bin/deliverquota"

	courier_imapd_service="courier-imapd"
	courier_imaps_service="courier-imaps"
	courier_pop3d_service="courier-pop3d"
	courier_pop3s_service="courier-pop3s"
	courier_authdaemon_service="courier-authdaemon"

	# Service name for Courier-IMAP <= 3.0.8
	old_courier_service="courier-imap"
}

# db_test test_query awk_script
# Runs test_query and processes it with awk_script. If the output is
# not empty, return 0, otherwise return 1. Hint: supply '1' for
# awk_script to test just for the presence of any output.
db_test()
{
	local any_db=
	eval `sh_get_args '--any-db) any_db=yes;;'`

	local test_query="$1"
	local awk_script="$2"
	local output

	if [ -n "$any_db" ]; then
		output="`mysql_raw_anydb -e \"$test_query\" 2>>\"$product_log\"`"
	else
		output="`mysql_raw -e \"$test_query\" 2>>\"$product_log\"`"
	fi
	local status=$?
	if [ "$status" -ne 0 ]; then
		p_echo "$output"
		die "run the following SQL query: $1"
	fi

	echo -n "$output" | awk -F '\t' -- "$awk_script" | test `wc -l` -ne 0
}

# db_do [--inten <inten>] query
# Runs query. If it fails, die
# the inten string describes the query reason (to make finding the bug simpler)
db_do()
{
	local desc="execute SQL query"
	eval `sh_get_args '--inten) desc=" (to $2)"; shift;;'`
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local query="$1"

	mysql -e "$query" >>"$product_log" 2>&1 || die "$desc, the query was: $query"
}

# db_select <query>
# runs <query> via mysql_raw
# writes output to db_select_output
# if query fails, output errors and return 1
db_select()
{
	local desc="execute SQL query"
	local query="$1"

	local output
	output="`mysql_raw -e \"$query\" 2>>\"$product_log\"`"
	local status="$?"
	if [ "$status" -ne "0" ]; then
		p_echo "$output"
		die "run the following SQL query: $query"
	fi

	db_select_output="$output"
	return 0
}

# db_test_database database
# Returns 0 if the database exists
db_test_database()
{
	local database="$1"

	local mysql_db_name="mysql"
	db_test "SHOW DATABASES" "\$1 == \"$database\""
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
# vim:ft=sh:

db_read_misc_attr()
{
	db_select "SELECT val FROM misc WHERE param = '$1'"
	echo "$db_select_output"
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
# vim:ft=sh:

set_dovecot_params()
{
	DOVECOT_CONFDIR="/etc/dovecot"
	DOVECOT_INCLUDE_DIR="/etc/dovecot/conf.d"
	DOVECOT_DIST_CONFDIR="/usr/share/doc/plesk-dovecot/dist-config"
	DOVECOT_CERT_DIR="/etc/dovecot/private"
	DOVECOT_CERT="$DOVECOT_CERT_DIR/ssl-cert-and-key.pem"

	DOVECOT_INTERNAL_USERGROUP="dovecot"
	DOVECOT_LOGIN_USERGROUP="dovenull"

	DOVECOT_LDA="/usr/libexec/dovecot/dovecot-lda"

	dovecot_service="dovecot"
}

is_remote_db_feature_enabled()
{
	[ -s "/etc/psa/private/dsn.ini" ]
}

get_dsn()
{
	local section="$1"
	local param="$2"
	! is_remote_db_feature_enabled || get_ini_conf_var "/etc/psa/private/dsn.ini" "$section" "$param"
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
# vim:ft=sh
# Usage:  pleskrc <service> <action>
pleskrc()
{
	[ 2 -le $# ] || die "Not enough arguments"

	local service_name=${1//[-.@]/_}
	local action=$2
	local ret=0
	local inten
	shift
	shift

	# Now check redefined functions
	if test "$machine" = "linux" && is_function "${service_name}_${action}_${machine}_${linux_distr}"; then
		"${service_name}_${action}_${machine}_${linux_distr}" "$@"
		return $?
	elif is_function "${service_name}_${action}_${machine}"; then
		"${service_name}_${action}_${machine}" "$@"
		return $?
	elif is_function "${service_name}_${action}"; then
		"${service_name}_${action}" "$@"
		return $?
	fi

	# Not redefined - call default action
	eval "service=\$${service_name}_service"
	[ -n "$service" ] || die "$action $service_name service (Empty service name for '$service_name')"

	if [ "$action" = "name" ]; then
		echo "${service}.service"
		return 0
	fi

	inten="$action service $service"
	[ "$action" = "status" -o "$action" = "exists" ] || echo_try "$inten"

	if [ -x "/bin/systemctl" -a "$do_upgrade" = "1" -a ! -f "/var/lock/parallels-panel-bootstrapper-running.lock" -a -z "$SYSTEMD_DAEMON_RELOADED" ]; then
		# reload systemd units if requested from an upgrade package script - in case a unit was changed
		/bin/systemctl daemon-reload
		SYSTEMD_DAEMON_RELOADED="yes"
	fi

	service_ctl "$action" "$service" "$service_name"

	ret="$?"
	if [ "$action" != "status" -a "${action}" != "exists" ]; then
		if [ "$ret" -eq 0 ]; then
			suc
		else
			if [ -x "/bin/systemctl" ]; then
				p_echo "`/bin/systemctl -l status \"${service}.service\" | awk 'BEGIN {s=0} s==1 {s=2} /^$/ {s=1} s==2 {print}'`"
			fi
			warn "$inten failed"
		fi
	fi

	return $ret
}

# NOTE:
#	Function service_ctl is just helper for pleskrc().
#	Do not call it directly, use pleskrc()!!!
service_ctl()
{
	local action=$1
	local service=$2
	local service_name=$3

	if [ "$action" != "exists" ]; then
		_service_exec $service exists
		if [ "$?" != "0" ]; then
			p_echo "attempt to ${inten} - service doesn't exist (missing unit file or not executable control script)"
			return 1
		fi
	fi

	case "$action" in
		start)
			pleskrc "$service_name" status || _service_exec "$service" "$action"
			;;
		stop)
			! pleskrc "$service_name" status || _service_exec "$service" "$action"
			;;
		restart)
			if pleskrc "$service_name" status; then
				_service_exec "$service" "$action"
			else
				_service_exec "$service" start
			fi
			;;
		reload)
			! pleskrc "$service_name" status || _service_exec "$service" "$action"
			;;
		status)
			_service_exec "$service" status
			;;
		try-restart)
			if [ -x "/bin/systemctl" ]; then
				_service_exec "$service" "$action"
			else
				! pleskrc "$service_name" status || _service_exec "$service" "restart"
			fi
			;;
		try-reload)
			! pleskrc "$service_name" status || _service_exec "$service" "reload"
			;;
		reload-or-restart)
			if [ -x "/bin/systemctl" ]; then
				_service_exec "$service" "$action"
			elif pleskrc "$service_name" status; then
				_service_exec "$service" "reload"
			else
				_service_exec "$service" "start"
			fi
			;;
		*)
			_service_exec "$service" "$action"
			;;
	esac >> "$product_log"
}

_service_exec()
{
	# Keep in sync with pylibplesk/plesk_service.py
	local service=$1
	local action=$2

	local action_cmd
	local sysvinit_service="/etc/rc.d/init.d/$service"

	if [ -x "/bin/systemctl" ]; then
		case "${action}" in
			exists)
				if /bin/systemctl cat "$service.service" >/dev/null 2>&1; then
					return 0 # systemd unit
				elif [ -f "/usr/lib/systemd/system/$service.service" ]; then
					/bin/systemctl daemon-reload
					return 0 # systemd unit which exists but was changed and has not been reloaded before
				elif [ -x "$sysvinit_service" ]; then
					return 0 # sysvinit compat
				fi
				return 1 # not found
				;;
			status)
				action="is-active"
				;;
			reload|graceful)
				action='reload-or-try-restart'
				;;
		esac
		/bin/systemctl "$action" "${service}.service"
	else
		warn "Cannot $action $service on this system: no executable /bin/systemctl"
		return 1
	fi
}

is_function()
{
	local type_output=$(type -t "$1")
	test "X${type_output}" = "Xfunction"
}

### Copyright 1999-2024. 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
}

p_see_product_log()
{
	log_is_in_dev "${product_log}" || printf " (see log file: ${product_log})" >&2
}

die()
{
	report_problem "fatal" "ERROR while trying to $@"
	printf "Check the error reason" >&2
	p_see_product_log
	echo ", fix and try again" >&2

	selinux_close

	exit 1
}

simply_die()
{
	report_problem "fatal" "$@"
	exit 1
}

warn()
{
	local inten="$1"

	if [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" ]; then
		p_echo
		p_echo "WARNING!"
		pnnl_echo "Some problems are found during $inten"
		p_see_product_log
		p_echo
		p_echo "Continue..."
		p_echo
	fi

	report_problem "warning" "Warning: $inten"
}

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

suc()
{
	p_echo "done"
}

write_structured_report()
{
	# Write json error report into file $PLESK_INSTALLER_ERROR_REPORT if specified.
	# @params are tags in format "key=value"
	# Report body (human readable information) is read from stdin.
	local report_file="$PLESK_INSTALLER_ERROR_REPORT"

	[ -n "$report_file" ] || return 0

	local python_bin=
	for bin in "/opt/psa/bin/python" "/usr/local/psa/bin/python" "/usr/bin/python2" "/usr/libexec/platform-python" "/usr/bin/python3"; do
		if [ -x "$bin" ]; then
			python_bin="$bin"
			break
		fi
	done

	if [ ! -x "$python_bin" ]; then
		p_echo "Cannot write structured error report: python interpreter not found."
		return 1
	fi

	"$python_bin" -c 'import sys, json
report_file = sys.argv[1]
error = sys.stdin.read()

data = {
    "error": error,
}

for tag in sys.argv[2:]:
    k, v = tag.split("=", 1)
    data[k] = v

with open(report_file, "a") as f:
    json.dump(data, f)
    f.write("\n")
' "$report_file" "date=$(date --utc --iso-8601=ns)" "$@"
}
### Copyright 1999-2024. 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"
}

# accumulates chown and chmod
set_ac()
{
	local u_owner g_owner perms node
	u_owner="$1"
	g_owner="$2"
	perms="$3"
	node="$4"

	# A very small optimization - replacing of two execs by one,
	#    it works only if the following conditions are observed:
	#       - u_owner is username (not UID);
	#       - g_owner is group (not GID);
	#       - perms is in octal mode.
	# If some conditions aren't observed,
	#    optimization doesn't work,
	#    but it doesn't break function
	[ "$(stat -c '%U:%G 0%a' $node)" != "$u_owner:$g_owner $perms" ] || return 0
	chown $u_owner:$g_owner $node || die "chown $u_owner:$g_owner $node"
	chmod $perms $node || die "chmod $perms $node"
}

mkdir_ex()
{
	local owner group mode dir
	owner="$1"
	group="$2"
	mode="$3"
	dir="$4"

	if ! test -d "$dir"; then
		mkdir "$dir" || die "create directory $dir"
	fi
	set_ac "$owner" "$group" "$mode" "$dir"
}

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
}

sh_get_args()
{
	echo 'while true; do case "$1" in '"$1"'*) break;; esac; shift; done'
}

get_random_number()
{
	perl -e '
	 my $res = int(rand($ARGV[0]));
	 if (exists $ARGV[1]) {
	  $res = $res + $ARGV[1];
	 }
	 print $res;
	' "$@"
}

get_random_string()
{
	local str_length="$1"
	local str_symbols="$2"
	if [ -x "$PRODUCT_ROOT_D/admin/sbin/random_str" -a -z "$str_symbols" ]; then
		"$PRODUCT_ROOT_D/admin/sbin/random_str" "$str_length"
	else
		# random_str utility may be unavailable in pre phase
		if [ -z "$str_length" ]; then
			str_length="14"
		fi
		if [ -z "$str_symbols" ]; then
			str_symbols="A-Za-z0-9_"
		fi

		< /dev/urandom tr -dc "$str_symbols" 2>/dev/null | head -c "$str_length" 2>/dev/null
	fi
}

sequence()
{
	if type seq >/dev/null 2>&1; then
		seq $*
	elif type jot >/dev/null 2>&1; then
		jot $*
	else
		die "Unable to find seq or jot command"
	fi
}

get_ini_conf_var()
{
	local conf="$1"
	local section="$2"
	local param="$3"

	[ -n "$conf" -a -n "$param" ] || die "get_ini_conf_var(): required parameters missing"

	local section_empty=0
	[ -n "$section" ] || section_empty=1

	perl -n -e 'BEGIN { $insect='$section_empty' }
				next if (/^\s*;/);
				$insect=0 if (/^\s*\[.*\]/);
				$insect=1 if (/^\s*\['$section'\]/);
				$val = $2, $val =~ s/\s+$//, print $val . "\n" 
					if ($insect && /^\s*('$param')\s*=\s*([^;\n]*)(;.*)?$/);' $conf | head -n 1
}

set_ini_conf_var()
{
	local conf="$1"
	local section="$2"
	local param="$3"
	local value="$4"

	[ -n "$conf" -a -n "$param" ] || die "set_ini_conf_var(): required parameters missing"

	local section_empty=0
	[ -n "$section" ] || section_empty=1

	perl -n -e 'BEGIN { $insect='$section_empty' }
				if (not /^\s*;/) {
					$insect=0 if (/^\s*\[.*\]/);
					$insect=1 if (/^\s*\['$section'\]/);
					if ($insect && /^(\s*('$param')\s*=\s*)([^;\n]*)((;.*)?)$/) {
						$tail = $4; chomp($tail); $tail = "    " . $tail if ($tail);
						print $1 . "'$value'" . $tail . "\n";
						next;
					}
				}
				print $_;' $conf > $conf.tmp && \
	cat $conf.tmp > $conf && rm -f $conf.tmp
}

sw_engine_pleskrun()
{
	if [ -x $PRODUCT_ROOT_D/bin/sw-engine-pleskrun ]; then
		$PRODUCT_ROOT_D/bin/sw-engine-pleskrun "$@"
	elif [ -x "/usr/bin/sw-engine" ]; then
		local args
		if [ -e "$PRODUCT_ROOT_D/admin/conf/php.ini" ]; then
			args="-c $PRODUCT_ROOT_D/admin/conf/php.ini"
		else
			args="-d psasem.semfile=\"$PRODUCT_ROOT_D/var/psasem.sem\""
		fi
		/usr/bin/sw-engine $args "$@"
	else
		echo "No Plesk PHP interpreter found"
		return 1
	fi
}

install_default_license_key()
{
	pnnl_echo "install default license key ..."

# check OF-key
	if sw_engine_pleskrun -r 'exit(of_get_key_by_product("plesk-unix") === false ? 1 :0);'; then
			p_echo "not needed, OF license found"
			return
	fi

# check Unified key
	if sw_engine_pleskrun -r 'exit(of_get_key_by_product("plesk-unified") === false ? 1 :0);'; then
			p_echo "not needed, unified license found"
			return
	fi

	local dest_dir="/etc/sw/keys/keys"
	local key=plesk-default-key.xml

    [ ! -s "$dest_dir/$key" ] || return 0

    cp -f "${PRODUCT_ROOT_D}/var/$key" "$dest_dir/"
    chown root:swkey-data "$dest_dir/$key"
    chmod 0660 "$dest_dir/$key"
    suc
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
#-*- vim:syntax=sh

product_log_name_ex()
{
	local aux_descr="$1"
	local action="${CUSTOM_LOG_ACTION_NAME-installation}"

	if [ -n "$aux_descr" ]; then
		aux_descr="_${aux_descr}"
	fi

	if [ -n "$CUSTOM_LOG_NAME" ]; then
		echo "${CUSTOM_LOG_NAME}${action:+_$action}${aux_descr}.log"
	else
		get_product_versions
		echo "plesk_${product_this_version}${action:+_$action}${aux_descr}.log"
	fi
}

product_log_name()
{
	product_log_name_ex
}

product_problems_log_name()
{
	product_log_name_ex "problems"
}

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
}

cleanup_problems_log()
{
	[ -f "$product_problems_log" ] || return 0
	touch "$product_problems_log.tmp"
	chmod 0600 "$product_problems_log.tmp"
	awk 'BEGIN 							{ st = "" }
		/^START/ && (st ~ /^START/) 	{ print st; }
		/^START/ 						{ st=$0; next }
		/^STOP/ && (st ~ /^START/) 		{ st=""; next }
		(st != "") 						{ print st; st="" }
										{ print }
		' "$product_problems_log" > "$product_problems_log.tmp" && \
	mv -f "$product_problems_log.tmp" "$product_problems_log" || \
	rm -f "$product_problems_log.tmp"

	if [ ! -s "$product_problems_log" ]; then
		rm -f "$product_problems_log"
	fi
}

set_log_action_name()
{
	CUSTOM_LOG_ACTION_NAME="$1"
}

mktemp_log()
{
	local logname="$1"
	local dir="$2"

	if [ "${logname:0:1}" != "/" ]; then
		logname="$dir/$logname"
	fi
	dir="`dirname $logname`"
	if [ ! -d "$dir" ]; then
		mkdir -p "$dir" || { echo "Unable to create log directory : $dir"; exit 1; }
		if [ "$EUID" -eq "0" ]; then
			set_ac root root 0700 "$dir"
		fi
	fi

	if [ "${logname%XXX}" != "$logname" ]; then
		mktemp "$logname"
	else
		echo "$logname"
	fi
}

log_is_in_dev()
{
	test "${1:0:5}" = "/dev/"
}

start_writing_logfile()
{
	local logfile="$1"
	local title="$2"
	! log_is_in_dev "$logfile" || return 0
	echo "START $title" >> "$logfile" || { echo "Cannot write installation log $logfile" >&2; exit 1; }
	[ "$EUID" -ne "0" ] || set_ac root root 0600 "$logfile"
}

log_start()
{
	true product_log_name product_problems_log_name mktemp_log

	local title="$1"
	local custom_log="$2"
	local custom_problems_log="$3"

	local product_log_dir="/var/log/plesk/install"

	product_log="$product_log_dir/`product_log_name`"
	product_problems_log="$product_log_dir/`product_problems_log_name`"
	problems_occured=0

	# init product log
	[ ! -n "$custom_log" ] || product_log="$custom_log"
	product_log=`mktemp_log "$product_log" "$product_log_dir"`

	# init problems log
	if [ -n "$custom_problems_log" ]; then
		product_problems_log=`mktemp_log "$custom_problems_log" "$product_log_dir"`
	elif [ -n "$custom_log" ]; then
		product_problems_log="$product_log"
	else
		product_problems_log=`mktemp_log "$product_problems_log" "$product_log_dir"`
	fi

	# write starting message into logs
	start_writing_logfile "$product_log" "$title"
	if [ "$product_log" != "$product_problems_log" ]; then
		start_writing_logfile "$product_problems_log" "$title"
	fi

	is_function profiler_setup && profiler_setup "$title" || :
}

log_transaction_start()
{
	LOG_TRANSACTION_TITLE="$1"
	LOG_TRANSACTION_SUBJECT="$2"
	local log_transaction_custom_logfile="$3"
	local log_transaction_custom_problems_logfile="$4"

	transaction_begin autocommit
	log_start "$LOG_TRANSACTION_TITLE" "$log_transaction_custom_logfile" "$log_transaction_custom_problems_logfile"
	transaction_add_commit_action "log_transaction_stop"
	transaction_add_rollback_action "log_transaction_stop"
}

log_transaction_stop()
{
	log_stop "$LOG_TRANSACTION_TITLE" "$LOG_TRANSACTION_SUBJECT"
}

log_stop()
{
	local title="$1"
	local subject="$2"

	if [ "$product_log" = "$product_problems_log" ] || \
			log_is_in_dev "$product_problems_log"; then
		[ -e "$product_log" ] && echo "STOP $title" >>"$product_log"
		is_function profiler_stop && profiler_stop || :
		return
	fi

	if [ -z "$subject" ]; then
		subject="[${title}]"
	fi

	# check if problems are non-empty, check for problems_occured
	local status
	local problem_lines="`problems_log_tail | wc -l`"
	if [ "$problem_lines" -eq 0 ]; then
		status="completed successfully"
	else
		if [ $problems_occured -ne 0 ]; then
			status="failed"
		else
			status="completed with warnings"
		fi
	fi

	if [ -e "$product_log" ]; then
		p_echo
		p_echo "**** $subject $status."
		p_echo
	fi

	if [ "$problem_lines" -ne 0 ]; then
		[ ! -e "$product_log" ] || problems_log_tail >>"$product_log" 2>&1
		problems_log_tail
	fi

	[ ! -e "$product_log" ] || echo "STOP $title" >>"$product_log"
	if [ $problems_occured -ne 0 ]; then
		echo "STOP $title: PROBLEMS FOUND" >>"$product_problems_log"
	else
		[ ! -s "$product_problems_log" ] || echo "STOP $title: OK" >>"$product_problems_log"
	fi

	if [ "X${PLESK_INSTALLER_KEEP_PROBLEMS_LOG}" = "X" ]; then
		cleanup_problems_log
	fi

	is_function profiler_stop && profiler_stop || :
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.

generate_password_file()
{
	local passwd_file="$1"
	local title="$2"
	local user="$3"
	local group="$4"
	local mode="$5"

	if [ "$#" -ne 5 ]; then 
		die "Some arguments was not defined for this function"
	fi

	local passwd
	local inten="generate random password for $title"

	echo_try $inten

	if [ ! -s "$passwd_file" ]; then 
		passwd=`get_random_string` || die $inten
		echo "$passwd" > "$passwd_file" || die $inten
		set_ac $user $group $mode $passwd_file || die $inten
	else
		set_ac $user $group $mode $passwd_file || die $inten
	fi
	suc
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.

get_pid()
{
	local i

	local ex_f="$1"
	local opt="$2"
	local owner="$3"

	local min_num="1"
	local ps_long="ps axuw"

	# Use pidof by default, bug 121868, except for FreeBSD - 140182
	if type pidof >/dev/null 2>&1 && [ "$os" != "BSD" ]; then
		for pid in `pidof -o $$ -o $PPID -o %PPID -x $ex_f`; do
			# Check for owner
			[ "$opt" = "true" -a "$owner" != "`ps -p $pid -o ruser=`" ] && continue
			min_num=$pid
			break
		done
		common_var=$min_num
		return $min_num
	fi

	case "$opt" in
		false)
			for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | awk '{print $2}' -`; do
				min_num=$i
				break
			done
			;;
		true)
			for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | grep "$owner" | awk '{print $2}' -`; do
				min_num=$i
				break
			done
			;;
		*)
			p_echo "get_pid: wrong parameter"
			die "get_pid $ex_f $opt $owner"
			;;
	esac

	common_var=$min_num
	return $min_num
}
### Copyright 1999-2024. 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_context()
{
	report_context="$*"
}

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-2024. 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-2024. WebPros International GmbH. All rights reserved.
transaction_begin()
{
	[ -n "$TRANSACTION_STARTED" ] && die "Another transaction in progress!"
	TRANSACTION_STARTED="true"
	TRANSACTION_ROLLBACK_FUNCS=
	TRANSACTION_COMMIT_FUNCS=
	local transaction_autocommit="$1"
	if [ -n "$transaction_autocommit" ]; then
		trap "transaction_commit_auto" EXIT
		trap "transaction_rollback" HUP PIPE INT QUIT TERM
	else
		trap "transaction_rollback" HUP PIPE INT QUIT TERM EXIT
	fi
}

transaction_rollback()
{
	TRANSACTION_RETURN_CODE="${TRANSACTION_RETURN_CODE:-$?}"
	[ -z "$TRANSACTION_STARTED" ] && die "Transaction is not started!"
	# perform rollback actions
	local f
	for f in ${TRANSACTION_ROLLBACK_FUNCS}; do
		"$f"
	done
	TRANSACTION_STARTED=
	TRANSACTION_ROLLBACK_FUNCS=
	TRANSACTION_COMMIT_FUNCS=
	trap - HUP PIPE INT QUIT TERM EXIT
	exit 1
}

transaction_commit()
{
	TRANSACTION_RETURN_CODE="${TRANSACTION_RETURN_CODE:-$?}"
	[ -z "$TRANSACTION_STARTED" ] && die "Transaction is not started!"
	# perform commit actions
	local f
	for f in ${TRANSACTION_COMMIT_FUNCS}; do
		"$f"
	done
	TRANSACTION_STARTED=
	TRANSACTION_ROLLBACK_FUNCS=
	TRANSACTION_COMMIT_FUNCS=
	trap - HUP PIPE INT QUIT TERM EXIT
}

transaction_commit_auto()
{
	TRANSACTION_RETURN_CODE="$?"
	if [ "$TRANSACTION_RETURN_CODE" -eq 0 ]; then
		transaction_commit "$@"
	else
		transaction_rollback "$@"
	fi
}

transaction_add_rollback_action()
{
	[ -z "$TRANSACTION_STARTED" ] && die "Transaction is not started!"
	# LIFO rollback order
	[ -z "$TRANSACTION_ROLLBACK_FUNCS" ] \
		&& TRANSACTION_ROLLBACK_FUNCS="$1" \
		|| TRANSACTION_ROLLBACK_FUNCS="$1 $TRANSACTION_ROLLBACK_FUNCS"
}

transaction_add_commit_action()
{
	[ -z "$TRANSACTION_STARTED" ] && die "Transaction is not started!"
	# FIFO commit order
	[ -z "$TRANSACTION_COMMIT_FUNCS" ] \
		&& TRANSACTION_COMMIT_FUNCS="$1" \
		|| TRANSACTION_COMMIT_FUNCS="$TRANSACTION_COMMIT_FUNCS $1"
}
### Copyright 1999-2024. 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=RedHat
	conceived_os_version="el8"

	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
}

get_my_cnf_param()
{
	local r=

	local my_cnf
	find_my_cnf "non-fatal" && \
		r=`perl -e '$p="'"$1"'";
		undef $/; $_=<>; s/#.*$//gm;
		/\[mysqld\](.*?)\[/sg;
		$_=substr($1, rindex $1,"$p") and
		/$p\s*=(.*)/m and print $1
		' ${my_cnf}`
	echo $r
}

get_mysql_socket()
{
	# Marked as local as it's not used anywhere else now.
	local mysql_socket="/var/lib/mysql/mysql.sock"

	local mysqlsock=`get_my_cnf_param  socket`
	local MYSQL_SOCKETS="/var/lib/mysql/mysql.sock /tmp/mysql.sock /var/run/mysqld/mysqld.sock"

	for i in $mysql_socket $mysqlsock $MYSQL_SOCKETS; do
		if [ -S "$i" ]; then
			# This is used internally by mysqld_safe. Maybe this whole function isn't required nowadays.
			# See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-mysql-sock.html
			MYSQL_UNIX_PORT=$i
			export MYSQL_UNIX_PORT
			mysql_socket="$i"
			break
		fi
	done
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.

#-*- vim:ft=sh

register_service() {

	[ -n "$1" ] || die "register_service: service name not specified"
	local inten="register service $1"
	echo_try "$inten"

	{
		# sysvinit tools will not be called on systemd OS'es
		# since such OS'es are not explicitly supported
		enable_respawn_service "$1.service"
		# systemctl daemon-reload is performed implicitly unless --no-reload is passed
		/bin/systemctl enable "$1.service"

		local rs_db="$PRODUCT_ROOT_D/admin/sbin/register_service_db"
		[ ! -x "$rs_db" ] || "$rs_db" -a "$@"
	}

	suc
}

unregister_service() {

	[ -n "$1" ] || die "unregister_service: service name not specified"
	local inten="unregister service $1"
	echo_try $inten

	{
		local rs_db="$PRODUCT_ROOT_D/admin/sbin/register_service_db"
		[ ! -x "$rs_db" ] || "$rs_db" -r "$1"

		disable_respawn_service "$1.service"
		# systemctl daemon-reload is performed implicitly unless --no-reload is passed
		/bin/systemctl disable "$1.service"

		# purge sysvinit symlinks from /etc/rc.d which might be created by systemd-sysv-install
		# it spawns `update-rc.d defaults` or `chkconfig --add` if sysvinit script exists
		! [ -x /sbin/chkconfig ] || /sbin/chkconfig --del "$1" 1>/dev/null 2>&1 || :
	} >> $product_log 2>&1

	suc
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.

#-*- vim:ft=sh

enable_respawn_service()
{

	grep_q_recursive() {
		local val="$1"
		local file="$2"
		if [ -f "$file" ]; then
			! grep -q "$val" "$file" || return 0
			for f in `sed -n -e "s/^\.include\s//p" $file`; do
				! grep_q_recursive "$val" "$f" || return 0
			done
		fi
		return 1
	}

	[ -n "$1" ] || die "enable_respawn_service: service name not specified"
	local inten="enable automatic respawn for service $1"
	echo_try "$inten"

	local service=$1
	local main_unit=`systemctl show $service | sed -n -e "s/FragmentPath=//p"`
	local respawn_unit="/usr/lib/systemd/system/$service.d/respawn.conf"
	local dropin_units=`systemctl show $service | sed -n -e "s/DropInPaths=//p" | sed "s|$respawn_unit||"`
	local ini="/usr/local/psa/admin/conf/panel.ini"
	local ini_section="systemd"

	local respawn
	[ ! -f "$ini" ] || respawn=`get_ini_conf_var "$ini" "$ini_section" respawn`

	if [ -z "${respawn/on/}" ]; then
		for unit in $main_unit $dropin_units; do
			! grep_q_recursive "^Restart=" 		"$unit" || respawn="off"
			! grep_q_recursive "^Type=oneshot" 	"$unit" || respawn="off"
		done
	fi

	rm -f "$respawn_unit"

	if [ -z "${respawn/on/}" ]; then
		mkdir -p "$(dirname $respawn_unit)"
		if [ -f "$ini" ]; then
			local restart=`		get_ini_conf_var "$ini" "$ini_section" Service.Restart`
			local restartsec=`	get_ini_conf_var "$ini" "$ini_section" Service.RestartSec`
		fi
		cat <<EOT > "$respawn_unit"
[Service]
Restart=${restart:-"on-failure"}
RestartSec=${restartsec:-"5"}
EOT
	fi

	suc
}

disable_respawn_service()
{

	[ -n "$1" ] || die "disable_respawn_service: service name not specified"
	local inten="disable automatic respawn for service $1"
	echo_try "$inten"

	local respawn_unit="/usr/lib/systemd/system/$1.d/respawn.conf"

	rm -f "$respawn_unit"

	suc
}

selinux_close()
{
	if [ -z "$SELINUX_ENFORCE" -o "$SELINUX_ENFORCE" = "Disabled" ]; then
		return
	fi

	setenforce "$SELINUX_ENFORCE"
}

### Copyright 1999-2024. 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/rc.d/init.d"
	PLESK_LIBEXEC_DIR="/usr/lib64/plesk-9.0"
	PLESK_DB_DIR="/var/lib/plesk"
	PRODUCT_BOOTSTRAPPER_DIR="`printf "/usr/local/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
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
set_swcpserver_params()
{
	swcpserver_service=sw-cp-server
	swcpserver_binary=/usr/sbin/sw-cp-serverd
	swcpserver_pidfile=/var/run/sw-cp-server.pid
	swcpserver_includedir=/etc/sw-cp-server/conf.d

	true swcpserver_status
}

swcpserver_status()
{
	get_pid "$swcpserver_binary" false
	local pid=$common_var
	if [ "$pid" -ne 1 ]; then
		return 0
	fi
	return 1
}

get_product_versions()
{
	# Don't use global variables set elsewhere in this code. Use substitutions if needed.
	local prod_root_d="/usr/local/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 "/usr/local/psa/version.upg" ]
}

set_postfix_auth()
{
	local run="$PRODUCT_ROOT_D/admin/sbin/mailmng-server --set-mail-params"

	if db_test "SELECT value FROM ServiceNodeConfiguration WHERE name='relay' AND value='open' AND serviceNodeId=1 AND section='mailServer'" 1 ; then
		run="$run --relayclient"
	fi

	if db_test "SELECT * FROM ServiceNodeConfiguration WHERE name='disable_smtp_auth' and value=0 AND serviceNodeId=1 AND section='mailServer'" 1 ; then
		run="$run --smtpauth"
	fi

	if db_test "SELECT * FROM ServiceNodeConfiguration WHERE name='disable_pop_auth' and value=0 AND serviceNodeId=1 AND section='mailServer'" 1 ; then
		run="$run --popauth"
	fi

	db_select "SELECT value FROM ServiceNodeConfiguration WHERE name='poplock_time' AND serviceNodeId=1 AND section='mailServer'"
	if [ -n "$db_select_output" ]; then
		# this will also set correct crontab for poplock.db cleanup
		run="$run --poplock-time=$db_select_output"
	fi

	$run >> $product_log 2>&1
}

update_postfix_poplockdb_cleanup_crontab()
{
	[ -x "${PRODUCT_RC_D}/postfix" -a ! -f "${PRODUCT_RC_D}/qmail" ] || return 0
	set_postfix_auth
}

set_mysql_auth()
{
	# This function requires set_mysql_server_params and set_mysql_client_params (or set_mysqld_params)
	# to be called before
	local inten="set up mysql authentication"
	local dsn_plesk_host="`get_dsn plesk host`"
	local dsn_plesk_port="`get_dsn plesk port`"
	local dsn_plesk_username="`get_dsn plesk username`"
	local dsn_plesk_password="`get_dsn plesk password`"

	get_admin_passwd

	[ -n "$dsn_plesk_host" ] || pleskrc mysql start

	mysql_host="${dsn_plesk_host:+--host=$dsn_plesk_host}"
	mysql_port="${dsn_plesk_port:+--port=$dsn_plesk_port}"
	mysql_user="--user=${dsn_plesk_username:-admin}"
	mysql_passwd="${dsn_plesk_password:-$admin_passwd}"

	if find_my_cnf 'non-fatal'; then
		mysql_defaults="--defaults-file=$my_cnf"
	else
		mysql_defaults="--no-defaults"
	fi

	if [ -z "$PLESK_MYSQL_AUTH_SKIP_CONNECTION_CHECK" ]; then
		mysql_test_connection 10 || die "$inten"
	fi
	suc
}

get_admin_passwd()
{
    [ -z "$admin_passwd" ] || return 0

    if [ -f "$mysql_passwd_file" ]; then
		admin_passwd=`cat "$mysql_passwd_file"`
		return 0
    fi

	admin_passwd=`get_random_string 1 'A-Z'`
	admin_passwd+=`get_random_string 1 'a-z'`
	admin_passwd+=`get_random_string 1 '0-9'`
	admin_passwd+=`get_random_string 1 '_%=+\-@<>:.,:'`
	admin_passwd+=`get_random_string 10 'A-Za-z0-9_%=+\-@<>:.,:'`
	admin_passwd=`printf "%s" "$admin_passwd" | fold -w 1 | shuf - | tr -d '\n'`

	[ -n "$admin_passwd" ] || admin_passwd="$PRODUCT_DEFAULT_PASSWORD"
	touch "$admin_password_needs_encryption_flag"
}

mysql_quote_string()
{
	echo "$1" | perl -pe 's|\\|\\\\|g'
}

mysql_test_connection()
{
	inten="establish test connection"
	echo_try $inten
	attempts=${1:-1}
	for i in `sequence $attempts`; do
		echo "" | mysql_direct mysql >> "$product_log" 2>&1
		if [ "$?" -eq "0" ]; then
			p_echo "connected"
			return 0
		fi
		[ "$attempts" -eq "1" ] || sleep 1
	done

	p_echo "failed"
	return 1
}

find_my_cnf()
{
	local non_fatal="$1"
	local cnf_files="/etc/my.cnf /etc/mysql/my.cnf /var/db/mysql/my.cnf"

	for my_cnf in $cnf_files; do
		if [ -f ${my_cnf} ]; then
			break
		fi
	done

	[ -f "$my_cnf" -o -n "$non_fatal" ] || {
		local msg="find the MySQL server configuration file. \
If you use a third-party MySQL server build, make sure you do not use implicit default configuration \
and you have the MySQL configuration file in one of the following locations: $cnf_files"
		echo "Failed to $msg" | write_structured_report 'stage=mysqlsetup' 'level=fatal' 'errtype=mysqlnomycnf' "mycnffiles=$cnf_files" || :
		die "$msg"
	}

	[ -f "$my_cnf" ] || return 1

	my_cnf_d=`awk '/^\s*!includedir\>/ {print $2}' "$my_cnf" | head -1`

	return 0
}

set_mysql_server_params()
{
	get_mysql_socket

	if [ -n "/usr/lib/systemd/system" -a -f "/usr/lib/systemd/system/mariadb.service" ]; then
	    mysql_service="mariadb"
	elif [ -n "/usr/lib/systemd/system" -a -f "/usr/lib/systemd/system/mysqld.service" ]; then
	    # Percona server
	    mysql_service="mysqld"
	elif [ -n "/usr/lib/systemd/system" -a -f "/usr/lib/systemd/system/mysql.service" ]; then
	    # MySQL 8 installations on debian / ubuntu
	    mysql_service="mysql"
	elif [ -x "${PRODUCT_RC_D}/mysqld" ]; then
	    mysql_service="mysqld"
	elif [ -x "${PRODUCT_RC_D}/mysqld.sh" ]; then
	    mysql_service="mysqld.sh"
	elif [ -x "${PRODUCT_RC_D}/mysqld" ]; then
	    mysql_service="mysqld"
	elif [ -x "${PRODUCT_RC_D}/mysql" ]; then
	    mysql_service="mysql"
	else
	    die "detect MySQL service name"
	fi
}

set_mysql_client_params()
{
	mysql_client="$MYSQL_BIN_D/mysql"

	# Override this variable as needed
	mysql_db_name="$PRODNAME"
	mysql_passwd_file="$product_etc/.${PRODNAME}.shadow"

	mysql_args="-N"
	mysql_args_raw="-Br"

	local dsn_plesk_dbname="`get_dsn plesk dbname`"
	[ -z "$dsn_plesk_dbname" ] || mysql_db_name="$dsn_plesk_dbname"
}

#Invoke mysql
mysql()
{
	mysql_anydb -D$mysql_db_name "$@"
}

mysql_anydb()
{
	(
		export MYSQL_PWD="$mysql_passwd"
		$mysql_client $mysql_defaults $mysql_host $mysql_port $mysql_user $mysql_args "$@" 2>>"$product_log"
		local status=$?

		if [ $status -gt 0 ]; then
			$mysql_client $mysql_defaults $mysql_host $mysql_port $mysql_user $mysql_args -D$mysql_db_name $mysql_args_raw -e "SHOW ENGINE innodb status" >>"$product_log" 2>&1
		fi
		unset MYSQL_PWD
		return $status
	)
}

# Invoke mysql without any wrapper or something else
mysql_direct()
{
	# a bit dirty but it works properly for passwords with spaces, quotes and double quotes:
	if [ -n "$mysql_passwd" ]; then
		(
			export MYSQL_PWD="$mysql_passwd"
			$mysql_client $mysql_defaults $mysql_host $mysql_port $mysql_user $mysql_args "$@" 2>>"$product_log"
			rc=$?
			unset MYSQL_PWD
			return $rc
		)
	else
		$mysql_client $mysql_defaults $mysql_host $mysql_port $mysql_user $mysql_args "$@" 2>>"$product_log"
	fi
}

# Invoke mysql in raw mode
mysql_raw()
{
	mysql $mysql_args_raw "$@"
}

mysql_raw_anydb()
{
	mysql_anydb $mysql_args_raw "$@"
}

uses_mysql_client()
{
	# Initialize local MySQL authentication parameters and test connection.
	# After that db_*() and mysql*() functions may be used.
	# Any MySQL-specific overrides (e.g., local mysql_db_name="whatever") should appear
	# *after* calling this function.
	# This function is for use in component installers that require access to MySQL DB.

	set_mysql_server_params
	set_mysql_client_params
	set_mysql_auth
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.

reset_user_password()
{
	true mysql_quote_string

	local user="$1"
	local passwd="$2"
	local hosts="${3:-localhost}"

	local inten="reset database user password for '${user}@${hosts}'"
	echo_try "${inten}"

	if [ "$hosts" = "127.0.0.1" -o "$hosts" = "::1" ] ; then
		hosts="${hosts} localhost"
	fi
	hosts="${hosts} %"

	local quoted_passwd=`mysql_quote_string "$passwd"`
	# MySQL has dropped PASSWORD() in 8.0.11:
	# https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-11.html
	local has_passwd_fun=""
	# mysql_direct() writes errors directly to $product_log, so we set
	# it to /dev/null to silence the expected error message about PASSWORD()
	# not existing
	if echo "SELECT PASSWORD('test')" | product_log=/dev/null mysql_direct mysql &>/dev/null; then
		has_passwd_fun=1
	fi
	local host=""
	for host in $hosts; do
		local query=""
		if [ -n "$has_passwd_fun" ]; then
			query="SET PASSWORD FOR '$user'@'$host' = PASSWORD('$quoted_passwd')"
		else
			query="ALTER USER '$user'@'$host' IDENTIFIED BY '$quoted_passwd'"
		fi
		if echo "$query" | mysql_direct mysql; then
			suc
			return 0
		fi
	done

	warn "$inten - database user does not exist."
	return 1
}

is_local_mysql_instance()
{
	local host="$1"
	[ -z "$host" -o "$host" = "localhost" -o "$host" = "127.0.0.1" -o "$host" = "::1" ]
}

check_db_accessible()
{
	local mysql_db_name="$1"
	local mysql_user="--user=$2"
	local mysql_passwd="$3"

	#INFO: we should not die here
	echo "" | mysql_direct 
}

reset_sitebuilder_passwd()
{
	local no_force="$1"
	local sb_conf="/usr/local/sb/config"
	[ -f "$sb_conf" ] || return 0

	local sb_host=`    get_ini_conf_var "$sb_conf" "database" "host"`
	local sb_username=`get_ini_conf_var "$sb_conf" "database" "username"`
	local sb_password=`get_ini_conf_var "$sb_conf" "database" "password"`
	local sb_dbname=`  get_ini_conf_var "$sb_conf" "database" "dbname"`

	is_local_mysql_instance "$sb_host" || return 0

	if [ -n "$no_force" ]; then
		check_db_accessible "$sb_dbname" "$sb_username" "$sb_password" && return 0 || :
	fi

	if reset_user_password "$sb_username" "$sb_password" "$sb_host"; then
		check_db_accessible "$sb_dbname" "$sb_username" "$sb_password"
	else
		# https://jira.plesk.ru/browse/PPP-4676
		return 0
	fi
}

get_webmail_config_param()
{
	local webmail_config="$1"
	local config_var="$2"
	local param="$3"
	local default_val="$4"
	local result=`sw_engine_pleskrun -n -r 'include "'$webmail_config'"; echo $'${config_var}${param}';' 2>/dev/null`
	[ -n "$result" ] || result="$default_val"
	echo "$result"
}

get_horde_config_param()
{
	get_webmail_config_param "/usr/share/psa-horde/config/conf.php" "conf" "$1" "$2"
}

get_roundcube_config_param()
{
	#INFO:  this function now is able to extract settings from config.inc.php, now it just db_dsnw;
	#	if need another parameters need to reimplement this function - parse defaults.inc.php, parse config.inc.php and merge data
	get_webmail_config_param "/usr/share/psa-roundcube/config/config.inc.php" "config" "$1"
}

reset_horde_passwd()
{
	local no_force="$1"

	set_horde_params

	local horde_shadow="$horde_passwd_file"
	[ -f "$horde_shadow" ] || horde_shadow="/etc/psa/.webmail.shadow"
	local hor_host=`  get_horde_config_param "['sql']['hostspec']" "localhost"`
	local hor_user=`  get_horde_config_param "['sql']['username']" "horde"`
	local hor_dbname=`get_horde_config_param "['sql']['database']" "horde"`
	local hor_passwd=`get_horde_config_param "['sql']['password']"`
	[ -n "$hor_passwd" ] || hor_passwd=`cat "$horde_shadow" 2>/dev/null`
	[ -n "$hor_passwd" -a -n "$hor_user" -a -n "$hor_dbname" ] || return 0

	is_local_mysql_instance "$hor_host" || return 0

	if [ -n "$no_force" ]; then
		! check_db_accessible "$hor_dbname" "$hor_user" "$hor_passwd" || return 0
	fi

	reset_user_password "$hor_user" "$hor_passwd" "$hor_host" && \
	check_db_accessible "$hor_dbname" "$hor_user" "$hor_passwd"
}

parse_mysql_dsn_get_user()
{
	echo $1 | perl -nle 'm|^mysql://([^:]+):([^@]+)@([^/:]+)(?::(\d+))?/(.*)$| and print $1 or exit 1'
}

parse_mysql_dsn_get_passwd()
{
	echo $1 | perl -nle 'm|^mysql://([^:]+):([^@]+)@([^/:]+)(?::(\d+))?/(.*)$| and print $2 or exit 1'
}

parse_mysql_dsn_get_host()
{
	echo $1 | perl -nle 'm|^mysql://([^:]+):([^@]+)@([^/:]+)(?::(\d+))?/(.*)$| and print $3 or exit 1'
}

parse_mysql_dsn_get_db()
{
	echo $1 | perl -nle 'm|^mysql://([^:]+):([^@]+)@([^/:]+)(?::(\d+))?/(.*)$| and print $5 or exit 1'
}

reset_roundcube_passwd()
{
	local no_force="$1"

	local roundcube_dsn=`get_roundcube_config_param "['db_dsnw']"`
	local roundcube_user=`parse_mysql_dsn_get_user "$roundcube_dsn"`
	local roundcube_passwd=`parse_mysql_dsn_get_passwd "$roundcube_dsn"`
	local roundcube_host=`parse_mysql_dsn_get_host "$roundcube_dsn"`
	local roundcube_db=`parse_mysql_dsn_get_db "$roundcube_dsn"`

	[ -n "$roundcube_passwd" -a -n "$roundcube_user" -a -n "$roundcube_db" ] || return 0

	is_local_mysql_instance "$roundcube_host" || return 0

	if [ -n "$no_force" ]; then
		! check_db_accessible "$roundcube_db" "$roundcube_user" "$roundcube_passwd" || return 0
	fi

	reset_user_password "$roundcube_user" "$roundcube_passwd" "$roundcube_host" && \
	check_db_accessible "$roundcube_db" "$roundcube_user" "$roundcube_passwd"
}

### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
phpmyadmin_config_backup()
{
	set_phpmyadmin_params
	if [ -f "$PHPMYADMIN_CONFIG" ]; then
		cp -f "$PHPMYADMIN_CONFIG" "$PHPMYADMIN_CONFIG_BACKUP"
	fi
}

phpmyadmin_rm_config_backup()
{
	rm -f "$PHPMYADMIN_CONFIG_BACKUP"
}

set_phpmyadmin_params()
{
	PHPMYADMIN_D="$PRODUCT_ROOT_D/phpMyAdmin"
	PHPMYADMIN_CONFIG="$PHPMYADMIN_D/config.plesk.php"
	# Executed as root, so must be placed in a directory which is root-owned and not world-writable
	PHPMYADMIN_CONFIG_BACKUP="$PLESK_DB_DIR/phpMyAdmin.config.php.save"

	# Layout of phpMyAdmin before 18.0.30
	PHPMYADMIN_D_OLD="$PRODUCT_ROOT_D/admin/htdocs/domains/databases/phpMyAdmin"
	PHPMYADMIN_CONFIG_OLD="$PHPMYADMIN_D_OLD/libraries/config.default.php"
}

pma__write_values_to_config()
{
	(
		umask 0027
		sed -e "`pma__sed_script`" < "$PHPMYADMIN_CONFIG.tpl" > "$PHPMYADMIN_CONFIG" || return 1
		set_admin_params
		set_ac root "$admin_group" 0640 "$PHPMYADMIN_CONFIG"
	)
}

pma__set_default_values()
{
	controluser="phpmyadmin"
	controlpass="`get_random_string 16`"
	pmadb="phpmyadmin"
}

pma__sed_script()
{
	echo "
	s|@@""CONTROLUSER""@@|$controluser|g
	s|@@""CONTROLPASS""@@|$controlpass|g
	s|@@""PMADB""@@|$pmadb|g
	"
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.

install_postfix_certificate()
{
	local force=
	if [ $# -ne 0 ]; then
		force="yes"
	fi

	local CERT_DIR=`/usr/sbin/postconf -h config_directory`
	local TLS_CERT=${CERT_DIR}/postfix_default.pem

	if ! mkdir_ex 0 0 755 ${CERT_DIR}; then
		warn "Unable to create directory for ${CERT_DIR} with proper permissions."
		return 1
	fi

	[ -z "${force}" -a -f ${TLS_CERT} ]	&& return ||:

	get_certificate "${TLS_CERT}"
	set_ac 0 0 600 "${TLS_CERT}"
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.

# $1 - openssl binary
# $2 - openssl args
# $3 - cert file name
# $4 - bits number
qmail_tls_cert()
{
	local QMAIL_CONTROL_D TLS_CERT

	QMAIL_CONTROL_D=${QMAIL_ROOT_D}/control
	TLS_CERT=${QMAIL_CONTROL_D}/$3

	if [ ! -f ${TLS_CERT} ]; then
		$1 $2 -out ${TLS_CERT} $4 >> $product_log 2>&1
		if [ $? -ne 0 ]; then
			warn "Certificate for qmail TLS sessions ${TLS_CERT} was not generated. Qmail will generate it at each TLS session. It is too slow and will make high CPU load."
		fi
		p_echo
	fi

	if [ -f ${TLS_CERT} ]; then
		chmod 600 ${TLS_CERT} && chown qmaild:0 ${TLS_CERT}
		if [ $? -ne 0 ]; then
			# Fallback for case when qmail is not installed
			chmod 600 ${TLS_CERT} && chown root:0 ${TLS_CERT}
			warn "Unable to set proper permission to ${TLS_CERT} Normally, owner user and group should be qmaild:0 and access should be 0600."
		fi
	fi
}

generate_tls_certificates()
{
	local SSL_BIN inten umask_sav

	inten="generate SSL certificates for TLS sessions"

	echo_try $inten

	SSL_BIN=/usr/bin/openssl

	# store old umask and set very secure one
	umask_sav=`umask`
	umask 0077

	qmail_tls_cert ${SSL_BIN} "genrsa" rsa512.pem 512
	#qmail_tls_cert ${SSL_BIN} "dhparam -2" dh512.pem 512
	#qmail_tls_cert ${SSL_BIN} "dhparam -2" dh1024.pem 1024

	umask ${umask_sav}

	suc
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
#qmail

set_qmail_params()
{
    QMAIL_DIR="/var/qmail"
    QMAIL_USERS="alias:2021:nofiles:false:alias qmaild:2020:nofiles:false: qmaill:2022:nofiles:false: qmailp:2023:nofiles:false: qmailq:2520:qmail: qmailr:2521:qmail: qmails:2522:qmail:"
    QMAIL_GROUPS="qmail:2520 nofiles:2020"

    #variable from psa.conf but used in mail-qc-driver
    #so we need define this before install psa base package
    if [ -z "$QMAIL_ROOT_D" ]; then 
	    QMAIL_ROOT_D="/var/qmail"
    fi

    qmail_service="qmail"
    qmail_extra_cmd=""
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
set_horde_params()
{
	horde_datadir="/usr/share/psa-horde"
	horde_confdir="/etc/psa-webmail/horde"
	horde_sysconfd="$horde_confdir/horde"
	horde_logdir="/var/log/psa-horde"
	horde_passwd_file="/etc/psa-webmail/horde/.horde.shadow"
	horde_title="Horde Web Based mail client"

	imp_datadir="$horde_datadir/imp"
	imp_sysconfd="$horde_confdir/imp"
	
	turba_datadir="$horde_datadir/turba"
	turba_sysconfd="$horde_confdir/turba"

	kronolith_datadir="$horde_datadir/kronolith"
	kronolith_sysconfd="$horde_confdir/kronolith"

	ingo_datadir="$horde_datadir/ingo"
	ingo_sysconfd="$horde_confdir/ingo"

	mnemo_datadir="$horde_datadir/mnemo"
	mnemo_sysconfd="$horde_confdir/mnemo"
	
	passwd_datadir="$horde_datadir/passwd"
	passwd_sysconfd="$horde_confdir/passwd"

	horde_user="horde_sysuser"
	horde_group="horde_sysgroup"

	horde_php_ini="/etc/psa-webmail/horde/horde/php.ini"
	horde_conf_php="/etc/psa-webmail/horde/horde/conf.php"

	horde_db_user_privileges=(
		"ALTER"
		"CREATE"
		"DELETE"
		"DROP"
		"INDEX"
		"INSERT"
		"REFERENCES"
		"SELECT"
		"UPDATE"
	)
}

generate_horde_password()
{
	local inten='generate horde password'

	local dsn_horde_password="`get_dsn horde password`"
	if [ -n "$dsn_horde_password" -a ! -s "$horde_passwd_file" ]; then
		echo "$dsn_horde_password" > "$horde_passwd_file"
	fi

	generate_password_file "$horde_passwd_file" "$horde_title" root "$horde_group" 640
	horde_password=`cat $horde_passwd_file` || die $inten
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
generate_roundcube_password()
{
	local inten='generate roundcube password'

	local dsn_roundcube_password="`get_dsn roundcube password`"
	if [ -n "$dsn_roundcube_password" -a ! -s "$roundcube_passwd_file" ]; then
		echo "$dsn_roundcube_password" > "$roundcube_passwd_file"
	fi

	generate_password_file "$roundcube_passwd_file" "$roundcube_title" root root 640
	roundcube_password=`cat $roundcube_passwd_file` || die $inten
}

update_roundcube_db_settings()
{
	local cfg_db_dsnw="\$config\['db_dsnw'\]"

	local host="`get_dsn roundcube host`"
	local port="`get_dsn roundcube port`"
	local db_user="$roundcube_db_user"
	local db_name="$roundcube_db_name"

	local roundcube_dsn=`get_roundcube_config_param "['db_dsnw']"`
	[ -n "$db_user" ] || db_user=`parse_mysql_dsn_get_user "$roundcube_dsn"`
	[ -n "$db_name" ] || db_name=`parse_mysql_dsn_get_db "$roundcube_dsn"`

	sed -e "s#${cfg_db_dsnw}.*#${cfg_db_dsnw} = 'mysql://${db_user}:${roundcube_password}@${host:-localhost}${port:+:$port}/${db_name}';#" \
		-i ${roundcube_conf}
}
### Copyright 1999-2024. WebPros International GmbH. All rights reserved.
# vim:set ft=sh:

set_roundcube_params()
{
	roundcube_passwd_file="/usr/share/psa-roundcube/config/.roundcube.shadow"
	roundcube_title="Roundcube Web Based mail client"
	roundcube_conf="/usr/share/psa-roundcube/config/config.inc.php"
	roundcube_conf_defaults="/usr/share/psa-roundcube/config/defaults.inc.php"
	roundcube_sql_d="/usr/share/psa-roundcube/SQL"
	roundcube_user="roundcube_sysuser"
	roundcube_group="roundcube_sysgroup"
	roundcube_home="/usr/share/psa-roundcube"
	roundcube_logs_d="/var/log/plesk-roundcube"
	roundcube_temp_d="/var/tmp"

	roundcube_php_ini="/etc/psa-webmail/roundcube/php.ini"
	roundcube_php_ini_tpl="/usr/share/psa-roundcube/config/php.ini.tpl"

	roundcube_preupgrade_version_file="/etc/psa-webmail/roundcube/version.upg"

	roundcube_db_user_privileges=(
		"ALTER"
		"CREATE"
		"DELETE"
		"DROP"
		"INDEX"
		"INSERT"
		"REFERENCES"
		"SELECT"
		"UPDATE"
	)
}

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

rstinst_update_default_cert_copy()
{
	local src="$certificate_file"
	local dst="$1"
	[ -n "$dst" ] || die "rstinst_update_default_cert_copy(): certificate file required"

	if diff -q "$certificate_file_old" "$dst" >/dev/null 2>&1 ; then
		cp -fp "$src" "$dst"
		set_ac 0 0 0400 "$dst"
	else
		p_echo "Not touching custom or absent certificate $dst"
	fi
}

rstinst_backup_old_default_cert()
{
	pp_echo "  Creating default certificate backup..."
	certificate_file_old="$certificate_file.old"
	cp -fp "$certificate_file" "$certificate_file_old"
}

rstinst_default_cert()
{
	set_admin_params
	pp_echo "  Updating default certificate..."
	cp -fp "$ADMIN_CERT" "$certificate_file"
}

rstinst_wipe_old_default_cert()
{
	pp_echo "  Removing default certificate backup..."
	rm -f "$certificate_file_old"
}

rstinst_reset_courier_imap_certs()
{
	set_courier_imap_params
	pp_echo "  Updating Courier-IMAP certificates..."

	rstinst_update_default_cert_copy "$IMAPD_CERT"
	rstinst_update_default_cert_copy "$POP3D_CERT"
}

rstinst_reset_dovecot_cert()
{
	set_dovecot_params
	pp_echo "  Updating Dovecot certificate..."

	rstinst_update_default_cert_copy "$DOVECOT_CERT"
}

rstinst_reset_mail_certs()
{
	if rstinst_is_qmail; then
		rstinst_reset_qmail_certs
	elif rstinst_is_postfix; then
		pp_echo "  Generating new Postfix certificates..."
		install_postfix_certificate force
	fi
}

rstinst_reset_qmail_certs()
{
	set_qmail_params
	local qmail_control_d="$QMAIL_ROOT_D/control"
	local qmail_tls_cert="$qmail_control_d/rsa512.pem"
	local qmail_client_cert="$qmail_control_d/clientcert.pem"
	local qmail_server_cert="$qmail_control_d/servercert.pem"
	[ -d "$qmail_control_d" ] || return 0

	pp_echo "  Generating new QMail certificates..."

	local qmail_user=qmaild
	local qmail_group=qmail
	if ! id "$qmail_user" 1>/dev/null 2>&1 || ! groupmod "$qmail_group" 1>/dev/null 2>&1 ; then
		# Qmail may not be actually installed, but we need to update certs nonetheless
		qmail_user=root
		qmail_group=0
	fi

	rm -f "$qmail_tls_cert" && \
	[ "$qmail_user" != "root" ] && generate_tls_certificates

	rstinst_update_default_cert_copy "$qmail_server_cert" && \
	set_ac "$qmail_user" "$qmail_group" 0640 "$qmail_server_cert"

	if [ ! -L "$qmail_client_cert" ] || [ "`readlink $qmail_client_cert`" != "$qmail_server_cert" ]; then
		rstinst_update_default_cert_copy "$qmail_client_cert" && \
		set_ac "$qmail_user" "$qmail_group" 0640 "$qmail_client_cert"
	fi
}

rstinst_generate_certificates()
{
	pp_echo " Generating new certificates..."
	rstinst_cloning_action create-backup-sign
	rstinst_cloning_action delete-certificates
	rstinst_default_cert
	rstinst_reset_courier_imap_certs
	rstinst_reset_dovecot_cert
	rstinst_reset_mail_certs
	rstinst_wipe_old_default_cert
}

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

rstinst_check_bool_misc_param()
{
	local param="$1"
	local default_value="$2"
	[ -n "$param" ] || die "rstinst_check_bool_misc_param(): parameter name required"
	[ -n "$default_value" ] || default_value="false"

	local param_value=`db_read_misc_attr "$param"`
	[ -n "$param_value" ] || param_value="$default_value"
	[ "$param_value" = "true" ]
}

rstinst_is_reset_init_conf_scheduled()
{
	rstinst_check_bool_misc_param "vps_cloning_reset_init_conf"
}

rstinst_is_license_keys_reset_scheduled()
{
	rstinst_check_bool_misc_param "vps_cloning_license_reset"
}

rstinst_is_public_image_cloning_mode()
{
	rstinst_check_bool_misc_param "vps_cloning_mode"
}

rstinst_is_public_image_cloning_started()
{
	rstinst_check_bool_misc_param "vps_cloning_started"
}

rstinst_is_update_master_key_scheduled()
{
	rstinst_check_bool_misc_param "vps_cloning_update_master_key"
}

rstinst_is_qmail()
{
	[ -x ${PRODUCT_ROOT_D}/admin/sbin/mailmng-server ] || return 1
	${PRODUCT_ROOT_D}/admin/sbin/mailmng-server --features | grep -q "SMTP_Server_package.*qmail"
}

rstinst_is_postfix()
{
	[ -x ${PRODUCT_ROOT_D}/admin/sbin/mailmng-server ] || return 1
	${PRODUCT_ROOT_D}/admin/sbin/mailmng-server --features | grep -q "SMTP_Server_package.*postfix"
}

rstinst_cloning_action()
{
	local action="$1"
	sw_engine_pleskrun "$PRODUCT_ROOT_D/admin/plib/scripts/cloning_actions.php" --do "$action" >> $product_log 2>&1
}

rstinst_set_status_flag()
{
	[ -n "$1" -a -n "$2" ] || return
	local status_d="$rstinst_status_d/$1"
	local flag="$2.flag"

	[ -d "$status_d" ] || mkdir -p "$status_d"
	echo `date +%s` >> "$status_d/$flag"
}

rstinst_check_status_flag()
{
	[ -f "$rstinst_status_d/$1/$2.flag" ]
}

rstinst_set_subtask_status_flag()
{
	rstinst_set_status_flag "subtask" "$1"
}

rstinst_setup_report_cloning()
{
	touch /var/lock/plesk-report-cloning.flag
}

rstinst_report_cloning()
{
	local rc="$1"
	local launcher="$PRODUCT_ROOT_D/bin/py3-python"
	local flag="/var/lock/plesk-report-cloning.flag"

	local report_bin="/root/parallels/report-update"
	[ -s "$report_bin" ] ||
		report_bin="/var/cache/parallels_installer/report-update"
	[ -d "`dirname "$report_bin"`" ] ||
		install -m 0700 -o root -g root -d "`dirname "$report_bin"`"
	[ -s "$report_bin" ] ||
		/usr/bin/curl -m 300 --retry 3 -fsSL "http://autoinstall.plesk.com/report-update" \
			-o "$report_bin" >> "$product_log" 2>&1
	[ -s "$report_bin" ] || {
		warn "locate or download report-update utility to report cloning result"
		return 1
	}

	"$launcher" "$report_bin" --op "clone" --rc "$rc" --start-flag "$flag" >> "$product_log" 2>&1
}

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

set_maintenance_mode_params()
{
	maintenance_sw_cp_server_config="/etc/sw-cp-server/conf.d/maintenance"
	maintenance_status="$PRODUCT_ROOT_D/var/maintenance/status.json"

	maintenance_scheduled=""
	maintenance_enabled=""
	if rstinst_is_maintenance_mode_scheduled; then
		maintenance_scheduled="true"
	fi
	if rstinst_is_maintenance_mode_enabled; then
		maintenance_enabled="true"
	fi

}

report_maintenance_status()
{
	local stage="$1"
	local percentage="$2"
	local message="$3"

	[ -n "$maintenance_enabled" ] || return
	echo '{"status":"'$stage'","progress":"'$percentage'","message":"'$message'"}' > "$maintenance_status"
}

rstinst_is_maintenance_mode_scheduled()
{
	rstinst_check_bool_misc_param "vps_cloning_maintenance_mode"
}

rstinst_is_maintenance_mode_enabled()
{
	grep -q '^set $maintenance on;' "$maintenance_sw_cp_server_config"
}

rstinst_enable_maintenance_mode()
{
	if [ -z "$maintenance_scheduled" ]; then
		echo "Maintenance mode does not schedued in database"
		return
	fi

	echo 'set $maintenance on;' > "$maintenance_sw_cp_server_config"
	maintenance_enabled="true"
}

rstinst_disable_maintenance_mode()
{
	if [ -z "$maintenance_scheduled" -o -z "$maintenance_enabled" ]; then
		return
	fi

	echo 'set $maintenance off;' > "$maintenance_sw_cp_server_config"
	rm -f "$maintenance_status"
	maintenance_enabled=""
}

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

rstinst_reread_admin_passwd()
{
	admin_passwd=
	set_mysql_auth
}

rstinst_gen_passwd()
{
	get_random_string 16 'A-Za-z0-9_'
}

rstinst_recipher_passwords()
{
	rstinst_cloning_action reset-secret-key || warn 'generating new encryption key and switching to it'
	rstinst_reread_admin_passwd
}

rstinst_reset_admin_passwd()
{
	pp_echo "  Generating new admin password..."
	rstinst_cloning_action reset-admin-password || warn 'resetting admin password'
	rstinst_reread_admin_passwd
}

rstinst_reset_sitebuilder_passwd()
{
	local sb_conf="/usr/local/sb/config"
	[ -f "$sb_conf" ] || return 0

	local sb_host=`get_ini_conf_var "$sb_conf" "database" "host"`
	is_local_mysql_instance "$sb_host" || return 0

	pp_echo "  Generating new WPB (sitebuilder) password..."

	set_ini_conf_var "$sb_conf" "database" "password" `rstinst_gen_passwd`
	reset_sitebuilder_passwd
}

rstinst_reset_apsc_passwd()
{
	check_apsc_installed || return 0

	read_apsc_connection_params_db
	is_local_mysql_instance "$apsc_db_host" || return 0

	pp_echo "  Generating new APS controller password..."

	apsc_db_passwd=`rstinst_gen_passwd`
	reset_user_password "$apsc_db_user" "$apsc_db_passwd" "$apsc_db_host" && \
	save_apsc_connection_params_db && \
	sw_engine_pleskrun "$PRODUCT_ROOT_D/admin/plib/scripts/check_apsc_connection.php" >>"$product_log" 2>&1
	[ $? -eq 0 ] || warn "connect to APS controller database with new password"
}

rstinst_reset_horde_passwd()
{
	set_horde_params
	[ -s "$horde_passwd_file" ] || return 0

	local hor_host=`get_horde_config_param "['sql']['hostspec']" "localhost"`
	is_local_mysql_instance "$hor_host" || return 0

	pp_echo "  Generating new $horde_title password..."

	rm -f "$horde_passwd_file" && \
	generate_horde_password && \
	reset_horde_passwd
}

rstinst_reset_roundcube_passwd()
{
	set_roundcube_params
	[ -s "$roundcube_passwd_file" ] || return 0

	pp_echo "  Generating new $roundcube_title password..."
	rm -f "$roundcube_passwd_file" && \
	generate_roundcube_password && \
	update_roundcube_db_settings && \
	reset_roundcube_passwd
}

rstinst_reset_phpmyadmin_passwd()
{
	set_phpmyadmin_params
	phpmyadmin_config_backup || return 0

	pp_echo "  Generating new phpMyAdmin password..."

	local pmahost="localhost"
	local controluser controlpass pmadb
	pma__set_default_values
	controlpass=`rstinst_gen_passwd`

	[ -n "$controlpass" -a -n "$controluser" -a -n "$pmadb" ] && \
	pma__write_values_to_config && \
	reset_user_password "$controluser" "$controlpass" "$pmahost" && \
	check_db_accessible "$pmadb" "$controluser" "$controlpass" && \
	phpmyadmin_rm_config_backup
	[ $? -eq 0 ] || warn "connect to phpMyAdmin database with new password"
}

rstinst_reset_mysql_debian_sys_maint_passwd()
{
	local mysql_debian_cnf="/etc/mysql/debian.cnf"

	[ -f "$mysql_debian_cnf" ] || return 0

	# debian-sys-maint is not used on Debian 9 anymore
	egrep -q "user\s*=\s*debian-sys-maint" /etc/mysql/debian.cnf || return 0

	pp_echo "  Generating new debian-sys-maint mysql password..."
	local mysql_debian_pass=`rstinst_gen_passwd`
	perl -i -ple '$_ = "$1 = '$mysql_debian_pass'" if /^(\s*password\s*)=/' "$mysql_debian_cnf"
	db_do "SET PASSWORD FOR 'debian-sys-maint'@localhost = PASSWORD('$mysql_debian_pass')"
}

rstinst_remove_additional_admins()
{
    pp_echo "  Removing additional administrators..."
    rstinst_cloning_action cleanup-admin-aliases
}

rstinst_generate_passwords()
{
	pp_echo " Generating new passwords..."
	rstinst_recipher_passwords
	rstinst_reset_admin_passwd
	rstinst_remove_additional_admins
	rstinst_reset_sitebuilder_passwd
	rstinst_reset_apsc_passwd
	rstinst_reset_horde_passwd
	rstinst_reset_roundcube_passwd
	rstinst_reset_phpmyadmin_passwd
	rstinst_reset_mysql_debian_sys_maint_passwd
	# Postgres is not configured by default.
}

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

rstinst_reset_libswkey_store()
{
	rstinst_is_license_keys_reset_scheduled || return 0
	pp_echo " Resetting license keys store..."

	local swkey_store="/etc/sw/keys"
	rm -rf $swkey_store/backup/*
	rm -rf $swkey_store/keys/*
	rm -rf $swkey_store/instances
	rm -f  $swkey_store/registry.xml
	install_default_license_key
}

rstinst_generate_guids()
{
	pp_echo " Generating new GUIDs for BL entities..."
	rstinst_cloning_action reset-guids
}

rstinst_reshuffle_cron_tasks()
{
	pp_echo " Randomizing cron tasks execution time shifts..."

	update_postfix_poplockdb_cleanup_crontab
	remove_cron_backup; install_cron_backup
}

rstinst_clean_panel_sessions()
{
	p_echo "  Cleaning Panel sessions..."
	clean_panel_sessions
}

rstinst_schedule_init_conf_screens()
{
	pp_echo " Enabling initial configuration screens on next admin login..."

	# show license, admin info, ip and passwd initial configuration screens
	rstinst_cloning_action schedule-init-conf-screens
	rstinst_clean_panel_sessions
}

rstinst_update_master_key()
{
	rstinst_is_update_master_key_scheduled || return 0
	pp_echo " Updating Plesk license key..."
	rstinst_cloning_action update-master-key
}

rstinst_reset_owner_id()
{
	pp_echo " Reset owner id..."
	db_do "DELETE FROM PleskStats WHERE param = 'cloudAccountId'"
}

rstinst_reset_upgrade_history()
{
    pp_echo " Reset upgrade history..."
    rstinst_cloning_action reset-upgrade-history
}

rstinst_reset_stats()
{
    pp_echo " Reset statistics..."
    rstinst_cloning_action reset-stats
}

rstinst_reset_one_time_logins()
{
    pp_echo " Reset one-ltime logins..."
    rstinst_cloning_action reset-one-time-logins
}

rstinst_reset_panel_certificate()
{
	pp_echo " Resetting existing certificate..."
	rstinst_backup_old_default_cert
	rstinst_cloning_action create-panel-certificate
}

rstinst_remap_ips()
{
	pp_echo " Remapping IP addresses..."
	rstinst_cloning_action remap-ips
}

rstinst_reset_all()
{
	pp_echo "Resetting instance-specific settings..."
	rstinst_reset_one_time_logins
	rstinst_reset_owner_id
	rstinst_reset_panel_certificate
	rstinst_remap_ips
	rstinst_generate_guids
	rstinst_update_master_key
	rstinst_generate_passwords
	rstinst_generate_certificates
	rstinst_reshuffle_cron_tasks
	rstinst_reset_libswkey_store
	rstinst_schedule_init_conf_screens
	rstinst_reset_upgrade_history
	rstinst_reset_stats
}

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

rstinst_trunc_postfix_aliases_db()
{
	# remove records related to admin's mail
	for key in anonymous drweb drweb-daemon kluser mailer-daemon mailman postmaster root ; do
		"/usr/sbin/postalias" -d "$key" "hash:/var/spool/postfix/plesk/aliases" >> $product_log 2>&1 || :
	done
}

rstinst_fix_hostname_postfix_virtual_db()
{
	local myhostname=`"/usr/sbin/postconf" -h myhostname`
	local myhostname_matched=

	db_select "select name from domains union all select name from domain_aliases"
	local domains="$db_select_output"

	# prepare records to remove
	local to_rm=`"/usr/sbin/postmap" -s "hash:/var/spool/postfix/plesk/virtual"`

	# do not remove records related to existing domains or domain aliases
	for domain in $domains; do
		[ "$domain" != "$myhostname" ] || myhostname_matched="yes"
		to_rm=`printf "$to_rm" | grep -v "^\([[:alnum:]_-]\+@\)\?${domain}\s"`
	done

	# remove records related to old hostname if exists
	for key in `printf "${to_rm}" | awk '{print $1}'`; do
		"/usr/sbin/postmap" -d "$key" "hash:/var/spool/postfix/plesk/virtual" >> $product_log 2>&1
	done

	# create default domain aliases if needed
	if [ -z "$myhostname_matched" ]; then
		for name in anonymous drweb kluser mailer-daemon postmaster root; do
			echo "$name@$myhostname $name@localhost.localdomain" | "/usr/sbin/postmap" -i "hash:/var/spool/postfix/plesk/virtual" >> $product_log 2>&1
		done
		echo "$myhostname 1" | "/usr/sbin/postmap" -i "hash:/var/spool/postfix/plesk/virtual" >> $product_log 2>&1
	fi
}

rstinst_reconfigure_mailserver()
{
	pp_echo " Reconfiguring mailserver..."
	if rstinst_is_postfix; then
		pp_echo " ==> Fix mailsrv settings..."

		! rstinst_is_reset_init_conf_scheduled || rstinst_trunc_postfix_aliases_db
		rstinst_fix_hostname_postfix_virtual_db
		"/usr/lib64/plesk-9.0/postfix-poplockdb-clean" >> $product_log 2>&1
		"/usr/lib64/plesk-9.0/remote_mail_restore/mail_auth_dump" >> $product_log 2>&1

		"/usr/local/psa/admin/sbin/mailmng-service" --restart-service --mail-component=daemons-only >> $product_log 2>&1 &
	fi
}

rstinst_reconfigure_webservers()
{
	pp_echo " Reconfiguring Webservers..."
	# This is at least needed to accommodate to default certificate change.
	# However, normaly there are no domains when this utility is called,
	# so it shouldn't take long.
	reconfigure_apache_if_needed
}

rstinst_update_all_services()
{
	pp_echo "Reloading services configuration..."
	rstinst_reconfigure_webservers
	rstinst_reconfigure_mailserver
	# We would also need to restart various services, if the script was run manually.
	# But that is not a top priority right now.
}

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

rstinst_is_updates_available()
{
	db_select "select count(42) from smb_componentUpdates"
	if [ -n "$db_select_output" -a "$db_select_output" == "0" ]; then
		echo "No updates for currently installed components found"
		return 1
	fi
}

rstinst_deferred_install_updates()
{
	! rstinst_check_bool_misc_param "vps_cloning_skip_update" || return 0
	pp_echo "Scheduling automatic product update..."
	rstinst_cloning_action set-skip-update

	{
		rstinst_set_subtask_status_flag "update"
		local ts_start=`date +%s`

		# check for updates
		rstinst_set_subtask_status_flag "update-check"
		sw_engine_pleskrun "$PRODUCT_ROOT_D/admin/plib/DailyMaintainance/script.php" -f "CheckForUpdates"
		rstinst_set_subtask_status_flag "update-check.complete"

		rstinst_reread_admin_passwd
		if rstinst_is_updates_available; then
			rstinst_set_subtask_status_flag "update.available"
			echo "Updates for currently installed components found"

			# sleep for default login_timeout before first attempt to updates installation
			local t_sleep=1800
			local ts_next=$((`date +%s` + t_sleep))
			echo "Updates installation is delayed for $t_sleep seconds (till `date -d @$ts_next`)"
			sleep "$t_sleep"
			rstinst_reread_admin_passwd

			while true ; do
				# check for updates available (it may already be installed by admin itself)
				rstinst_is_updates_available || break

				# if active session found then go to sleep
				db_select "select ifnull(max(modified + lifetime), 0) from sessions"
				t_sleep=$((db_select_output - `date +%s`))

				if [ "$t_sleep" -gt "0" ]; then
					echo "Active panel session was found"

					[ "$t_sleep" -le "300" ] || t_sleep=300
					ts_next=$((`date +%s` + t_sleep))
					if [ $((ts_next - ts_start)) -gt 43200 ]; then
						rstinst_set_subtask_status_flag "update.timeout"
						echo "Update installation is aborted due timeout"
						break
					fi

					echo "Updates installation is delayed for $t_sleep seconds (till `date -d @$ts_next`)"
					rstinst_set_subtask_status_flag "update-delay"
					sleep "$t_sleep"
					rstinst_reread_admin_passwd
					rstinst_set_subtask_status_flag "update-delay.complete"
					continue
				fi

				rstinst_set_subtask_status_flag "update-install"
				echo "Starting asynchronous product update task..."
				sw_engine_pleskrun "$PRODUCT_ROOT_D/admin/plib/DailyMaintainance/script.php" -f "InstallUpdates"
				rstinst_set_subtask_status_flag "update-install.complete"
				echo "Asynchronous update task completed with return code $?"
				echo
				break
			done
		fi

		rstinst_set_subtask_status_flag "update.complete"
	} >> $product_log 2>&1 &
}

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

reexec_with_clean_env "$@"

prog="`basename $0`"
rstinst_action="$1"
shift
rstinst_args="$@"

usage() {
cat << EOT
Usage: $prog <command> [options]

Available commands and options:
    schedule   Schedule cloning service to be run on the next boot.

    start-pre  Perform preliminary actions. Used by plesk-cloning.service.
               This command is called automatically in the scope
               of 'start' command if it hasn't been called before.

    start      Perform cloning.
    --force    Reset instance-specific data regardless of currently
               active cloning mode options.

    status     Get current status of the cloning procedure.
    --json     Use json formatted output.

    help       Show this help message.

WARNING:

You probably don't want to invoke this utility directly. It will reset ALL
global instance-specific data on this machine, including but not limited to
passwords, certificates, and optionally license keys.

If you are preparing a public master image for a cloud platform or
virtualization solution take a look at 'cloning' utility.

If you are sure you need to invoke this utility directly, pass
'--do-what-I-say' option along with '$prog start'. Note that this utility
is not designed to reset any customer data, but only global and admin data.
EOT
	exit 1
}

rstinst_check_args()
{
	local opt_do_what_i_say=

	for arg in $rstinst_args; do
		case "${rstinst_action}${arg}" in
			start--do-what-I-say)
				opt_do_what_i_say="yes"
			;;
			start--force)
				opt_force_instance_reset="yes"
			;;
			status--json)
				opt_status_json="yes"
			;;
			help*|*-h|*--help)
				usage
			;;
			*)
				echo "Unknown argument '$arg'"
				echo
				usage
			;;
		esac
	done

	[ "${rstinst_action}" != "start" -o -n "$opt_do_what_i_say" ] || usage
}

rstinst_log_title()
{
	echo "$prog $rstinst_action $rstinst_args AT `date`"
}

rstinst_init()
{
	set_log_action_name "$prog"
	[ "$rstinst_action" == "status" ] || log_transaction_start "`rstinst_log_title`"

	rstinst_check_args

	product_default_conf
	initial_conf
	set_common_params
	read_conf

	rstinst_status_d="$PRODUCT_ROOT_D/var/$prog/status"

	[ "$rstinst_action" != "schedule" ] || rm -rf "$rstinst_status_d"

	if [ "$rstinst_action" != "status" ]; then
		set_error_report_source "backend"
		set_error_report_component "reset_instance_data"
		set_error_report_context "`rstinst_log_title`"

		# mysql isn't required for the prereset stage
		# moreover it may not yet be ready to accept connections
		# see plesk-cloning.service for details
		[ "$rstinst_action" = "prereset" ] || uses_mysql_client
		set_apache_params
		set_swcpserver_params
		set_maintenance_mode_params
	fi
}

rstinst_do_action()
{
	local action="$1"
	[ -n "$action" ] || return 1
	rstinst_set_status_flag "action" "$action.started"
	rstinst_${action} && rstinst_set_status_flag "action" "$action.completed"
}

rstinst_check_action_started()
{
	rstinst_check_status_flag "action" "$1.started"
}

rstinst_check_action_completed()
{
	rstinst_check_status_flag "action" "$1.completed"
}

rstinst_get_status()
{
	local status=

	if rstinst_check_action_completed "postreset"; then
		# already finished
		rstinst_check_action_completed "reset" && status="completed" || status="error"
	elif rstinst_check_action_started "prereset"; then
		# was started, check service is running
		local is_active=`/bin/systemctl is-active plesk-cloning.service`
		if [ "$is_active" == "activating" -o "$is_active" == "active" -o "$is_active" == "deactivating" ]; then
			status="running"
		elif rstinst_check_action_completed "postreset"; then
			# service has been exited right now, recheck is required
			status=`rstinst_get_status`
		else
			status="error"
		fi
	elif rstinst_check_action_started "schedule"; then
		# was scheduled, check service is enabled
		if /bin/systemctl is-enabled plesk-cloning.service >/dev/null 2>&1; then
			status="scheduled"
		elif rstinst_check_action_started "prereset"; then
			# service has been started rigth now, recheck is required
			status=`rstinst_get_status`
		else
			status="error"
		fi
	fi

	echo "${status:-absent}"
}

rstinst_status()
{
	local status=`rstinst_get_status`

	if [ -z "$opt_status_json" ]; then
		echo "$status"
	else
		echo "{\"status\":\"$status\"}"
	fi
}

rstinst_schedule()
{
	register_service plesk-cloning
}

rstinst_prereset()
{
	rstinst_setup_report_cloning

	# make sure the service is invoked only once
	unregister_service plesk-cloning

	# normally this code runs in the scope of ExecStartPre section of plesk-cloning.service
	# it is executed before start of sw-cp-server due Requires/After options of the service
	# so reload isn't required to apply maintenance mode
	rstinst_enable_maintenance_mode
	report_maintenance_status "clone" 0
}

rstinst_reset()
{
	if [ "$opt_force_instance_reset" != "yes" ]; then
		if ! rstinst_is_public_image_cloning_mode || rstinst_is_public_image_cloning_started; then
			die "No cloning was scheduled or one already started"
		fi
	fi

	rstinst_cloning_action start-event

	# Note: general policy for this script is to avoid interrupting its
	# execution unless something _extremely_ bad happened.
	# Ideally we should execute each action that might fail in a separate
	# subshell. But that would dramatically influence global variables
	# and therefore probably introduce a couple of new critical bugs.

	report_maintenance_status "clone" "30" "Resetting instance-specific settings..."
	rstinst_reset_all
	report_maintenance_status "clone" "60" "Reloading services configuration..."
	rstinst_update_all_services
	report_maintenance_status "clone" "90" "Scheduling automatic product update..."
	rstinst_deferred_install_updates
	pp_echo "Completed"

	rstinst_cloning_action complete-event
}

rstinst_postreset()
{
	rstinst_disable_maintenance_mode
	pleskrc swcpserver try-reload
}

rstinst_do_action_postreset()
{
	rstinst_do_action "postreset"
	rstinst_report_cloning "$TRANSACTION_RETURN_CODE"
}

rstinst_init

true rstinst_schedule rstinst_prereset rstinst_reset rstinst_postreset
case "$rstinst_action" in
	schedule)
		rstinst_do_action "schedule"
	;;
	start-pre)
		rstinst_do_action "prereset"
	;;
	start)
		transaction_add_rollback_action	"rstinst_do_action_postreset"
		transaction_add_commit_action	"rstinst_do_action_postreset"

		# execute preliminary actions if util is started not by systemd
		if ! rstinst_check_action_started "prereset"; then
			rstinst_do_action "prereset"
			# reload of sw-cp-server is required to apply maintenance mode
			pleskrc swcpserver try-reload
		fi

		rstinst_do_action "reset"
	;;
	status)
		rstinst_status
	;;
	*)
		usage
	;;
esac

# vim:ft=sh
