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

#
# Plesk script
#


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

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

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

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

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

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

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


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

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

	return 1
}

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

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

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

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

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

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

#courier-imap

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

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

	COURIER_DELIVER_QUOTA="/usr/bin/deliverquota"

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

	# Service name for Courier-IMAP <= 3.0.8
	old_courier_service="courier-imap"
}
### Copyright 1999-2015. Parallels IP Holdings GmbH. All Rights Reserved.
# vim:ft=sh:

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

	DOVECOT_INTERNAL_USERGROUP="dovecot"
	DOVECOT_LOGIN_USERGROUP="dovenull"

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

	dovecot_service="dovecot"
}

### Copyright 1999-2015. Parallels IP Holdings 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')"

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

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

	ret="$?"
	if [ "$action" != "status" -a "${action}" != "exists" ]; then
		if [ "$ret" -eq 0 ]; then
			suc
		else
			[ ! -x "/bin/systemctl" ] || /bin/systemctl status "${service}.service" >> "$product_log" 2>&1
			warn "$inten"
		fi
	fi

	return $ret
}

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

	if [ "$action" != "exists" ]; then
		_service_exec $service exists;
		if [ "$?" != "0" ]; then
			warn "attempt to ${inten} - control script doesn't exist or isn't executable"
			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
			;;
		*)
			_service_exec "$service" "$action"
			;;
	esac >> "$product_log"
}

_service_exec()
{
	local service=$1
	local action=$2

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

	if [ -x "/bin/systemctl" ]; then
		case "${action}" in
			exists)
				if /bin/systemctl list-unit-files | awk 'BEGIN { rc = 1 } $1 == "'$service'.service" { rc = 0;} END { exit rc }'; then
					return 0 # systemd unit
				elif [ -x "$sysvinit_service" ]; then
					return 0 # sysvinit compat
				fi
				return 1 # not found
				;;
			status)
				action="is-active"
				;;
			reload)
				action='reload-or-try-restart'
				;;
		esac
		/bin/systemctl "$action" "${service}.service"
	else
		if [ -x "/usr/sbin/invoke-rc.d" ]; then
			action_cmd="/usr/sbin/invoke-rc.d $service"
		elif [ -x "/sbin/service" ]; then
			action_cmd="/sbin/service $service"
		elif [ -x "/usr/sbin/service" ]; then
			action_cmd="/usr/sbin/service $service"
		else
			action_cmd="$sysvinit_service"
		fi

		if [ "$action" = "exists" ]; then
			[ -x "$sysvinit_service" ] && return 0 || return 1
		else
			$action_cmd $action
		fi
	fi
}

is_function()
{
	local type_output="`type \"$1\" 2>/dev/null | head -n1 | awk '{print $NF}'`"
	test "X${type_output}" = "Xfunction"
}
### Copyright 1999-2015. 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
}

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

warn()
{
	local inten
	inten="$1"
	p_echo
	p_echo "WARNING!"
	pnnl_echo "Some problems are found during $inten"
	p_echo "(see log file: ${product_log})"
	p_echo
	p_echo "Continue..."
	p_echo

	product_log_tail | send_error_report_with_input "Warning: $inten"

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

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

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

	chown $u_owner:$g_owner $node || die "chown $u_owner:$g_owner $node"
	chmod $perms $node || die "chmod $perms $node"
}
### Copyright 1999-2015. 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_12.5.30${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 ! expr match "$logname" '/' > /dev/null; 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 [ "`id -u`" = "0" ]; then
			set_ac root 0 0700 "$dir"
		fi
	fi

	if echo $logname  | grep -q XXX > /dev/null; then
		mktemp "$logname"
	else
		echo "$logname"
	fi
}

log_is_in_dev()
{
	local logfile="$1"
	expr match "$logfile" '/dev/' > /dev/null
	return $?
}

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; }
	[ ! "`id -u`" = "0" ] || set_ac root 0 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 || :
}

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

get_product_versions()
{
	local prod_root_d="/usr/local/psa"
	
	product_name="psa"
	product_this_version="12.5.30"
	product_this_version_tag="testing"
	if [ -z "$product_prev_version" ]; then
		if [ -r "$prod_root_d/version.upg" ]; then
			product_prev_version=`cat "$prod_root_d/version.upg" | awk '{ print $1 }'`
		elif [ -r "$prod_root_d/version" ]; then
			product_prev_version=`cat "$prod_root_d/version" | awk '{ print $1 }'`
		else
			product_prev_version="$product_this_version"
		fi
	fi
}

### Copyright 1999-2015. 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-2015. Parallels IP Holdings GmbH. All Rights Reserved.
# vim:syntax=sh

export LANG="C"
umask 022

prog="`basename $0`"
action="$1"
service="$2"
cmds_num="$#"

usage()
{
	echo "Usage: $prog [--enable|--disable] <service>"
	echo ""
	echo "SERVICES:"
	echo "            panel   Applying patches for sw-cp-server."
	echo "            apache  Applying patches for apache server."
	echo "            courier Applying patches for courier-imap."
	echo "            dovecot Applying patches for dovecot."
	echo "            qmail   Applying patches for qmail MTA."
	echo "            proftpd Applying patches for proftpd."
	echo "            all     Applying patches for all installed services described above."

	exit 1
}

[ "$cmds_num" -eq 2 ] || usage

services_list="panel apache courier dovecot qmail proftpd"

log_transaction_start "${prog}${*:+ $*}" "" "plesk-pci-compliance-resolver.log" "/dev/stderr"

read_conf

apache_ssl_conf="$HTTPD_INCLUDE_D/ssl.conf"
sw_server_ssl_conf="/etc/sw-cp-server/conf.d/pci-compliance.conf"
courier_conf_imap="/etc/courier-imap/imapd"
courier_conf_pop="/etc/courier-imap/pop3d"
courier_ssl_conf="/etc/courier-imap/imapd-ssl /etc/courier-imap/pop3d-ssl"

dovecot_installed=0
courier_installed=0

# common things
#------------------------------------------------------------------
check_mail_services()
{
	local mailmng="${PRODUCT_ROOT_D}/admin/sbin/mailmng-server"
	local imap_pop3_server

	test -x "$mailmng" || return 0
	imap_pop3_server=`"$mailmng" --features | grep "'IMAP_POP3_Server'"`

	echo "$imap_pop3_server" | grep -qi "dovecot" && dovecot_installed=1 || :
	echo "$imap_pop3_server" | grep -qi "Courier-IMAP" && courier_installed=1 || :
}

true check_services fail do_disable do_enable
check_services()
{
	local service="$1"
	local flag

	[ "$service" = "all" ] && return 0

	for entry in $services_list; do
		if [ "$1" = "$entry" ]; then
			flag=1
			break
		fi
	done

	[ -z "$flag" ] && return 1

	return 0
}

fail()
{
	p_echo "failed"
}

do_enable()
{
	local service="$1"
	local key="$2"
	local value="$3"
	local config="$4"
	local bkp_file="$5"

	echo_try "enable PCI compliance fixes for $service"

	[ -z "$bkp_file" ] && bkp_file="${config}.pci"

	# checking on already modified file and config file exists
	if [ -e "$bkp_file" ]; then
		echo -n "already modified... "
		suc
		return 2
	fi

	if [ ! -e "$config" ]; then
		echo -n "file: $config not found... "
		fail
		return 1
	fi

	# Comment default strings for RedHat based distros
	if [ "$service" = "apache service" ]; then
		cat "$config" | awk '{
			if (/^<VirtualHost _default_/) {
				flag=1;
			}
			if (/^<\/VirtualHost/) {
				flag=0;
			}
			if (flag && (/^SSLProtocol/ || /^SSLCipherSuite/)) {
				printf ("# ");
				print;
				next;
			}
			print;
		}' > ${config}.new
		mv -f ${config}.new $config
	fi

	# Get original record and backup
	original_str="`cat $config | grep -- \"$key\" |grep -v \"^#\"`"
	echo "$original_str" > $bkp_file

	# Replace record to new value
	if [ -z "$original_str" ]; then
		# Hack for apache
		val="`cat $config | grep -- \"<IfModule mod_ssl.c>\" |grep -v \"^#\"`"
		if [ -z "$val" ]; then
			echo "$value" >> ${config}
		else
			sed -e "s|<IfModule mod_ssl.c>|<IfModule mod_ssl.c>\n$value|" \
			    < $config > ${config}.new &&  mv -f ${config}.new $config
		fi
	else
		sed -e "s|^$original_str$|$value|" < $config > ${config}.new && \
		mv -f ${config}.new $config
	fi

	suc
	return 0
}

do_disable()
{
	local service="$1"
	local key="$2"
	local value="$3" # for compat with 'enable' action
	local config="$4"
	local bkp_file="$5"

	echo_try "disable PCI compliance fixes for $service"

	[ -z "$bkp_file" ] && bkp_file="${config}.pci"

	# checking on already modified file and config file exists
	if [ ! -e "$bkp_file" ]; then
		echo -n "already original config... "
		suc
		return 2
	fi

	if [ ! -e "$config" ]; then
		echo -n "file: $config not found... "
		fail
		return 1
	fi

	# Get record from config and original record
	value="`cat $config | grep -- \"$key\" |grep -v \"^#\"`"
	original_str="`cat $bkp_file`"

	# Replace record to new value
	sed -e "s|^$value$|$original_str|" < $config > ${config}.new && \
	mv -f ${config}.new $config && \
	rm -f $bkp_file

	suc
	return 0
}

service_restart()
{
	local serv="$1"
	local status="$2"

	if [ "$status" -eq 0 ]; then
		echo_try "restart $serv"
		pleskrc $serv restart >/dev/null && suc || fail
	fi

	return $?
}

#-----------------------------------------------------------------------------
# service specific routines
#-----------------------------------------------------------------------------

# panel routines
#-----------------------------------------------------------------------------
true panel_action panel_status
panel_status()
{
	return 0
}

panel_action()
{

	case $1 in
		enable)
		cat <<- EOF > $sw_server_ssl_conf
			ssl_ciphers DHE-DSS-AES256-SHA:AES256-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:KRB5-DES-CBC3-MD5:KRB5-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:EDH-DSS-DES-CBC3-SHA:DES-CBC3-SHA:DES-CBC3-MD5:DHE-DSS-RC4-SHA:KRB5-RC4-MD5:KRB5-RC4-SHA:RC4-SHA:RC4-MD5:RC2-CBC-MD5:RC4-MD5;
			ssl_prefer_server_ciphers on;
			EOF
		;;
		disable)
			rm -f $sw_server_ssl_conf
		;;
		*)
	        usage
			return 1
        ;;
	esac
	/etc/init.d/sw-cp-server reload
}

true courier_action
courier_action()
{
	local action="$1"

	if [ "$courier_installed" != 1 ]; then
        echo "service courier-imap is not installed, skip modifying."
        return 0
	fi

	local key='TLS_CIPHER_LIST'
	local value='TLS_CIPHER_LIST="HIGH:MEDIUM:!SSLv2:!LOW:!EXP:!aNULL:!ADH:@STRENGTH"'

	flag=0
	for conffile in $courier_ssl_conf; do
		do_$action "courier-imap ssl service" "$key" "$value" "$conffile" || flag=1
	done

	value="IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA AUTH=CRAM-MD5 AUTH=CRAM-SHA1 AUTH=CRAM-SHA256 IDLE"
	do_$action "courier-imap IMAP4 service" "IMAP_CAPABILITY=" "IMAP_CAPABILITY=\"$value\"" \
			"$courier_conf_imap" "${courier_conf_imap}.pci.1" || flag=1
	do_$action "courier-imap IMAP4 service" "IMAP_CAPABILITY_ORIG=" "IMAP_CAPABILITY_ORIG=\"$value\"" \
			"$courier_conf_imap" "${courier_conf_imap}.pci.2" || flag=1

	value="\$IMAP_CAPABILITY AUTH=PLAIN"
	do_$action "courier-imap IMAP4 TLS service" "IMAP_CAPABILITY_TLS=" "IMAP_CAPABILITY_TLS=\"$value\"" \
			"$courier_conf_imap" "${courier_conf_imap}.pci.3" || flag=1
	value="\$IMAP_CAPABILITY_ORIG AUTH=PLAIN"
	do_$action "courier-imap IMAP4 TLS service" "IMAP_CAPABILITY_TLS_ORIG=" "IMAP_CAPABILITY_TLS_ORIG=\"$value\"" \
			"$courier_conf_imap" "${courier_conf_imap}.pci.4" || flag=1

	value="LOGIN CRAM-MD5 CRAM-SHA1 CRAM-SHA256"
	do_$action "courier-imap POP3 service" "POP3AUTH=" "POP3AUTH=\"$value\"" \
			"$courier_conf_pop" "${courier_conf_pop}.pci.1" || flag=1
	do_$action "courier-imap POP3 service" "POP3AUTH_ORIG=" "POP3AUTH_ORIG=\"$value\"" \
			"$courier_conf_pop" "${courier_conf_pop}.pci.2" || flag=1

	value="LOGIN PLAIN"
	do_$action "courier-imap POP3 TLS service" "POP3AUTH_TLS=" "POP3AUTH_TLS=\"$value\"" \
			"$courier_conf_pop" "${courier_conf_pop}.pci.3" || flag=1
	do_$action "courier-imap POP3 TLS service" "POP3AUTH_TLS_ORIG=" "POP3AUTH_TLS_ORIG=\"$value\"" \
			"$courier_conf_pop" "${courier_conf_pop}.pci.4" || flag=1

	set_courier_imap_params
	service_restart courier_imapd "$flag"
	service_restart courier_imaps "$flag"
	service_restart courier_pop3d "$flag"
	service_restart courier_pop3s "$flag"

	return $flag
}

true apache_action
apache_action()
{
	local action="$1"

	set_apache_params
# Copy/Remove PCI-Compliance template
	case $action in
		enable)
			if [ -f "/usr/local/psa/admin/conf/templates/custom/server/PCI_compliance.php" ]; then
				echo "Custom server/PCI_Compliance.php template already exists"
				echo "Do nonthing"
				return 0
			fi

			if [ ! -f "/usr/local/psa/admin/conf/templates/pci_compliance/server/PCI_compliance.php" ]; then
				echo "/usr/local/psa/admin/conf/templates/pci_compliance/server/PCI_compliance.php not exists"
				return 1
			fi

			mkdir -p /usr/local/psa/admin/conf/templates/custom/server
			cp -f /usr/local/psa/admin/conf/templates/pci_compliance/server/PCI_compliance.php /usr/local/psa/admin/conf/templates/custom/server/PCI_compliance.php
			;;
		disable)
			rm -f /usr/local/psa/admin/conf/templates/custom/server/PCI_compliance.php
			;;
	esac

	httpdmng_reconfigure server
	service_restart apache "0"

	return 0
}

true qmail_action
qmail_action()
{
	local action="$1"
	local flag="/var/qmail/control/rejectplain"
	case "$action" in
		enable) touch $flag >/dev/null 2>&1 ;;
		*) rm -f $flag >/dev/null 2>&1 ;;
	esac
}

true proftpd_action
proftpd_enable()
{
        local proftpd_conf="/etc/proftpd.conf"
        local sp1='[[:space:]]*'
        local sp2='[[:space:]]\+'

        proftpd_disable

        sed -i -e "/^${sp1}Include${sp2}\/etc\/proftpd.include/ i \\
<IfModule mod_tls.c> #pci_compliance_resolver\n\
        # globaly setup security policy\n\
        TLSProtocol SSLv23\n\
        TLSCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM\n\
</IfModule> #pci_compliance_resolver\
" ${proftpd_conf}
}

proftpd_disable()
{
        local proftpd_conf="/etc/proftpd.conf"
        local sp1='[[:space:]]*'
        local sp2='[[:space:]]\+'

        sed -i -e "/^${sp1}<${sp1}IfModule${sp2}mod_tls.c${sp1}>${sp1}#${sp1}pci_compliance_resolver/,/^${sp1}<${sp1}\/IfModule${sp1}>${sp1}#${sp1}pci_compliance_resolver/ d" ${proftpd_conf}
}

proftpd_action()
{
        local action="$1"

        case $action in
                enable)
                        proftpd_enable
                        ;;
                disable)
                        proftpd_disable
                        ;;
        esac
}

true dovecot_action
dovecot_action()
{
	local action="$1"
	set_dovecot_params

	local pci_compliance_config="${DOVECOT_INCLUDE_DIR}/11-plesk-security-pci.conf"
	local no_restart=0
	local res=0

	if [ "$dovecot_installed" != 1 ]; then
        echo "service dovecot is not installed, skip modifying."
        return 0
	fi

	case "$action" in
		enable)
			echo_try "apply PCI compliance fixes for service Dovecot"
			cat > "$pci_compliance_config"  <<EOF
##
## PCI compliance changes made by admin/bin/pci_compliance_resolver utility.
## Do not edit this file directly. Use the utility instead.
##

disable_plaintext_auth = yes
ssl_cipher_list = "HIGH:MEDIUM:!SSLv2:!LOW:!EXP:!aNULL:!ADH:@STRENGTH"
EOF
			suc # need real check?
			;;
		disable)
			echo_try "remove PCI compliance fixes for service Dovecot"
			test -f "$pci_compliance_config" && rm -f "$pci_compliance_config" || no_restart=1
			suc
			;;
	esac

	service_restart dovecot $no_restart
}


true all_action
all_action()
{
    local action="$1"

    for entry in $services_list; do
	    service="$entry"
	    ${entry}_action $action
	    echo ""
    done

    return 0
}

check_mail_services
# getopt like selector
#-----------------------------------------------------------------------------
case "$action" in
	--enable)
		check_services $service || echo "Unsupported service: $service"
		${service}_action enable
		exit $?
		break
		;;

	--disable)
		check_services $service || echo "Unsupported service: $service"
		${service}_action disable
		exit $?
		break
		;;
	*)
		usage
		;;
esac
