#!/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.
# 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
	local service_script=""
	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
		[ "$ret" -eq 0 ] && suc || warn $inten
	fi

	return $ret
}

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

	local action_cmd=
	local service_script=

	if [ -x "$SYSTEM_RC_D/$service" ]; then
		service_script="$SYSTEM_RC_D/$service"
	elif [ ! -z "${PRODUCT_RC_D}" -a -x "$PRODUCT_RC_D/$service" ]; then
		service_script="$PRODUCT_RC_D/$service"
	fi

	if [ "$action" = "exists" ]; then 
		[ -n "$service_script" ] && return 0 || return 1
	elif [ -z "$service_script" ]; then
		warn "Unable to ${inten} - control script doesn't exist or isn't executable"
		return 1
	fi


	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 [ -n ${service_script} ]; then
		action_cmd="$service_script"
	fi

	
	case "$action" in
		start)
			pleskrc $service_name status || $action_cmd $action
			;;
		stop)
			! pleskrc $service_name status || $action_cmd $action
			;;
		restart)
			if pleskrc $service_name status; then 
				$action_cmd $action
			else 
				$action_cmd start
			fi
			;;
		reload)
			! pleskrc $service_name status || $action_cmd $action
			;;
		status)
		    $action_cmd "status"
			;;
	    *)
		    $action_cmd $action
			;;
	esac >> $product_log 2>&1
}

is_function()
{
	local type_output="`type \"$1\" 2>/dev/null | head -n1 | awk '{print $NF}'`"
	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 "$@"
    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
}

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

set_error_report_context()
{
	error_report_context="$@"
}

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

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

log_start()
{
	true product_log_name product_problems_log_name

	local title="$1"
	product_log="/tmp/`product_log_name`"
	product_problems_log="/tmp/`product_problems_log_name`"
	problems_occured=0

	echo "START $title" >>"$product_log" 	&& echo "START $title" >>"$product_problems_log" 	&& chmod 600 "$product_log" "$product_problems_log" 	|| {
		echo "Cannot write installation log $product_log, $product_problems_log" >&2
		exit 1
	}

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

log_stop()
{
	local title="$1"
	local subject="$2"
	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

	p_echo
	p_echo "**** $subject $status."
	p_echo

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

	echo "STOP $title" >>"$product_log"
	if [ $problems_occured -ne 0 ]; then
		echo "STOP $title: PROBLEMS FOUND" >>"$product_problems_log"
	else
		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-2012. Parallels IP Holdings GmbH. All Rights Reserved.

# here goes functions

package_script_begin_rpm()
{
	package_script_begin
}

package_script_end_rpm()
{
	package_script_end
}

package_script_begin()
{
	if [ "X$process" = "X" ]; then
		if	 [ "X$do_reconfigure" = "X1" ]; then
			process="reconfiguration"
		elif  [ "X$do_upgrade" = "X1" ]; then
			process="upgrade"
		else
			process="installing"
		fi
	fi

	log_start "`package_script_log_title`"
	set_error_report_context "`package_script_log_title`. `report_context_action`"

	product_default_conf
	initial_conf
	set_common_params
	read_conf
}

package_script_end()
{
	packagemng_set_dirty_flag

	log_stop "`package_script_log_title`" "Package $PACKAGE_NAME scriptlet"
}

package_script_log_title()
{
	local stage
	case "$do_upgrade" in
		0) stage="installing";;
		1) stage="upgrading";;
		*) stage="installing";;
	esac
	if [ -n "$PACKAGE_DEB_ACTION" ]; then
		stage="$stage (deb action: $PACKAGE_DEB_ACTION)"
	fi
	echo "$PACKAGE_NAME-$PACKAGE_VERSION-$PACKAGE_RELEASE $stage AT `date`"
}

report_context_action()
{
	local action
	get_product_versions
	if [ "X$do_upgrade" = "X1" -o "$product_prev_version" != "$product_this_version" ]; then
		action="Doing $product_name upgrade from $product_prev_version to $product_this_version"
	else
		action="Doing $product_name $product_this_version installation"
	fi
	echo "$action"
}
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
# vim:ft=sh

initial_conf()
{
	DEMO_VERSION="no"
	PRODNAME="psa"
	PRODUCT_NAME="psa"
	product_full="Plesk"
	product=${PRODNAME}
	PRODUCT_FULL_NAME="Plesk"

	product_etc="/etc/${PRODNAME}"
	prod_conf_t="/etc/psa/psa.conf"
	prodkey="$product_etc/$PRODNAME.key"

	minimal_changes=""

	EXTERNAL_PACKAGES=""
	EXTERNAL_PACKAGES_DIR=""

	BUILDER_UID="10007"

	PERL5LIB=/opt/psa/local/share/perl/5.14.2:/opt/psa/local/lib/perl/5.14.2
	export PERL5LIB

        support_contact="http://www.parallels.com/support"
	sales_email="sales@parallels.com"

	product_version="11.5.30"
	product_db_version="011005030"
	conceived_os_vendor=Ubuntu
	conceived_os_version="12.04"
	osrels="ubuntu12.04"

	prev_product="plesk"
	prev_clients_group="${prev_product}cln"

        clients_group="${product}cln"
        clients_GID=10001

        services_group="psaserv"
        services_GID=10003

        product_suff="saved_by_${product}".`date "+%m.%d;%H:%M"`
        product_suffo="saved_by_${product}"

	PREV_PRODUCT_ROOT_D="/usr/local/${prev_product}"

	# plesk default password
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		PRODUCT_DEFAULT_PASSWORD="plesk"
	else
		PRODUCT_DEFAULT_PASSWORD="setup"
	fi
}

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=/opt/psa
PRODUCT_RC_D=/etc/init.d
PRODUCT_ETC_D=/opt/psa/etc
PLESK_LIBEXEC_DIR=/usr/lib/plesk-9.0
HTTPD_VHOSTS_D=/var/www/vhosts
HTTPD_CONF_D=/etc/apache2
HTTPD_INCLUDE_D=/etc/apache2/conf.d
HTTPD_BIN=/usr/sbin/apache2
HTTPD_LOG_D=/var/log/apache2
HTTPD_SERVICE=apache2
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/run/mysqld/mysqld.sock
PGSQL_DATA_D=/var/lib/postgresql//main
PGSQL_CONF_D=/etc/postgresql//main
PGSQL_BIN_D=/usr/lib/postgresql/9.1/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/python
CATALINA_HOME=/var/lib/tomcat6
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=/usr/lib/cgi-bin
AWSTATS_TOOLS_D=/usr/share/awstats/tools
AWSTATS_DOC_D=/usr/share/awstats
OPENSSL_BIN=/usr/bin/openssl
LIB_SSL_PATH=/lib/libssl.so
LIB_CRYPTO_PATH=/lib/libcrypto.so
CLIENT_PHP_BIN=/opt/psa/bin/php-cli
SNI_SUPPORT=true
APS_DB_DRIVER_LIBRARY=/usr/lib/libmysqlserver.so.2
IPv6_DISABLED=false
SA_MAX_MAIL_SIZE=256000

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

#-*- vim:ft=sh

register_service(){

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

	{
		# update-rc.d for Debian/Ubuntu (not SuSE)
		/usr/sbin/update-rc.d "$1" defaults
	} >> $product_log 2>&1

	suc
}

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

	setenforce "$SELINUX_ENFORCE"
}

selinux_relabel_dir()
{
	if ! command -v restorecon >/dev/null 2>&1; then
		return
	fi
	if [ "$1" = "-F" ]; then
		selinux_set_force_arg
		shift
	else
		SELINUX_FORGE_ARG=
	fi

	if [ "$1" = "-e" ]; then
		selinux_set_exclude_arg "$2"
		shift 2
	else
		SELINUX_EXCLUDE_ARG=
	fi

	restorecon $SELINUX_FORGE_ARG $SELINUX_EXCLUDE_ARG -R "$@" >>"$product_log" 2>&1 || report_problem "Error while setting SELinux types for '$dir'"
}

selinux_set_force_arg()
{
	SELINUX_FORGE_ARG="" 
}

selinux_set_exclude_arg()
{
	selinux_set_exclude_arg_pass "$1"
}

selinux_set_exclude_arg_pass()
{
	SELINUX_EXCLUDE_ARG=""
}
### 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/lib/plesk-9.0"
	PLESK_DB_DIR="/var/lib/plesk"
	POSTFIX_LIBEXEC_DIR="/usr/lib/postfix"
	PRODUCT_BOOTSTRAPPER_DIR="/opt/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_syslog_params()
{
	syslog_service="sysklogd"
	syslog_conf_ng="/etc/syslog-ng/syslog-ng.conf"

	syslog_conf=""
	for config in rsyslog.conf rsyslog.early.conf syslog.conf; do
		[ -f "/etc/$config" ] && syslog_conf="$syslog_conf /etc/$config"
	done

	# FIXME: quick fix of 142129
	if [ "${machine}" = "linux" -a ! -x "$PRODUCT_RC_D/$syslog_service" -a -x "$PRODUCT_RC_D/rsyslog" ]; then
		syslog_service="rsyslog"
		syslog_binary="/sbin/rsyslogd"
	elif [ "${machine}" = "linux" -a ! -x "$PRODUCT_RC_D/$syslog_service" -a -x "$PRODUCT_RC_D/syslog-ng" ]; then
		syslog_service="syslog-ng"
		syslog_binary="/sbin/syslog-ng"
	else
		syslog_binary="/sbin/syslogd"
	fi
}


reload_syslog()
{
	# set_syslog_params must be called in outed function

	if [ "X$syslog_service" = "Xrsyslog" ]; then
		# Bug 142129
		# rsyslog service registration is necessary
		# it is workaround on default rsyslog service registration behaviour
		register_service rsyslog 2345 16 74
		# then we restart it
	fi

	if [ "$syslog_service" = "syslog" -o "$syslog_service" = "rsyslog" ] && [ "$PLESK_VZ" = "1" ]; then
		# 146355 - rsyslog/syslog service returns false on VZ
		/etc/init.d/$syslog_service restart
	elif [ "X$syslog_service" = "Xrsyslog" ]; then
		pleskrc syslog restart
	else
		pleskrc syslog reload
	fi
}

### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
# -*- vim:syntax=sh

packagemng_set_dirty_flag()
{
	if [ -f ${PRODUCT_ROOT_D}/admin/bin/packagemng ]; then
		${PRODUCT_ROOT_D}/admin/bin/packagemng --set-dirty-flag 1>>$product_log 2>&1
	fi
}

get_product_versions()
{
	local prod_root_d="/opt/psa"
	
	product_name="psa"
	product_this_version="11.5.30"
	product_this_version_tag=""
	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-2012. Parallels IP Holdings GmbH. All Rights Reserved.
#-*- vim:syntax=sh

select_maillog()
{
	inten="set maillog file to $PRODUCT_ROOT_D/var/log/maillog"

	set_syslog_params

	mail_log="$PRODUCT_ROOT_D/var/log/maillog"

	if [ "X$syslog_service" = "Xrsyslog" ]; then
		reload_syslog
		return
	fi

	[ -d "$PRODUCT_ROOT_D/var/log" ] || mkdir -p "$PRODUCT_ROOT_D/var/log"
	touch $mail_log
	chmod 0640 $mail_log
	selinux_relabel_dir "$PRODUCT_ROOT_D/var/log"

	for config in $syslog_conf; do
		[ -f "$config" ] && set_maillog $config $mail_log $inten >> $product_log 2>&1
	done

	[ -f $syslog_conf_ng ] && set_maillog_ng $mail_log $inten  >> $product_log 2>&1

	reload_syslog
}

_set_maillog_ng_change()
{
    local conf_file mail_log inten bak_ext

    conf_file=$1
    mail_log=$2
    inten=$3
    bak_ext=$4

    echo_try "$inten"

    local mloc_cmd mloc_arg
    local ws
    ws=$(echo -ne " \t")

    ## Set log in $PRODUCT_ROOT_D/var/log/maillog
    mloc_cmd="-e"
    mloc_arg='s|^\(['"$ws"']*destination['"$ws"']\+mail['"$ws"']*{[^"]*"\)[^"]*\(.*\)$|\1'"$mail_log"'\2|'

    ## By default SuSE-9.3 and SuSE-10 syslog-ng settings
    ## doesn't allow any 'mail' log messages to be put into
    ## /var/log/messages. We wish to allow mail.warn to pass
    ## through the filter, so we need to tune the conditions...
    ## So we change
    ## filter f_messages   { not facility(news, mail) and not filter(f_iptables); };
    ## to
    ## filter f_messages   { not (facility(news) or filter(f_iptables)) or filter(f_mailwarn); };
    ##
    ## I'm not sure if the whole filter is well optimized though
    ##
    ## Here I don't try to perform a sofisticated replace. The proper way
    ## would require a deep analisys of the current configuration and
    ## I don't see any sense to do it at this time, probably once in a future...

    local mfmt_cmd mfmt_arg
    mfmt_cmd=-e
    mfmt_arg='s|^\(['"$ws"']*filter['"$ws"']\+f_messages['"$ws"']*{\).*|\1 not (facility(news) or filter(f_iptables)) or filter(f_mailwarn); };|'

    ## now execute the entire command *IN-PLACE*
    ## all modern sed's (well at least on supported systems
    ## do support this option.

    ## One HAVE NOT TO quite mail_log_expr and mf_expr below!
    sed $mloc_cmd "$mloc_arg" $mfmt_cmd "$mfmt_arg" "-i$bak_ext" "$conf_file" || die "$intent"
}

set_maillog_ng() {
    local mail_log intent
    mail_log=$1
    intent=$2

	if [ -f "${syslog_conf_ng}.in" ]; then
	    _set_maillog_ng_change "${syslog_conf_ng}.in" "$mail_log" "$intent" ".bak" && 		/sbin/SuSEconfig --module syslog-ng
	else
# Modest SuSE 1.20 doens't rule syslog through SuSE-config, bug 118238
		_set_maillog_ng_change "${syslog_conf_ng}" "$mail_log" "$intent" ".bak"
	fi

}

set_maillog()
{
	local syslog_conf=$1
	mail_log=$2
	inten=$3

	mail_log_str="-$mail_log"

	echo_try "$inten"

	log_str="^mail.*[[:space:]]*$mail_log*"
	grep "$log_str" $syslog_conf > /dev/null
	if [ "$?" -ne 0 ]; then
		grep '^mail\.\*' $syslog_conf > /dev/null
		if [ "$?" -eq 0 ]; then
			## if line "mail.*       ..." is exist then
			## replace this with new line
			grep -q '^mail\.\*.*;' $syslog_conf
			if [ $? -eq 0 ]; then
				sed -e "s|^mail\.\*.*\(;.*\)$|mail.*					$mail_log_str\1|" 					< $syslog_conf > $syslog_conf.tmp
			else
				sed -e "s|^mail\.\*.*$|mail.*						$mail_log_str|" 					< $syslog_conf > $syslog_conf.tmp
			fi
			mv -f $syslog_conf.tmp $syslog_conf
		else
			## if line "mail.*       ..." is NOT exist then
			## search "*.       ..." line
			num=`awk '{if ((my==0) && (index($1, "*.") == 1)) {my=1; print FNR;}}' < $syslog_conf`
			if [ "0$num" -gt "0" ]; then
				## if line "*.       ..." is exist then
				## disable all lines beginning with "mail."
				## and insert new line "mail.*      ..." before this
				sed -e 's/^\(mail\.\)/#\1/' 					-e ''${num}'i					mail.*						'$mail_log_str'' 					< $syslog_conf > $syslog_conf.tmp && 				mv -f $syslog_conf.tmp $syslog_conf || die "$inten"
			else
				## if line "*.       ..." is NOT exist then
				## disable all lines beginning with "mail."
				## and insert new line "mail.*      ..." at the end of file
				sed -e 's/^\(mail\.\)/#\1/'	< $syslog_conf > $syslog_conf.tmp && 				echo "mail.*						$mail_log_str" >> $syslog_conf.tmp && 				mv -f $syslog_conf.tmp $syslog_conf || die "$inten"
			fi
		fi
	fi

	sed -e 's|\(^.*\)maili\none\;\(.*\)|\1\2|g' < $syslog_conf > $syslog_conf.tmp &&           mv -f $syslog_conf.tmp $syslog_conf || die "$inten"
	echo 'mail.none			-/var/log/messages' >> /var/log/messages 

	suc
}
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.

[ -z "$PLESK_INSTALLER_DEBUG" ] || set -x
[ -z "$PLESK_INSTALLER_STRICT_MODE" ] || set -e
package_script_begin_rpm
select_maillog
package_script_end_rpm
