#!/bin/bash
### Copyright 1999-2026. 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-2026. 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
}
### Copyright 1999-2026. 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"
	pleskrc_is_failure_for_action_ok "$action" || 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="$?"

	pleskrc_is_failure_for_action_ok "$action" || {
		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
	}

	return $ret
}

pleskrc_is_failure_for_action_ok()
{
	local action="$1"
	case "$action" in
		status|exists|is-active|is-enabled|is-failed) return 0 ;;
	esac
	return 1
}

# 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"
}

# 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
}

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"
}

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"
}

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

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-2026. WebPros International GmbH. All rights reserved.

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

	local update_ticket="`get_update_ticket`"

	set_error_report_source
	set_error_report_component
	set_error_report_params
	set_error_report_environment

	true construct_report_code construct_report_debug construct_report_message

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

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

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

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

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

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

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

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

construct_report_message()
{
	product_and_problems_log_tail

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

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

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

	set_error_report_source
	get_product_versions

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

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

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

	local summary="$1"

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

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

	construct_report "$severity" "$summary"

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

	problems_occured=1
}

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

set_error_report_component()
{
	local component="$1"

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

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

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

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

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

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

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

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

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

get_update_ticket()
{
	[ -r $PRODUCT_ROOT_D/var/update_ticket ] && cat $PRODUCT_ROOT_D/var/update_ticket | awk '{$1=$1};1'
}
### Copyright 1999-2026. 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-2026. 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-2026. 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
}
### Copyright 1999-2026. WebPros International GmbH. All rights reserved.
# vim:ft=sh

selinux_is_active()
{
	if [ -z "$SELINUX_ENFORCE" ]; then
		selinux_getenforce
	fi

	case "$SELINUX_ENFORCE" in
	Enforcing|Permissive) return 0;;
	*) return 1;;
	esac
}

selinux_support_is_installed()
{
	# This function checks if Plesk SELinux support component is installed
	set_selinux_params
	[ -s "$selinux_module" ]
}

selinux_configuration_is_required()
{
	# All public functions that modify SELinux state should check that this is true!
	selinux_is_active && selinux_support_is_installed
}

selinux_get_mount_dir()
{
	unset SELINUX_MOUNT_DIR

	if awk '$2 == "/selinux"{exit(1)}' /proc/mounts && mkdir -p /selinux; then
		SELINUX_MOUNT_DIR=/selinux
	else
		SELINUX_MOUNT_DIR="`mktemp -d /tmp/selinuxXXXXXX`"
	fi >>"$product_log" 2>&1
}

selinux_getenforce()
{
	if [ "$1" = "--check" -a -n "$SELINUX_ENFORCE" ]; then
		return
	fi
	unset SELINUX_ENFORCE

	if ! ( command -v selinuxenabled >/dev/null 2>&1 && selinuxenabled ); then
		SELINUX_ENFORCE=Disabled
		return
	fi

	if awk '$3 == "selinuxfs"{exit(1)}' /proc/mounts; then
		selinux_get_mount_dir
		mount -t selinuxfs none "$SELINUX_MOUNT_DIR"
	fi

	if ! command -v getenforce >/dev/null 2>&1; then
		SELINUX_ENFORCE=Disabled
		return
	fi

	SELINUX_ENFORCE="`getenforce`"
	if test $? -ne 0; then
		SELINUX_ENFORCE=Disabled
		return
	fi
}

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

	setenforce "$SELINUX_ENFORCE"
}

selinux_relabel_dir()
{
	selinux_configuration_is_required || return 0

	if ! command -v restorecon >/dev/null 2>&1; then
		return
	fi

	local ret=0
	if ! restorecon -i -R "$@" >>"$product_log" 2>&1; then
		warn "Error while setting SELinux types. Command was: restorecon -i -R $*"
		ret=1
	fi

	[ -z "$do_repair" ] || return $ret
}

setsebool_ifdiffer()
{
	selinux_configuration_is_required || return 0

	if ! command -v setsebool >/dev/null 2>&1; then
		return
	fi

	if [ "$2" != "`getsebool $1 | cut -d' ' -f 3`" ]; then
		setsebool -P "$1" "$2"
	fi
}

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

set_selinux_params()
{
	selinux_module="$PRODUCT_ROOT_D/etc/plesk.pp"
}

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

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" ]
}

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

modsec_list_rulesets() {
	local dir="$1"
	local enabled_only="$2"
	local rules_conf_path="$3"
	if [ -z "$enabled_only" ]; then
		cd "$dir" || { echo >&2 "Unable to cd into '$dir'"; return 1; }
		ls | grep -v '\.backup$' | grep -E -v '\.saved-[0-9]+'
		cd - >/dev/null 2>&1
	else
		[ -r "$rules_conf_path" ] || return 0
		local dir_len=`echo "$dir//" | wc -L`
		cat "$rules_conf_path" | grep --only-matching "$dir/[^/]\+" | cut -c "${dir_len}-" | sort | uniq
	fi
}

modsec_is_ruleset_installed() {
	local releset_base_dir="$1"
	local ruleset="$2"
	[ -d "$releset_base_dir/$ruleset" ] && return 0

	return 1
}

modsec_list_configs() {
	local dir="$1"
	local enabled_only="$2"
	local rules_conf_path="$3"
	local ruleset="$4"

	if [ -z "$enabled_only" ]; then
		local ret=0
		cd "$dir" || { echo >&2 "Unable to cd into '$dir'"; return 1; }
		if [ -z "$ruleset" ]; then
			modsec_list_rulesets "$dir" "" "$rules_conf_path" | xargs -I{} -n 1 find {} -name \*.conf | sort
		else
			if ls "$ruleset" > /dev/null 2>&1; then
				find "$ruleset" -name \*.conf | sort
			else
				echo >&2 "No such ruleset: $ruleset"
				ret=1
			fi
		fi
		cd - >/dev/null 2>&1
		return $ret
	else
		[ -r "$rules_conf_path" ] || return 0
		local dir_ruleset="${dir}${ruleset:+/$ruleset}"
		local dir_len=`echo "$dir//" | wc -L`
		if [ "$enabled_only" = "raw" ]; then
			cat "$rules_conf_path" | grep -o "^[^#]*" | grep -o "$dir_ruleset/.*\.conf" | cut -c ${dir_len}-
		else
			for c in `cat "$rules_conf_path" | grep -o "^[^#]*" | grep -o "$dir_ruleset/.*\.conf"`; do
				echo $c | cut -c ${dir_len}-
				modsec_list_configs "$dir" "$enabled_only" "$c"
			done
		fi
	fi
}
### Copyright 1999-2026. WebPros International GmbH. All rights reserved.

# N.B.: not using 'reexec_with_clean_env "$@"' here due to MODSEC_VENDOR_* environment variables.

# constants
PN=`basename $0`
DEFAULT_RULESET="owasp_modsecurity_crs_4-plesk"

HTTPD_RULES_BASE_DIR="/etc/httpd/conf/modsecurity.d/rules"
HTTPD_RULES_CONFIG="/etc/httpd/conf/modsecurity.d/zz_rules.conf"
HTTPD_MODULES_CTL="/usr/local/psa//admin/sbin/httpd_modules_ctl"

NGINX_RULES_BASE_DIR="/etc/nginx/modsecurity.d/rules"
NGINX_RULES_CONFIG="/etc/nginx/modsecurity.d/rules.conf"
NGINX_MAIN_CONFIG="/etc/nginx/modsecurity.d/main.conf"
NGINX_PLESK_CONFIG="/etc/nginx/modsecurity.d/plesk.conf"
NGINX_MODULES_CTL="/usr/local/psa//admin/sbin/nginx_modules_ctl"

usage() {
	cat << EOT
Usage: modsecurity_ctl [COMMANDS] [OPTIONS]...

commands:
    -e, --enable                 enable plesk modsecurity backend
    -d, --disable                disable plesk modsecurity backend
    -s, --status                 show status of modsecurity backend

    -E, --enable-ruleset         enable specified rule sets
    -l, --list-rules             list separate rules (one rule for each .conf file)
    -L, --list-rulesets          list rule sets
    -t, --list-tags              list tags
    -i, --install                install new rule set
    -u, --uninstall              uninstall rule set
    -I, --is-ruleset-installed   check if a specific ruleset is installed
    --rollback                   rollback rule set on previous state
    --enable-only-rules          enable specified rules
    -D, --disable-all-rules      disable all rules

    -B, --rules-base-dir         show base directory for rule sets

    -h, --help                   show this help

options:
    -a, --archive-path <PATH>    path to archive contained rule set
    -r, --rule <CONF>            rule to be enabled by --enable-rules command (can be specified several times)
    -R, --ruleset <RULESET>          rule set for --install, --enable-ruleset and --uninstall commands
                                 possible values: crs, atomic, comodo, comodo_free, custom.
    --with-backup                backup rule set before installing new rule set
    --enabled                    list only enabled rules or rulesets (for --list-rules, --list-sets and --list-tags commands)
    --enabled-raw                display list of includes as-is (for --list-rules)

web-server flags:
    --apache                     evaluate command for apache web-server. Can't be used with --nginx flag.
                                 Apache web server used by default if no web server flag presented.
    --nginx                      evaluate command for nginx web-server. Can't be used with --apache flag.

examples:
    Install and enable custom rule set, backup previous custom set if exists:
    # modsecurity_ctl --install --with-backup --enable-ruleset --ruleset custom --archive-path <PATH>

    Install (download and unpack) comodo rule set, backup previous comodo set if exists:
    # env MODSEC_VENDOR_LOGIN=<login> MODSEC_VENDOR_PASS=<pass> modsecurity_ctl --install --with-backup --ruleset comodo

    Rollback custom rule set and enable previous custom configuration if exists:
    # modsecurity_ctl --rollback --ruleset custom
EOT
}

create_audit_log()
{
	# This is a temporary solution for support fail2ban modsecurity jail. For now fail2ban will fail to start if
	# modsec_audit.log does not exist. This file will be created by modsecurity himself only after some preparation.
	# But the BL part cannot know if modsecurity is ready and start fail2ban just in time. Waiting until the file
	# arrives in BL looks not a very good idea as well. So we just create a file on modsecurity enable process in this script.
	# In fact fail2ban will change this behaviour soon and will start even if a file is missed. But for now those changes are not ready.
	# Implementation process can be tracked on this github issue: https://github.com/fail2ban/fail2ban/issues/1379
	local modsec_log="/var/log/modsec_audit.log"
	if [ ! -e "$modsec_log" ]; then
		touch "$modsec_log"
		selinux_relabel_dir "$modsec_log"
	fi
}

# make plesk work with mod_security package from atomicorp:
# fix apache config files, restart apache if necessary
fix_atomic_modsec_layout()
{
	[ "$linux_distr" = "redhat" ] || return 0

	local atomic_conf_path="/etc/httpd/conf.d/00_mod_security.conf"
	local plesk_conf_path="/etc/httpd/conf.d/security2.conf"
	local require_apache_restart=""

	local count_config_lines=0

	if [ -e "$atomic_conf_path" ]; then
		count_config_lines=$(cat "$atomic_conf_path" | grep -E -v '^\s*$' | grep -E -v '^\s*#' | wc -l)
		if [ "$count_config_lines" -gt 0 ]; then
			# edit atomic config to prevent recreating on mod_security package upgrade
			printf "$AUTOGENERATED_CONFIGS" >  "$atomic_conf_path"
			require_apache_restart=yes
		fi
	fi

	if [ ! -e "$plesk_conf_path" ]; then
		cat - > "$plesk_conf_path" <<EOL
#LoadModule security2_module modules/mod_security2.so

<IfModule security2_module>
	SecDataDir /var/lib/mod_security
	IncludeOptional "/etc/httpd/conf/modsecurity.d/*.conf"
</IfModule>
EOL
		require_apache_restart=yes
	fi
	if [ "$require_apache_restart" = "yes" ] && ! pleskrc apache restart > /dev/null; then
		echo "Unable to restart apache." >&2
		return 1
	fi
}

modsecurity_apache_enable() {
	fix_atomic_modsec_layout || return 1
# enable apache modules mod_security and unique_id
	"$HTTPD_MODULES_CTL" --enable security2,unique_id
}

modsecurity_apache_disable() {
	fix_atomic_modsec_layout || return 1
# disable mod_security module
	"$HTTPD_MODULES_CTL" --disable security2
}

modsecurity_apache_status() {
	fix_atomic_modsec_layout || return 1
	local modules_list
	modules_list=`"$HTTPD_MODULES_CTL" --status --all-modules`
	modsecurity_loaded=`echo "$modules_list" | grep "security2 on"`
	unique_id_loaded=`echo "$modules_list" | grep "unique_id on"`
	if [ -n "$modsecurity_loaded" -a -n "$unique_id_loaded" ]; then
		echo "Enabled"
	else
		echo "Disabled"
	fi
}

modsecurity_nginx_enable() {
	local plesk_conf_path="/etc/nginx/conf.d/modsecurity.conf"

	if [ ! -e "$NGINX_RULES_CONFIG" ]; then
		printf "$AUTOGENERATED_CONFIGS" > $NGINX_RULES_CONFIG
	fi

	if [ ! -e "$NGINX_PLESK_CONFIG" ]; then
		printf "$AUTOGENERATED_CONFIGS" > $NGINX_PLESK_CONFIG
	fi

	if [ ! -e "$NGINX_MAIN_CONFIG" ]; then
		printf "$AUTOGENERATED_CONFIGS" > $NGINX_MAIN_CONFIG
		printf "Include $NGINX_PLESK_CONFIG\n" >> $NGINX_MAIN_CONFIG
		printf "Include $NGINX_RULES_CONFIG\n" >> $NGINX_MAIN_CONFIG
	fi

	if [ ! -e "$plesk_conf_path" ]; then
		printf "$AUTOGENERATED_CONFIGS" > "$plesk_conf_path"
		printf "modsecurity on;\nmodsecurity_rules_file $NGINX_MAIN_CONFIG;\n" >> "$plesk_conf_path"
	fi

	setsebool_ifdiffer ngx_can_access_any_shared_memory on

	"$NGINX_MODULES_CTL" --no-restart --enable modsecurity
}

modsecurity_nginx_disable() {
	local plesk_conf_path="/etc/nginx/conf.d/modsecurity.conf"
	rm $plesk_conf_path

	setsebool_ifdiffer ngx_can_access_any_shared_memory off

	# Don't make real disabling of modsecurity module for now. This needed
	# because some virtual hosts configuration can store modsecurity directives
	# If modsecurity module not going to be loaded in nginx, configuration check
	# is going to be failed in this case.
	#"$NGINX_MODULES_CTL" --no-restart --disable modsecurity
}

modsecurity_nginx_status() {
	# Since we remove real disabling of modsecurity, we need to check status
	# of module with checking of file /etc/nginx/conf.d/modsecurity.conf exsistence
	#
	# local modsecurity_loaded
	# modsecurity_loaded=`"$NGINX_MODULES_CTL" --status | grep "modsecurity on"`
	
	# if [ -n "$modsecurity_loaded" ]; then
	# 	echo "Enabled"
	# else
	# 	echo "Disabled"
	# fi
	local plesk_conf_path="/etc/nginx/conf.d/modsecurity.conf"

	if [ ! -e "$plesk_conf_path" ]; then
		echo "Disabled"
	else
		echo "Enabled"
	fi

}

unpack_zip_archive() {
	local archive="$1"
	local target_dir="$2"
	unzip -q -j -d "$target_dir" "$archive"
}

unpack_tarxx_archive() {
	local archive="$1"
	local target_dir="$2"
	tar -C "$target_dir" -x -f "$archive"
}

install_config() {
	local config="$1"
	local target_dir="$2"
	cp -f "$config" "$target_dir/"
}

install_archive() {
	local archive="$1"
	local base_dir="$2"
	local target_name="$3"
	local type="$4"

	if [ -z "$type" ]; then
# detect archive type
		if expr match "$archive" '.*\.zip' >/dev/null ; then
			type="zip"
		elif expr match "$archive" '.*\.tar\.gz' >/dev/null ; then
			type="tar.gz"
		elif expr match "$archive" '.*\.tgz' >/dev/null ; then
			type="tgz"
		elif expr match "$archive" '.*\.tar\.bz2' >/dev/null ; then
			type="tar.bz2"
		elif expr match "$archive" '.*\.conf' >/dev/null ; then
			type="conf"
		else
			echo >&2 "Unknown archive type: '$archive'"
			return 1
		fi
	fi

	if [ -z "$target_name" ]; then
# get filename
		filename=`basename "$archive" ".$type"`
# create target dir
		target_dir=`mktemp -d "$base_dir/$filename.XXXX"`
	else
		target_dir="$base_dir/$target_name"
		rm -rf "$target_dir"
		mkdir -p "$target_dir"
	fi
# extract
	case "$type" in
		zip) unpack_zip_archive "$archive" "$target_dir";;
		tar.gz|tar.bz2|tgz) unpack_tarxx_archive "$archive" "$target_dir";;
		conf) install_config "$archive" "$target_dir";;
		*) echo >&2 "Unknown archive type: '$archive'"; exit 1;;
	esac
}

uninstall_ruleset() {
	local ruleset="$1"
	local base_dir="$2"
	rm -rf "$base_dir/$ruleset"
}

enable_ruleset() {
	local rules_conf_path="$1"
	local base_dir="$2"
	local ruleset="$3"
	enable_only_configs "$rules_conf_path" "$base_dir" "$ruleset/*.conf"
}

enable_only_configs() {
	local rules_conf_path="$1"
	local base_dir="$2"
	local configs="$3"

	printf "$AUTOGENERATED_CONFIGS\n" > "$rules_conf_path"
	local old_ifs="$IFS"
	IFS="
"
	for conf in "$configs"; do
		local conf_trimmed=`echo "$conf" | sed -e 's/\s*$//g' -e 's/^\s*//g'`
		[ -z "$conf_trimmed" ] || echo "Include \"$base_dir/$conf_trimmed\"" >> "$rules_conf_path"
	done
}

process_init_config_template()
{
	local dir="$1"
	local init_conf="$dir/plesk_init.conf"
	if [ -r "${init_conf}.tpl" ]; then
		printf "$AUTOGENERATED_CONFIGS\n" > "${init_conf}"
		sed -e "s#@ruleset_base_dir@#$dir#g" < "${init_conf}.tpl" >> "${init_conf}"
	fi
}

list_tags() {
	local dir="$1"
	local enabled_only="$2"
	local rules_conf_path="$3"
	cd "$dir" || { echo >&2 "Unable to cd into '$dir'"; return 1; }
	grep -E -o "tag:'([^']*)'" `modsec_list_configs "$dir" "$enabled_only" "$rules_conf_path"` | cut -d"'" -f2 | sort | uniq
	cd - >/dev/null 2>&1
}

backup_rules_conf() {
	local rules_conf_path="$1"
	local rules_conf_backup="${rules_conf_path}.backup"
	[ ! -e "$rules_conf_path" ] || cp -f "$rules_conf_path" "$rules_conf_backup"
}

rollback_rules_conf() {
	local rules_conf_path="$1"
	local rules_conf_backup="${rules_conf_path}.backup"
	[ ! -e "$rules_conf_backup" ] || cp -f "$rules_conf_backup" "$rules_conf_path"
}

backup_ruleset() {
	local dir="$1"
	local backup_dir="${dir}.backup"
	if [ ! -d "$dir" ]; then
		echo >&2 "Unable to backup: directory doesn't exist: '$dir'"
		return 1
	fi
	if [ -e "$backup_dir" ]; then
		rm -rf "$backup_dir"
	fi
	cp -r "$dir" "$backup_dir"
}

rollback_ruleset() {
	local base_dir="$1"
	local ruleset="$2"
	local rules_conf_path="$3"
	rm -f "$rules_conf_path" # disable ruleset
	local ruleset_dir="$base_dir/$ruleset"
	local backup_dir="${ruleset_dir}.backup"
	[ ! -d "${ruleset_dir}.new" ] || rm -rf "${ruleset_dir}.new"
	[ ! -d "$ruleset_dir" ] || mv "$ruleset_dir" "${ruleset_dir}.new"
	[ ! -d "$backup_dir" ] || mv "$backup_dir" "$ruleset_dir"
}

#parse options
TEMP=`getopt -o edsElLtiuIa:r:R:BDh --long \
	enable,disable,status,enable-ruleset,list-rules,list-rulesets,list-tags,install,uninstall,is-ruleset-installed,enable-only-rules,rules-base-dir,archive-path:,rule:,ruleset:,with-backup,rollback,enabled,enabled-raw,disable-all-rules,apache,nginx,help \
     -n "$PN" -- "$@"`

if [ $? != 0 ] ; then echo "Internal error!" >&2 ; exit 1 ; fi
eval set -- "$TEMP"

opt_enable=0
opt_disable=0
opt_status=0
opt_enable_ruleset=0
opt_list_rules=0
opt_list_sets=0
opt_list_tags=0
opt_install=0
opt_uninstall=0
opt_is_installed=0
opt_enable_only_rules=0
opt_disable_all_rules=0
opt_rollback=0
opt_archive_path=
opt_ruleset=
opt_rules=
opt_with_backup=0
opt_rules_base_dir=0
opt_server="apache"


while true ; do
	case "$1" in
		-e|--enable) opt_enable=1; shift;;
		-d|--disable) opt_disable=1; shift;;
		-s|--status) opt_status=1; shift;;
		-E|--enable-ruleset) opt_enable_ruleset=1; shift;;
		-l|--list-rules) opt_list_rules=1; shift;;
		-L|--list-rulesets) opt_list_sets=1; shift;;
		-t|--list-tags) opt_list_tags=1; shift;;
		-i|--install) opt_install=1; shift;;
		-u|--uninstall) opt_uninstall=1; shift;;
		-I|--is-ruleset-installed) opt_is_installed=1; shift;;
		--rollback) opt_rollback=1; shift;;
		--enable-only-rules) opt_enable_only_rules=1; shift;;
		-D|--disable-all-rules) opt_disable_all_rules=1; shift;;
		-B|--rules-base-dir) opt_rules_base_dir=1; shift;;
		-a|--archive-path) opt_archive_path="$2"; shift; shift;;
		-r|--rule)
			if [ -z "$opt_rules" ]; then
				opt_rules="$2"
			else
				opt_rules="$opt_rules
$2"
				opt_rules=`echo "$opt_rules" | sed 's/^\s*//g'`
				shift 2
			fi;;
		-R|--ruleset) opt_ruleset="$2"; [ ! "$opt_ruleset" = "crs" ] || opt_ruleset="$DEFAULT_RULESET"; shift; shift;;
		--with-backup) opt_with_backup=1; shift;;
		--enabled) opt_enabled="enabled_only"; shift;;
		--enabled-raw) opt_enabled="raw"; shift;;
		--nginx) opt_server="nginx"; shift;;
		--apache) opt_server="apache"; shift;;
		-h|--help) usage; exit 0;;
		--) shift ; break ;;
		*) echo "Internal error!" ; exit 1 ;;
	esac
done

# to set $product_log:
log_transaction_start "$PN" "" "$PN.log"
# to set $linux_distr and $AUTOGENERATED_CONFIGS:
product_default_conf
initial_conf
set_common_params
read_conf
# to set $apache_service for pleskrc():
set_apache_params

RULES_CONFIG=""
RULES_BASE_DIR=""
case "$opt_server" in
	"nginx")
		RULES_CONFIG=$NGINX_RULES_CONFIG
		RULES_BASE_DIR=$NGINX_RULES_BASE_DIR
		;;
	"apache")
		RULES_CONFIG=$HTTPD_RULES_CONFIG
		RULES_BASE_DIR=$HTTPD_RULES_BASE_DIR
		;;
	*) echo "Unspecified server! Use --nginx or --apache to specify server." ; exit 1 ;;
esac

if [ "$opt_enable" = "1" ]; then
	create_audit_log
	case "$opt_server" in
		"nginx") modsecurity_nginx_enable ;;
		"apache") modsecurity_apache_enable ;;
		*) echo "Unspecified server! Use --nginx or --apache to specify server." ; exit 1 ;;
	esac
elif [ "$opt_disable" = "1" ]; then
	case "$opt_server" in
		"nginx") modsecurity_nginx_disable ;;
		"apache") modsecurity_apache_disable ;;
		*) echo "Unspecified server! Use --nginx or --apache to specify server." ; exit 1 ;;
	esac
elif [ "$opt_status" = "1" ]; then
	case "$opt_server" in
		"nginx") modsecurity_nginx_status ;;
		"apache") modsecurity_apache_status ;;
		*) echo "Unspecified server! Use --nginx or --apache to specify server." ; exit 1 ;;
	esac
	exit $?
elif [ "$opt_install" = "1" ]; then
	if [ -z "$opt_ruleset" ]; then
		echo >&2 "--ruleset is not specified"
		exit 1
	fi

	rm -rf "$RULES_BASE_DIR/${opt_ruleset}.new"

	if [ "$opt_with_backup" = "1" -a -d "$RULES_BASE_DIR/$opt_ruleset" ]; then
		backup_ruleset "$RULES_BASE_DIR/$opt_ruleset" || exit 1
	fi

	if [ -f "$RULES_CONFIG" ]; then
		backup_rules_conf "$RULES_CONFIG"
		rm -f "$RULES_CONFIG"
	fi

	archive_type=
	if [ "$opt_ruleset" = "comodo" -o "$opt_ruleset" = "atomic" -o "$opt_ruleset" = "tortix" -o "$opt_ruleset" = "comodo_free" ]; then
		archive_type="tar.gz"
		ruleset_proc="$opt_ruleset"
		if [ "$opt_ruleset" = "comodo_free" ]; then
			[ "$opt_server" = "nginx" ] || archive_type="zip"
			ruleset_proc="comodo"
		fi
		ruleset_archive_path="$RULES_BASE_DIR/${opt_ruleset}_rule_set.$archive_type"
		get_ruleset_output=$("$PLESK_LIBEXEC_DIR/modsecurity_get_${ruleset_proc}_ruleset" \
			"$ruleset_archive_path" \
			"$RULES_BASE_DIR/$opt_ruleset" \
			"$opt_server" 2>>"$product_log" \
				| tee -a "$product_log"; exit ${PIPESTATUS[0]})
		if [ "$?" -ne 0 ]; then
			if [ -n "$get_ruleset_output" ]; then
				echo "$get_ruleset_output" >&2
			else
				echo "Failed to download $opt_ruleset rule set." >&2
			fi
			if ! pleskrc apache status >/dev/null 2>&1; then
				# try to resurrect apache if it was unsuccessfully restarted by get_?_ruleset-script.
				# (apache configs should be reverted at the moment)
				pleskrc apache restart
			fi
			exit 1
		fi
		opt_archive_path="$ruleset_archive_path"
	fi

	[ -n "$opt_archive_path" ] || { echo >&2 "--archive-path is not specified"; exit 1; }
	[ ! -s "$opt_archive_path" ] || install_archive "$opt_archive_path" "$RULES_BASE_DIR" "$opt_ruleset" "$archive_type"

	process_init_config_template "$RULES_BASE_DIR/$opt_ruleset"

	if [ "$opt_enable_ruleset" = "1" ]; then
		enable_ruleset "$RULES_CONFIG" "$RULES_BASE_DIR" "$opt_ruleset"
	fi
elif [ "$opt_rollback" = "1" ]; then
	if [ -z "$opt_ruleset" ]; then
		echo >&2 "--ruleset is not specified"
		exit 1
	fi
	rollback_ruleset "$RULES_BASE_DIR" "$opt_ruleset" "$RULES_CONFIG"
	rollback_rules_conf "$RULES_CONFIG"
elif [ "$opt_enable_ruleset" = "1" ]; then
	if [ -z "$opt_ruleset" ]; then
		echo >&2 "--ruleset is not specified"
		exit 1
	fi
	backup_rules_conf "$RULES_CONFIG"
	enable_ruleset "$RULES_CONFIG" "$RULES_BASE_DIR" "$opt_ruleset"
elif [ "$opt_uninstall" = "1" ]; then
	if [ -z "$opt_ruleset" ]; then
		echo >&2 "--ruleset is not specified"
		exit 1
	fi
	uninstall_ruleset "$opt_ruleset" "$RULES_BASE_DIR"
elif [ "$opt_is_installed" = "1" ]; then
	if [ -z "$opt_ruleset" ]; then
		echo >&2 "--ruleset is not specified"
		exit 1
	fi

	if modsec_is_ruleset_installed "$RULES_BASE_DIR" "$opt_ruleset" ; then
		echo "Installed"
	else
		echo "Not installed"
	fi

elif [ "$opt_enable_only_rules" = "1" ]; then
	backup_rules_conf "$RULES_CONFIG"
	enable_only_configs "$RULES_CONFIG" "$RULES_BASE_DIR" "$opt_rules"
elif [ "$opt_disable_all_rules" = "1" ]; then
	backup_rules_conf "$RULES_CONFIG"
	enable_only_configs "$RULES_CONFIG" "$RULES_BASE_DIR"
elif [ "$opt_list_rules" = "1" ]; then
	modsec_list_configs "$RULES_BASE_DIR" "$opt_enabled" "$RULES_CONFIG" "$opt_ruleset"
elif [ "$opt_list_sets" = "1" ]; then
	modsec_list_rulesets "$RULES_BASE_DIR" "$opt_enabled" "$RULES_CONFIG"
elif [ "$opt_list_tags" = "1" ]; then
	list_tags "$RULES_BASE_DIR" "$opt_enabled" "$RULES_CONFIG"
elif [ "$opt_rules_base_dir" = "1" ]; then
	echo "$RULES_BASE_DIR"
else
	usage
fi

# vim: ft=sh
