#!/bin/bash
### Copyright 1999-2017. Parallels IP Holdings GmbH. All Rights Reserved.
#

#
# Plesk script
#


### Copyright 1999-2017. Parallels IP Holdings GmbH. All Rights Reserved.

### Copyright 1999-2017. Parallels IP Holdings GmbH. All Rights Reserved.
set_apache_params()
{
	apache_user="apache"
	apache_UID=80
	apache_group="apache"
	apache_GID=80

	user_apxs="/usr/sbin/apxs"

	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_conf2="$HTTPD_CONF_D/httpd2.conf"
	apache_httpd_conf_in="$HTTPD_CONF_D/httpd.conf.in"

	apache_httpd_include="$HTTPD_INCLUDE_D/zz010_psa_httpd.conf"

	APACHE_CERT="$HTTPD_CONF_D/httpd.pem"
	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=/usr/sbin
	suexec_file=suexec

	rpm_httpd_bin=/usr/sbin/httpd
}

module_exists()
{
	local dir
	[ -n "$1" ] || return 1
	test -n "$2" && test -e "${apache_modules_d}/$2" && return
	test -e "${apache_modules_d}/mod_$1.so" && return
	if [ -n "${additional_apache_modules_d}" ]; then
		for dir in $additional_apache_modules_d; do 
			if [ -f "${dir}/mod_$1.so"  ] ; then return ; fi
			if [ -n "$2" -a -f "${dir}/$2" ] ; then return ; fi
		done
	fi
	return 1
}

# FIXME: This function is working for RedHat based distros only
# fix httpd_d variable to adopt one for other OSes
find_module_conf()
{
	local module_name="$1"
	local httpd_d="${HTTPD_CONF_D%/*}"
	local config
# On CentOS7+ modules config is changed
	local fallback_modules_config="${HTTPD_CONF_D%/*}/conf.modules.d/00-base.conf"

	for dir in conf conf.d conf.modules.d; do
		config=`grep -rl "LoadModule[[:space:]]${module_name}_module[[:space:]]" $httpd_d/$dir/*.conf 2>/dev/null`
		[ -n "$config" ] || continue
		echo "$config"
		return
	done
	echo "$fallback_modules_config"
}

# Run before it
#        read_conf
#        # set_common_params
#        set_apache_params
add_apache_module()
{
	local module_name="$1"
	local module_soname="$2" # optional
	local config="$3" # optional

	if ! module_exists $module_name "$module_soname"; then
		# TODO : fix message error
		p_echo "Shared object mod_${module_name}.so not found in ${apache_modules_d}...skipped."
		return
	fi


# On CentOS7+ modules config is changed
		local fallback_modules_config="${HTTPD_CONF_D%/*}/conf.modules.d/00-base.conf"
		if [ -z "$config" ]; then
			config=`find_module_conf $module_name`
		fi

		[ -n "$module_soname" ] || module_soname="mod_$module_name.so"
		perl -snle 'BEGIN{ $r = qr/LoadModule.*${mod}_module.*${soname}/ } s/^\s*#.*?($r)/$1/; $found=1 if /$r/; print }
			{ print "LoadModule ${mod}_module ${mdir}/${soname}" unless $found' 			-- -mod="${module_name}" -mdir="${apache_modules_d}" -soname="$module_soname" < "${config}" > "${config}.new" && 		mv -f "${config}.new" "${config}"

}

# Run before it
#        read_conf
#        # set_common_params
#        set_apache_params
remove_apache_module()
{
	local module_name="$1"
	local module_soname="$2" # optional
	local config="$3" # optional

		if [ -z "$config" ] ; then
			config=`find_module_conf $module_name`
		fi

		# Is shared library name specified?
		[ -n "$module_soname" ] || module_soname="mod_$module_name.so"

		perl -sple 's/^\s*(LoadModule.*${mod}_module.*${soname})/# $1/' 			-- -mod="${module_name}" -mdir="${apache_modules_d}" -soname="$module_soname" < "${config}" > "${config}.new" && 		mv -f "${config}.new" "${config}"

}

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

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

# echo message to product log without new line, unless debug
pnnl_echo()
{
    if [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" -o -z "$product_log" ] ; then
        echo -n "$*" >&2
    else
        echo -n "$*" >> "$product_log" 2>&1
    fi
}

die()
{
	PACKAGE_SCRIPT_FAILED="$*"

	report_problem \
		"ERROR while trying to $*" \
		"Check the error reason(see log file: ${product_log}), fix and try again"

	selinux_close

	exit 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()
{
	[ -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"
		echo "$problem_message" >> "$product_problems_log" 2>&1
	done
	p_echo

	product_log_tail | send_error_report_with_input "Problem: $@"

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

	problems_occured=1
}

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

suc()
{
	p_echo "done"
}

# do not call it w/o input! Use send_error_report in these cases.
send_error_report_with_input()
{
	get_product_versions
	{
		echo "$@"
		echo ""
		if [ -n "$error_report_context" ]; then
			echo "Context: $error_report_context"
			echo ""
		fi
		if [ -n "$RP_LOADED_PATCHES" ]; then
			echo "Loaded runtime patches: $RP_LOADED_PATCHES"
			echo ""
		fi
		cat -
	} | $PRODUCT_ROOT_D/admin/bin/send-error-report --version "$product_this_version" install >/dev/null 2>&1
}
### Copyright 1999-2017. Parallels IP Holdings 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.

	export LANG=C LC_MESSAGES=C LC_ALL=C
	export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
	umask 022

	[ -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
	}
	'
}

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

call_optional_function()
{
	export LANG=C LC_MESSAGES=C LC_ALL=C
	local type_output="`type \"$1\" 2>/dev/null | head -n 1`"
	case "$type_output" in
		*function)
			"$@"
			;;
		*)
			return 0
			;;
	esac
}
### Copyright 1999-2017. Parallels IP Holdings 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
		echo "plesk_17.5.3${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
}

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

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

create_product_log_symlink()
{
	local logfile="$1"
	local prevdir="$2"

	local prevlog="$prevdir/`basename $logfile`"
	[ -e "$prevlog" ] || ln -sf "$logfile" "$prevlog"
}

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

	# create compat symlinks if logs are written to default localtions
	if [ -z "$custom_log" -a -z "$CUSTOM_LOG_NAME" ]; then
		create_product_log_symlink "$product_log" "/tmp"
		[ ! -z "$custom_problems_log" ] || create_product_log_symlink "$product_problems_log" "/tmp"
	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"
}

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

	# remove symlink to problems log if the log was removed
	local linkpath="/tmp/`basename $product_problems_log`"
	if [ -L "$linkpath" -a ! -e "$linkpath" ]; then
		rm -f "$linkpath"
	fi

	is_function profiler_stop && profiler_stop || :
}
### Copyright 1999-2017. Parallels IP Holdings 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 "$@"
}

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 [ "X$do_upgrade" = "X1" ]; then
			p_echo "Unable to find product configuration file: $prod_conf_t. Default values will be used."
			return 1
		fi
	fi
	return 0
}

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

	setenforce "$SELINUX_ENFORCE"
}
### Copyright 1999-2017. Parallels IP Holdings 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=C
	export PATH LANG
	unset GREP_OPTIONS
	umask 022
	ulimit -n 65535 2>/dev/null

	K_HUP="/bin/kill -HUP"
	K_KILL="/bin/kill -KILL"
	K_TERM="/bin/kill -TERM"
	K_USR2="/bin/kill -USR2"
	K_TEST="/bin/kill -0"

	users_created=""
	groups_created=""

	certificate_file="$PRODUCT_ETC_D/httpsd.pem"
	services="/etc/services"
	mtab="/etc/mtab"
	get_hostname="hostname"
	get_domainname="domainname"

	#default parameters
	tar="tar"
	crontab="/usr/bin/crontab"

	cp_preserve="cp -p"
	SYSTEM_RC_D=/etc/init.d
	PLESK_LIBEXEC_DIR="/usr/lib64/plesk-9.0"
	PLESK_DB_DIR="/var/lib/plesk"
	POSTFIX_LIBEXEC_DIR="/usr/libexec/postfix"
	PRODUCT_BOOTSTRAPPER_DIR="/usr/local/psa/bootstrapper/pp17.5.3-bootstrapper"
	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 PARALLELS PLESK PANEL.\n"
	PRODUCT_LOGS_D="/var/log/plesk"

	set_common_params_linux 

	rp_patch_runtime
}

set_common_params_linux()
{
	get_hostname="hostname -f"
	fstab="/etc/fstab"
	cp_preserve="cp --preserve=all --remove-destination"
	machine="linux"
	sendmail="/usr/sbin/sendmail"
	ps="ps axw"
	ps_long="ps axuw"
	false_shell="/bin/false"
	dummy_home="/"
	compress="gzip -9 -c"
	uncompress="gunzip -c"
	uudecode="uudecode -o /dev/stdout"
	ifconfig="/sbin/ifconfig -a"
	inet_str="inet addr"

	useradd_options="-r"
	if [ -f /etc/SuSE-release ]; then
		linux_distr="suse"
	elif [ -f /etc/debian_version ]; then
		linux_distr="debian"
		get_domainname="dnsdomainname"
	else
		linux_distr="redhat"
	fi

	sndml_ini="/etc/init.d/sendmail"
	mail_local="/usr/libexec/mail.local"
	if [ -x /sbin/nologin ]; then
		dummy_shell="/sbin/nologin"
	else
		dummy_shell="/bin/false"
	fi
	bash_shell="/bin/bash"
	rbash_shell="/bin/rbash"
	uudecode_full="/usr/bin/uudecode"
	# FIXME: remove or keep? can't find use of this variable
	# named_osrelease=`perl -F"/[.-]/" -n -a  -e 'printf "%02u%02u%02u\n", $F[0],$F[1],$F[2]' /proc/sys/kernel/osrelease`

	return 0
}

get_product_versions()
{
	local prod_root_d="/usr/local/psa"
	
	product_name="psa"
	product_this_version="17.5.3"
	product_this_version_tag=""
	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
}

### Copyright 1999-2017. Parallels IP Holdings 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" PIPE EXIT
		trap "transaction_rollback" HUP INT QUIT TERM
	else
		trap "transaction_rollback" HUP PIPE INT QUIT TERM EXIT
	fi
}

transaction_rollback()
{
	[ -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()
{
	[ -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_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-2017. Parallels IP Holdings GmbH. All Rights Reserved.
# vim:syntax=sh

set_nginx_params()
{
	nginx_service=nginx
	nginx_rc_config="/etc/sysconfig/nginx"
	nginx_user="nginx"
}

nginx_is_rc_enabled()
{
	grep -q '^\s*NGINX_ENABLED=\s*"\?yes"\?\s*\(#.*\)\?$' "$nginx_rc_config" >/dev/null 2>&1
}

# vim:ft=sh:
### Copyright 1999-2017. Parallels IP Holdings GmbH. All Rights Reserved.

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

Options:
    -s, --status
    -a, --all-modules                   Do not filter out required modules in --status command
    -e, --enable <module1,module2...>   Turn on specified modules
    -d, --disable <module1,module2...>  Turn off specified modules
    -M, --status-mpm                    List available/enabled mpm's
    -m, --set-mpm <mpm>                 Switch mpm
    -R, --no-restart                    Do not restart apache

    -h, --help                          Display this help and exit
EOT
	return 1
}

short_module_name()
{
	local fullname="$1"
	local short_mod_name
	short_mod_name=`expr match "$fullname" 'mod_\(.*\)$'`
	if [ "$?" != "0"  ] ; then
		short_mod_name=`expr match "$fullname" 'lib\(.*\)$'`
		[ "$?" = "0" ] || return 1
	fi
	echo $short_mod_name
}

is_module_enabled()
{
	local short_mod_name="$1"
	expr match "$short_mod_name" 'php7.*' 2>&1 > /dev/null
	[ "$?" = "0" ] && short_mod_name="php7"
	enabled_modules_list | egrep -q "\<${short_mod_name}(_module|)\>" 2>/dev/null
	return $?
}

is_module_static()
{
	local short_mod_name="$1"
	static_modules_list | egrep -q "\<(mod_|)${short_mod_name}\>" 2>/dev/null
	return $?
}

enable_mod()
{
	local modules
	local ret
	local IFS
	local module_soname
	local module_config
	modules=$1
	ret=0
	IFS=,
	for module in $modules ; do
		if is_module_static "$module"; then
			# Compiled in modules are always enabled
			continue
		fi
		module_soname=""
		module_config=""
		if expr match "$module" 'php.*' 2>&1 > /dev/null; then
			module_soname="lib$module.so"
			module_config="/etc/httpd/conf.modules.d/10-php.conf"
		fi
		if ! add_apache_module "$module" "$module_soname" "$module_config" ; then
			ret=1
		fi
	done
	return $ret
}

disable_mod()
{
	local modules
	local ret
	local IFS
	local module_soname
	local module_config
	modules=$1
	ret=0
	IFS=,
	for module in $modules ; do
		if is_module_static "$module"; then
			p_echo "ERROR: Module $module is compiled in (static) and cannot be disabled!"
			ret=1
			continue
		fi
		module_soname=""
		module_config=""
		if expr match "$module" 'php.*' 2>&1 > /dev/null; then
			module_soname="lib$module.so"
			module_config="/etc/httpd/conf.modules.d/10-php.conf"
		fi
		if ! remove_apache_module "$module" "$module_soname" "$module_config"  2>> $product_log ; then
			ret=1
		fi
	done
	return $ret
}

status_mods()
{
	local show_all_modules="$1"
	local all_mod_list
	local ena_mod_list
	local short_mod_name
	local required_mods
	local required_mods_re
	local static_mod_list
	local mod

	all_mod_list=`all_modules_list`
	required_mods=`required_modules_list`
	if [ "$show_all_modules" = "1" ]; then
		static_mod_list=`static_modules_list`
		all_mod_list="$all_mod_list $static_mod_list"
		required_mods="$required_mods $static_mod_list"
	fi
	if [ -n "$required_mods" ] ; then
		required_mods_re="`echo "$required_mods" | tr '\n' ' ' | sed -s 's/\s\+/\\\|/g'`\$"
	fi

	for mod in $all_mod_list; do
		short_mod_name=`short_module_name $mod`
		if [ "$?" != "0"  ] ; then continue; fi

		# use filter for required modules
		if [ "$show_all_modules" = "1" -o -z "$required_mods_re" ] || ! expr match "$short_mod_name" "$required_mods_re" 2>&1 > /dev/null ; then
			if is_module_static "$short_mod_name"; then
				echo "$short_mod_name static"
			elif is_module_enabled "$short_mod_name"; then
				echo "$short_mod_name on"
			else
				echo "$short_mod_name off"
			fi
		fi
	done
	return 0
}

status_mpm()
{
	local output
	local ret
	output=`status_mods 1`
	ret="$?"
	[ "$ret" = "0" ] || return "$ret"
	echo "$output" | grep '^mpm_'
}

switch_mpm()
{
	local to="$1"
	local mpms IFS
	mpms="`status_mpm`"
	IFS="
"
	for ms in $mpms; do
		local mod=`echo $ms | cut -d' ' -f 1`
		if [ "$mod" != "$to" ]; then
			disable_mod "$mod"
		fi
	done
	enable_mod "$to"
	if [ "$to" = "mpm_event" ]; then
		disable_mod "php5"
		if expr match "$linux_distr" "redhat" >/dev/null; then
			local php_conf="/etc/httpd/conf.d/php.conf"
# surround php_value pragmas with <IfModule php>:
			perl -ple 'BEGIN { $inside = 0; $opened = 0; }
				if (/<IfModule\s+mod_php5.c>/i) {
					$inside = 1;
				} elsif (/<\/IfModule>/i) {
					$inside = 0;
				} elsif (/^\s*php_value/ and !$inside) {
					$opened = 1;
					$inside = 1;
					print "<IfModule mod_php5.c>";
				} elsif (!/^\s*php_value/ and $opened) {
					print "</IfModule>";
				}
				END { print "</IfModule>" if $opened }' 				"$php_conf" > "$php_conf.new" && mv -f "$php_conf.new" "$php_conf"
		fi
	fi
}

static_modules_list()
{
	if [ -z "$VAR_STATIC_MODULES_LIST_EVALUATED" ]; then
		local static_mod_list
		static_mod_list="`/usr/sbin/apachectl -l | awk '$1 ~ /\.c$/ {print $1}' | cut -d. -f1 2>> "$product_log"`"
		VAR_STATIC_MODULES_LIST="`echo "$static_mod_list" | egrep -v '^(core|http_core|prefork)$'`"
		VAR_STATIC_MODULES_LIST_EVALUATED=1
	fi
	echo "$VAR_STATIC_MODULES_LIST"
}

required_modules_list()
{
	echo "env auth_digest authn_file authz_host authz_user actions alias  proxy.plesk proxy_fcgi.plesk autoindex dav dir log_config mime negotiation setenvif ssl"

	set_nginx_params
	nginx_is_rc_enabled && echo "rpaf aclr"

	# mod_security and unique_id
	local mod_security_version=`$PRODUCT_ROOT_D/admin/sbin/packagemng --list | awk -F: '$1 ~ /^modsecurity$/ {print $2}'`
	if [ -n "$mod_security_version" ]; then
		echo "security2"
		if is_module_enabled "security2"; then
			echo "unique_id"
		fi
	fi
}

all_modules_list()
{
	ls "$apache_modules_d" | grep '\.so$' | sed 's/\.so//'
}

enabled_modules_list_aux()
{
	local ena_mod_list
	local apachectl_err
	if [ "$linux_distr" = "redhat" -o "$linux_distr" = "debian" -o "$linux_distr" = "ubuntu" ]; then
		# Note: this is actually required only for RedHat systems and old Debian-based (Debian 5, Ubuntu 8.04)
		ena_mod_list=`/usr/sbin/apachectl -M 2>&1`
		apachectl_err=$?
	else
		ena_mod_list=`/usr/sbin/apachectl -M 2>> $product_log`
		apachectl_err=$?
	fi

	if  [ "$apachectl_err" = "0" ] ; then
		echo "$ena_mod_list" | awk '$1 ~ /module/ {print $1}'
		return 0
	fi
	case "$linux_distr" in
		debian)
			ena_mod_list=`ls /etc/apache2/mods-enabled/*.load | xargs -n 1 basename | sed 's/\.load//' 2>> $product_log`
			ena_mod_list_ret=$?
			if [ "$ena_mod_list_ret" != "0" ] ; then
				echo "$ena_mod_list_ret" >> $product_log
				return 1
			fi
			echo $ena_mod_list
			return 0
		;;
		suse*)
			(. /etc/sysconfig/apache2;echo ${APACHE_MODULES}) 2>/dev/null;
			return 0;
		;;
		redhat*)
			find /etc/httpd/conf/ /etc/httpd/conf.d/ -maxdepth 1 -type f -exec grep -h LoadModule {} \; | 				perl -nale 'unless(m/^\s*#/) { print substr($F[1], 0, -7) }'
			return $?
		;;
	esac

	return 1
}

enabled_modules_list()
{
	if [ -z "$VAR_ENABLED_MODULES_LIST_EVALUATED" ]; then
		VAR_ENABLED_MODULES_LIST=`enabled_modules_list_aux`
		VAR_ENABLED_MODULES_LIST_EVALUATED=1
	fi
	echo "$VAR_ENABLED_MODULES_LIST"
}

## begin script

reexec_with_clean_env "$@"

if [ $# -eq 0 ] ; then
    usage
    exit 1
fi

log_transaction_start "httpd_modules_ctl${*:+ $*}" "" "httpd_modules_ctl.XXXXXX"
read_conf
set_common_params
set_apache_params
# Initialize modules lists (in the outer shell)
enabled_modules_list >/dev/null
static_modules_list >/dev/null

TEMP=`getopt -o e:d:saMm:Rh 	--long enable:,disable:,status,all-modules,status-mpm,set-mpm:,no-restart,help -n "$0" -- "$@"`
if [ $? != 0 ] ; then
	echo "Terminating..." >&2
	rm -f $product_log
	exit 1
fi
eval set -- "$TEMP"

ret=0
to_restart=0
opt_status=0
opt_status_mpm=0
opt_all_modules=0
opt_no_restart=0
while true ; do
	case "$1" in
		-e|--enable)
			enable_mod $2
			ret=`expr $ret \| $?`
			to_restart=1
			shift 2
		;;
		-d|--disable)
			disable_mod $2
			ret=`expr $ret \| $?`
			to_restart=1
			shift 2
		;;
		-m|--set-mpm)
			switch_mpm "$2"
			ret=`expr $ret \| $?`
			to_restart=1
			shift 2
		;;
		-s|--status)
			opt_status=1
			shift
		;;
		-M|--status-mpm)
			opt_status_mpm=1
			shift
		;;
		-a|--all-modules)
			opt_all_modules=1
			shift
		;;
		-R|--no-restart)
			opt_no_restart=1
			shift
		;;
		-h|--help)
			usage
			rm -f $product_log
			exit $?
		;;
		--) shift ; break ;;
		*) p_echo "Internal error: unhandled option $1" ;
			rm -f "$product_log"
			exit 1
		;;
	esac
done

if [ "$opt_status" = "1" ]; then
	status_mods_output=`status_mods $opt_all_modules`
	ret=$?
	[ "$ret" != "0" ] || echo "$status_mods_output" | sort
elif [ "$opt_status_mpm" = "1" ]; then
	status_mpm_output=`status_mpm`
	ret=$?
	[ "$ret" != "0" ] || echo "$status_mpm_output" | sort
fi

if [ "$to_restart" != "0" -a "$opt_no_restart" = "0" ] ; then
	# Restart web server
	if ! "$PRODUCT_ROOT_D/admin/sbin/websrvmng" --restart  >> "$product_log" 2>&1 ; then
		ret=1
	fi
fi

if [ "$ret" != "0" ]; then
	# Operation completed with errors. Cat $product_log on stderr
	cat $product_log >&2
fi

rm -f "$product_log"
exit $ret

# vim:ft=sh
