#!/bin/sh
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
#

#
# Plesk script
#


### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
# Migration manager tables will be managed by plesk

### Copyright 1999-2012. 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"

	set_apache_params_linux

	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
}

set_apache_params_linux()
{
	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"
}

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
}

# 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 redhat/centos some modules has own configs: perl, python
		if [ -n "$config" ] ; then
			:
		elif [ -e "$HTTPD_INCLUDE_D/$module_name.conf" ]; then
			config="$HTTPD_INCLUDE_D/$module_name.conf"
		else
			config="${apache_httpd_conf}"
		fi
		
		[ -n "$module_soname" ] || module_soname="mod_$module_name.so"
		
		cat $config | 			perl -e '
				@lines = <STDIN>;
				$found = 0;
				$lastline = 0;
				for ($i=0; $i<=$#lines; $i++)
				{
					if ( @lines[$i] =~ /^\s*?#\s*?LoadModule.*@ARGV[0]_module.*@ARGV[2]/ )
					{
						if ( $found > 0 )
						{
							@lines[$i] =~ s/^(.*)$/####This line was duplicated: $1/;
						}else{
							@lines[$i] =~ s/^\s*?#\s*?L/L/;
							$found++;
						}
					}
					elsif ( @lines[$i] =~ /^\s*?(LoadModule.*@ARGV[0]_module.*@ARGV[2])/ )
					{
						if ( $found > 0 )
						{
							@lines[$i] =~ s/^(.*)$/####This line was duplicated: $1/;
						}else{
							$found++;
						}
					}
					elsif ( @lines[$i] =~ /^[^#\s]*?<If/ )
					{
						$deep++;
					}
					elsif ( @lines[$i] =~ /^[^#\s]*?<\/If/ )
					{
						$deep--;
					}
					if ( @lines[$i] =~ /LoadModule.*_module.*so/  && $deep <= 0 )
					{
						$lastline = $i;
					}
				}
				if ( $found == 0 && $lastline > 0 )
				{
					print @lines[0..$lastline];
					print "LoadModule @ARGV[0]_module @ARGV[1]/@ARGV[2]\n";
					print @lines[$lastline+1..$#lines];
				}else{
					print @lines;
				}
			' "${module_name}" "${apache_modules_d}" "$module_soname" 		> $config.new
		mv $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

# Got config to work
		if [ -n "$config" ]; then
			:
		elif [ -e "$HTTPD_INCLUDE_D/$module_name.conf" ]; then
			config="$HTTPD_INCLUDE_D/$module_name.conf"
		else
			config="${apache_httpd_conf}"
		fi

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

		cat $config | 			perl -e '
				@lines = <STDIN>;
				$found = 0;
				$foundcomment = 0;
				$lastline = 0;
				$r1 = "^[^#\s]*?(LoadModule.*@ARGV[0]_module.*@ARGV[1])";
				$r2 = "^\s*?#\s*?LoadModule.*@ARGV[0]_module.*@ARGV[1]";
				for ($i=0; $i<=$#lines; $i++)
				{
					if ( @lines[$i] =~ /$r1/ )
					{
						if ( $found > 0 || $foundcomment > 0 )
						{
							@lines[$i] =~ s/^(.*)$/####This line was duplicated: $1/;
						}else{
							@lines[$i] =~ s/^(.*)$/#$1/;
							$found++;
						}
					}
					elsif ( @lines[$i] =~ /$r2/ )
					{
						if ( $foundcomment > 0 || $found > 0 )
						{
							@lines[$i] =~ s/^(.*)$/####This line was duplicated: $1/;
						}else{
							$foundcomment++;
						}
					}
				}
				print @lines;
			' "$module_name" "$module_soname" 		> "$config.new"
		mv "$config.new" "$config"
}
### Copyright 1999-2012. Parallels IP Holdings 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 "$@"
}

# 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 "$@"
    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 "$*"
    else
        echo -n "$*" >> "$product_log" 2>&1
    fi
}

die()
{
	PACKAGE_SCRIPT_FAILED="$*"

	printf "\a\a"
	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()
{
	{
		echo $@
		echo ""
		if [ -n "$error_report_context" ]; then
			echo "Context: $error_report_context"
			echo ""
		fi
		cat -
	} | $PRODUCT_ROOT_D/admin/bin/send-error-report "install" >/dev/null 2>&1
}

detect_vz()
{
	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
	return 0
}

### the function similar to awk -F'$fs' 'print $N'
get_narg_fs()
{
	local IFS="$2"
	get_narg $3 $1
}

get_narg()
{
	shift $1 2>/dev/null || return
	echo $1
}

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

get_groupID()
{
# try to get GID, id -g doesn't show groups without users
	common_var=`cat /etc/group | awk -F':' '$1 == "'$1'" {print $3}'` 

# We have non-empty value if success
	test -n "$common_var"
}

group_check()
{
	local group grp_res
	group="$1"

	grp_res=`groupmod "$group" 1>/dev/null 2>&1 ; echo $?`

	echo "$grp_res"
}

del_user_from_group()
{
	local user group inten existing newlist

	test $# -eq 2 || die "user or group is not defined"

	inten="remove user ${1} from group ${2}"
	echo_try "$inten"

	user=$1

	get_groupID $2 || die "$inten"
	group=$common_var

	existing=`id -G "$user"`
	newlist=`echo "$existing" | xargs -n1 | egrep -v "^${group}$" | xargs`

	if [ "X${existing}" = "X${newlist}" ]; then
        	p_echo "user ${user} is not in group ${group}"
                return
        fi;

        newlist=`echo "${newlist}" | sed 's|[[:space:]]\+|,|g'`
        usermod -G "$newlist" "$user" 2>>"$product_log" && suc || die "$inten"
}

add_user_to_group()
{
	local user group grp_res existing newlist

	user="$1"
	group="$2"

	# check exists group
	p_echo " Checking for the group '$group'..."
	grp_res=`group_check "$group"`

	if [ "X$grp_res" != "X0" ]; then
			p_echo " Group '$group' not exists"
			p_echo " It is necessary to add group '$group'"
			err
	fi

	inten="add supplementary group '$group' for user '$user'"
	echo_try "$inten"

	existing=`id -Gn "$user"|sed 's|[[:space:]]\+|,|g'`
	if
		test "`id -gn "$user"`" = "$group" \
		|| echo "$existing" | grep -q "\\<$group\\>"
	then
		p_echo " already there"
		return
	fi

	if test -z "$existing"; then
		newlist="$group"
	else
		newlist="$existing,$group"
	fi

	usermod -G "$newlist" "$user" 2>>"$product_log" && suc || die "$inten"
}

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
			[ 0$ignore_miss_conf -ne 1 ] && p_echo "Unable to find product configuration file: $prod_conf_t"
			return 1
		fi
	fi
	return 0
}

 #default values

product_default_conf()
{

PRODUCT_ROOT_D=/usr/local/psa
PRODUCT_RC_D=/etc/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
FTPD_CONF=/etc/proftpd.conf
FTPD_CONF_INC=/etc/proftpd.include
FTPD_BIN_D=/usr/bin
FTPD_VAR_D=/var/run/proftpd
FTPD_SCOREBOARD=/var/run/proftpd/scoreboard
NAMED_RUN_ROOT_D=/var/named/run-root
NAMED_OPTIONS_CONF=
NAMED_ZONES_CONF=
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.6
CATALINA_HOME=/usr/share/tomcat5
DRWEB_ROOT_D=/opt/drweb
DRWEB_ETC_D=/etc/drweb
GPG_BIN=/usr/bin/gpg
TAR_BIN=/bin/tar
AWSTATS_ETC_D=/etc/awstats
AWSTATS_BIN_D=/var/www/cgi-bin/awstats
AWSTATS_TOOLS_D=/usr/share/awstats
AWSTATS_DOC_D=/var/www/html/awstats
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=false
APS_DB_DRIVER_LIBRARY=/usr/lib64/libmysqlserver.so.2
IPv6_DISABLED=false
SA_MAX_MAIL_SIZE=256000

}

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

	setenforce "$SELINUX_ENFORCE"
}
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.

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

	#VZP used to determine that we're inside SVE
	vza_file="/var/vzagent"

	#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/pp11.5.30-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"

	set_common_params_linux 

	detect_vz
}

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"

	if [ -f /etc/slackware-version ]; then
	    linux_distr="slackware"
	    useradd_options=""
	    sndml_ini="/etc/rc.d/init.d/sendmail"
	    mail_local="/usr/libexec/mail.local"
	    dummy_shell=""
	    named_osrelease=0
	else
	    useradd_options="-M"
	    if [ -f /etc/mandrake-release ]; then
		linux_distr="mandrake"
	    elif [ -f /etc/fedora-release ]; then
		linux_distr="fedora"
	    elif [ -f /etc/SuSE-release ]; then
		linux_distr="suse"
		useradd_options="-r"
	    elif [ -f /etc/debian_version ]; then
		linux_distr="debian"
		get_domainname="dnsdomainname"
		useradd_options=""
	    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"
	    named_osrelease=`cat /proc/sys/kernel/osrelease | perl -F"/[.-]/" -n -a  -e 'printf "%02u%02u%02u\n", $F[0],$F[1],$F[2]'`
	fi

	return 0
}

### Copyright 1999-2012. 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
}
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
usage()
{
cat << EOT
Usage: nginx_proxy { --on | --off } --port-map <mapping> [ --no-httpd-selinux-fix ]
       nginx_proxy --status

	-s, --status    Check whether NGINX is enabled in proxy mode
	-e, --on        Turn on NGINX as reverse proxy to Apache
	-d, --off       Turn off NGINX as reverse proxy and make Apache frontend server

	-m, --port-map <from1:to1,from2:to2,...>
	                Specify Apache ports mapping during enabling or disabling 
	                NGINX as reverse proxy.
	-n, --no-httpd-selinux-fix
	                Normally Apache is allowed to bind to a restricted set of ports
	                by SELinux. By default upon making Apache a backend server
	                this utility would allow it to bind to any unprivileged port. 
	                This option suppresses such behavior. 
	                You can manually allow Apache to use specific ports, e.g. using:
	                # semanage port -a -t http_port_t -p tcp <port>

Warning: this utility expects that all web server configuration files except main 
ones have already been updated. Otherwise NGINX and Apache may fail to start.
EOT
	exit 1
}

# --- args check ---

while [ "$#" -gt 0 ]; do
	case "$1" in
		-s|--status)
			opt_status="yes"
			shift
			;;
		-e|--on)
			opt_enable="yes"
			shift
			;;
		-d|--off)
			opt_disable="yes"
			shift
			;;
		-m|--port-map)
			opt_port_map="$2"
			shift 2
			;;
		-n|--no-httpd-selinux-fix)
			opt_no_httpd_selinux_fix="yes"
			shift
			;;
		--skip-cleanup)
			opt_skip_cleanup="yes"
			shift
			;;
		-h|--help)
			usage
			;;
		*)
			echo "Unknown argument '$1'"
			echo
			usage
			;;
	esac
done

[ -n "$opt_status"  -a -z "$opt_enable$opt_disable$opt_port_map$opt_no_httpd_selinux_fix" ] || \
[ -n "$opt_enable"  -a -n "$opt_port_map" -a -z "$opt_status" ] || \
[ -n "$opt_disable" -a -n "$opt_port_map" -a -z "$opt_status" ] || \
	usage

# --- logging ---

product_log="`mktemp /tmp/nginx_proxy.log.XXXXXX`"
product_problems_log="$product_log"

# --- workers ---

ngxp_enable_rc()
{
	local do_enable="$1"
	p_echo "Switching NGINX rc enabled state to '$do_enable'"
	if grep -q '^\s*NGINX_ENABLED=' "$nginx_rc_config" >/dev/null 2>&1 ; then
		sed -e 's/^\(\s*NGINX_ENABLED=\s*\)"\?[^"]*"\?\(\s*\(#.*\)\?\)$/\1'$do_enable'\2/g' "$nginx_rc_config" > "$nginx_rc_config.tmp" && \
		mv -f "$nginx_rc_config.tmp" "$nginx_rc_config" || \
			rm -f "$nginx_rc_config.tmp"
	else
		echo "NGINX_ENABLED=$do_enable" >> "$nginx_rc_config"
	fi
	chmod 644 "$nginx_rc_config"
}

ngxp_find_apache_configs()
{
	find $HTTPD_CONF_D $HTTPD_INCLUDE_D -type f \( -name '*.conf' -o -path '*/sites-*' \) | sort | uniq
}

ngxp_switch_apache_ports()
{
	local OLD_IFS="$IFS"
	local IFS=","
	local port_map="$1"
	local from_port to_port sed_cmds
	p_echo "Switching Apache ports in config files using mapping '$port_map'"
	for port_pair in $port_map ; do
		from_port=`get_narg_fs "$port_pair" ':' 1`
		to_port=`  get_narg_fs "$port_pair" ':' 2`
		
		sed_cmds="$sed_cmds -e "'s/^\(\s*Listen\s\+\)'${from_port}'\(\s*\(#.*\)\?\)$/\1'${to_port}'\2/g'
		sed_cmds="$sed_cmds -e "'s/^\(\s*NameVirtualHost\s\+[^:[:space:]]\+\):'${from_port}'\(\s*\(#.*\)\?\)$/\1:'${to_port}'\2/g'
		sed_cmds="$sed_cmds -e "'s/^\(\s*<VirtualHost\s\+[^:[:space:]]\+\):'${from_port}'\(\s*>\s*\(#.*\)\?\)$/\1:'${to_port}'\2/g'
	done
	IFS="$OLD_IFS"

	ngxp_apache_cfg_bakup_d=`mktemp -d /tmp/nginx_proxy_backups.XXXXXX`
	[ "$?" -eq 0 ] || die "Failed to create temporary directory for Apache config backups"
	p_echo "Apache config file backups will be saved to '$ngxp_apache_cfg_bakup_d'"

	for config in `ngxp_find_apache_configs`; do
		grep -q '^[^#]*\(Listen\|NameVirtualHost\|VirtualHost\)' "$config" >/dev/null 2>&1 || continue
		mkdir -p "$ngxp_apache_cfg_bakup_d/`dirname $config`"
		cp "$config" "$ngxp_apache_cfg_bakup_d/$config"

		sed $sed_cmds "$config" > "$config.tmp" && \
		! diff -q "$config" "$config.tmp" >/dev/null 2>&1 && \
		p_echo "Updating '$config'." && \
		mv -f "$config.tmp" "$config" || \
			rm -f "$config.tmp"
	done
}

ngxp_switch_apache_ports_cleanup()
{
	rm -rf "$ngxp_apache_cfg_bakup_d"
}

ngxp_switch_apache_modules()
{
	true add_apache_module remove_apache_module

	local action="$1"
	[ "$action" = "add" -o "$action" = "remove" ] || die "ngxp_switch_apache_modules(): expected 'add' or 'remove' argument"

	p_echo "Performing $action of Apache RPAF module"
	${action}_apache_module "rpaf"
	p_echo "Performing $action of Apache aclr2 module"
	${action}_apache_module "aclr"
}

ngxp_switch_selinux_apache_bind_any_port()
{
	local enable="$1"
	local output
	[ "$opt_no_httpd_selinux_fix" = "yes" ] && enable=0
	[ "$enable" = "1" -o "$enable" = "0" ] || die "ngxp_switch_selinux_apache_bind_any_port(): expected '0' or '1' argument"

	if ! command -v setsebool >/dev/null 2>&1 ; then
		p_echo "SELinux adjustments not required (no setsebool utility)"
		return 0
	fi

	p_echo "Switching Apache ability to bind to any port (SELinux) to $enable"
	if ! getsebool -a | grep -q httpd_can_bind_all_ports 2>/dev/null ; then
		p_echo "Warning: SELinux boolean httpd_can_bind_all_ports not found. Is plesk.pp policy installed?"
		return 1
	fi
	output=`setsebool -P httpd_can_bind_all_ports $enable 2>&1`
	if [ "$?" -ne 0 ]; then
		# Policy will often disallow 'setsebool' to append to anything in /tmp/
		echo "$output" >>"$product_log"
		return 1
	fi
}

ngxp_apache_control()
{
	local action="$1"
	p_echo "Doing Apache $action"
	$PRODUCT_ROOT_D/admin/sbin/apache_control_adapter "--$action" 2>>"$product_log"
}

ngxp_nginx_control()
{
	local action="$1"
	p_echo "Doing NGINX $action"
	$PRODUCT_ROOT_D/admin/sbin/nginx_control "--$action" 2>>"$product_log"
}

ngxp_do_status()
{
	if nginx_is_rc_enabled ; then
		pp_echo "on"
	else
		pp_echo "off"
	fi
}

ngxp_do_enable()
{
	nginx_is_rc_enabled && pp_echo "NGINX as reverse proxy is already enabled, but I will reenable it anyway"
	add_user_to_group $nginx_user psaserv

	ngxp_switch_apache_ports "$opt_port_map"
	ngxp_switch_apache_modules "add"
	ngxp_enable_rc "yes"
	ngxp_switch_selinux_apache_bind_any_port 1
	ngxp_nginx_control "stop"
	ngxp_apache_control "restart" && \
	ngxp_nginx_control "start"
	ngxp_retval="$?"
	ngxp_watchdog_reconfigure "enable"
}

ngxp_do_disable()
{
	nginx_is_rc_enabled || pp_echo "NGINX as reverse proxy is already disabled, but I will redisable it anyway"

	ngxp_switch_apache_ports "$opt_port_map"
	ngxp_switch_apache_modules "remove"
	ngxp_enable_rc "no"
	ngxp_switch_selinux_apache_bind_any_port 0
	ngxp_watchdog_reconfigure "disable"	
	ngxp_nginx_control "stop" && \
	ngxp_apache_control "restart"
	ngxp_retval="$?"

	del_user_from_group $nginx_user psaserv
}

ngxp_watchdog_reconfigure()
{
	# XXX if watchdog will ever work with services on SN, move this to nginxmng or elsewhere
	local nginx_action=$1
	# regenerate watchdog confs and reload watchdog
	if [ -x "@@MODULES_BIN_D@@/watchdog/wd" ] ; then
		if [ "$nginx_action" = "disable" ] ; then
			# turn nginx monitoring off
			"@@MODULES_BIN_D@@/watchdog/wd" --unmonit-service=nginx
		fi
		"@@MODULES_BIN_D@@/watchdog/wd" --adapt
	fi
}

# --- the script ---

product_default_conf
read_conf
set_common_params
set_apache_params
set_nginx_params

[ "$opt_status"  = "yes" ] && ngxp_do_status
[ "$opt_enable"  = "yes" ] && ngxp_do_enable
[ "$opt_disable" = "yes" ] && ngxp_do_disable

if [ "0${ngxp_retval}" -eq 0 ]; then
	p_echo "SUCCESS"
	[ "$opt_skip_cleanup" = "yes" ] || {
		ngxp_switch_apache_ports_cleanup
		rm -f "$product_log"
	}
fi

exit $ngxp_retval

# vim:syntax=sh
