#!/bin/bash
### Copyright 1999-2017. Plesk International GmbH. All rights reserved.
#

#
# Plesk script
#



#default values

product_default_conf()
{

PRODUCT_ROOT_D=/usr/local/psa
PRODUCT_RC_D=/etc/rc.d/init.d
PRODUCT_ETC_D=/usr/local/psa/etc
PLESK_LIBEXEC_DIR=/usr/lib64/plesk-9.0
HTTPD_VHOSTS_D=/var/www/vhosts
HTTPD_CONF_D=/etc/httpd/conf
HTTPD_INCLUDE_D=/etc/httpd/conf.d
HTTPD_BIN=/usr/sbin/httpd
HTTPD_LOG_D=/var/log/httpd
HTTPD_SERVICE=httpd
QMAIL_ROOT_D=/var/qmail
PLESK_MAILNAMES_D=/var/qmail/mailnames
RBLSMTPD=/usr/sbin/rblsmtpd
NAMED_RUN_ROOT_D=/var/named/chroot
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/python
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=true
APS_DB_DRIVER_LIBRARY=/usr/lib64/libmysqlserver.so.2
IPv6_DISABLED=false
SA_MAX_MAIL_SIZE=256000

}

is_function()
{
	local type_output=$(type -t "$1")
	test "X${type_output}" = "Xfunction"
}
### Copyright 1999-2017. Plesk International 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 "$@" >&2
}

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

# 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. Plesk International GmbH. All rights reserved.
#-*- vim:syntax=sh

product_log_name_ex()
{
	local aux_descr="$1"
	local action="${CUSTOM_LOG_ACTION_NAME-installation}"

	if [ -n "$aux_descr" ]; then
		aux_descr="_${aux_descr}"
	fi

	if [ -n "$CUSTOM_LOG_NAME" ]; then
		echo "${CUSTOM_LOG_NAME}${action:+_$action}${aux_descr}.log"
	else
		echo "plesk_17.8.11${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. Plesk International GmbH. All rights reserved.

#
# Support for runtime patching of shell scripts (including utilities and package scripts).
#

# --- Service functions ---

# Load and apply a patch in a relatively safe way
rp_safe_load_patch()
{
	local patch_file="$1"
	echo_try "load shell patch '$patch_file'"
	/bin/sh -n "$RP_BASEDIR/$patch_file" && 
	{
		. "$RP_BASEDIR/$patch_file"
		RP_LOADED_PATCHES="$RP_LOADED_PATCHES $patch_file"
	} &&
	suc
}

# Apply patches specific to the current context (e.g., depending on utility basename or package name)
# This is currently not implemented. This may be overriden by "spark".
rp_patch_runtime_context_specific()
{
	:
}

# --- Main entry points ---

rp_patch_runtime()
{
	# List of loaded patch files
	RP_LOADED_PATCHES=

	local RP_BASEDIR="$PRODUCT_BOOTSTRAPPER_DIR/rp"
	[ -d "$RP_BASEDIR" ] || return 0

	if [ -r "$RP_BASEDIR/spark" ]; then
		rp_safe_load_patch "spark"
	fi

	call_optional_function rp_patch_runtime_context_specific "$@"
}

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. Plesk International GmbH. All rights reserved.
# vim:ft=sh:

#set_params

set_common_params()
{
	common_var=0

	PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
	LANG=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/rc.d/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.8.11-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 PLESK.\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.8.11"
	product_this_version_tag="testing"
	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. Plesk International GmbH. All rights reserved.
transaction_begin()
{
	[ -n "$TRANSACTION_STARTED" ] && die "Another transaction in progress!"
	TRANSACTION_STARTED="true"
	TRANSACTION_ROLLBACK_FUNCS=
	TRANSACTION_COMMIT_FUNCS=
	local transaction_autocommit="$1"
	if [ -n "$transaction_autocommit" ]; then
		trap "transaction_commit" 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. Plesk International GmbH. All rights reserved.

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

prog="`basename $0`"
msmtp_config="/etc/msmtprc"
pwdeval_config="/etc/psa/private/msmtp-pwdeval.conf"

usage()
{
	local message="$1"
	if [ -n "$message" ]; then
		echo "ERROR: $message"
		echo
	fi

cat << EOT
Usage: $prog --mail-relay {ip|hostname} [ OPTIONS ]

    --mail-relay {ip|hostname}      Set mail relay address.
    --port {port number}            Force mail relay port. If not specified an
                                    appropriate default one will be used.
    --tls {on|off}                  Turn TLS support on/off. Default is on.
    --auth-user {SMTP user name}    Enable authentication and use a given name.
                                    Password must be specified as well.
                                    By default authentication is off and client
                                    should be in mail relay whitelist.
    --auth-passwd {SMTP password}   Set password for SMTP authentication.
                                    Only plain-text passwords are supported.
                                    A password set via this option will be 
                                    world-readable in configuration file.
                                    Consider passing password via environment
                                    variable instead (see below).
    --allow-users {ALL|SERVICE}     Which system users should be able to send
                                    mail. ALL (default) will allow all system 
                                    users. SERVICE (default if password is set
                                    via environment) will allow only service 
                                    users.
    --allow-users {user1, userN}    Explicitly set a list of comma and/or space
                                    separated users that should be able to
                                    send mail.
  Environment variables:
    PSA_PASSWORD                    Set password for SMTP authentication in
                                    plain form.
    PSA_CRYPTED_PASSWORD            Set password for SMTP authentication in 
                                    encrypted form ('sym' password type).
                                    Password set via either PSA_PASSWORD or
                                    PSA_CRYPTED_PASSWORD environment variables
                                    will be readable only by users that are 
                                    permitted to send mail (see --allow-users).
  Important notes:
    * Calling this utility overwrites configuration files entirely. Therefore
      you need to specify all desired options each time you call it.
    * Setting up SMTP authentication instead of a whitelist on relay side
      doesn't automatically free you from potential security problems on
      relay side. You need to carefully enforce security on the server side.
EOT
	exit 1
}

# --- args check ---

opt_tls="on"
opt_port=
opt_auth_user=
opt_auth_passwd=
opt_psa_passwd="$PSA_PASSWORD"
opt_psa_crypted_passwd="$PSA_CRYPTED_PASSWORD"
opt_allow_users="ALL"
[ -n "$opt_psa_passwd" -o -n "$opt_psa_crypted_passwd" ] && opt_allow_users="SERVICE"

# Note: when working with passwords use only shell builtins!
unset PSA_PASSWORD
unset PSA_CRYPTED_PASSWORD

while [ "$#" -gt 0 ]; do
	case "$1" in
		--mail-relay|-r)
			opt_mail_relay="$2"
			shift; shift
			;;
		--port|-P)
			opt_port="$2"
			shift; shift
			;;
		--tls)
			opt_tls="$2"
			shift; shift
			;;
		--auth-user|-u)
			opt_auth_user="$2"
			shift; shift
			;;
		--auth-passwd|-p)
			opt_auth_passwd="$2"
			shift; shift
			;;
		--allow-users)
			opt_allow_users="$2"
			shift; shift
			;;
		--help|-h)
			usage
			;;
		*)
			usage "Unknown argument '$1'"
			;;
	esac
done

[ -n "$opt_mail_relay" ] ||
	usage "--mail-relay option is required"
[ -z "$opt_port" ] || [ "$opt_port" -gt 0 ] 2>/dev/null ||
	usage "Invalid --port option argument, an integer in range 1-65535 expected"
[ "$opt_tls" = "on" -o "$opt_tls" = "off" ] ||
	usage "Invalid --tls option argument, 'on' or 'off expected"
[ -n "$opt_auth_user" -a \( -n "$opt_auth_passwd" -o -n "$opt_psa_passwd" -o -n "$opt_psa_crypted_passwd" \) ] || [ -z "$opt_auth_user" -a -z "$opt_auth_passwd" ] ||
	usage "Invalid --auth-* options combination, user and password should be specified simultaneously"
[ -n "$opt_allow_users" ] ||
	usage "Invalid --allow-users option argument, 'ALL', 'SERVICE' or list of users expected"
[ "$opt_allow_users" = "ALL" ] || [ -n "$opt_auth_user" -a -z "$opt_auth_passwd" ] ||
	usage "Invalid --allow-users option usage, to restrict users permitted to send mail you should specify SMTP authentication password via environment variable"

# --- logging ---

log_transaction_start "${prog}${*:+ $*}" "" "msmtpmng.log.XXXXXX"

# --- utility functions ---

mc_generate_msmtp_config()
{
	printf "${AUTOGENERATED_CONFIGS}\n"
	cat <<-EOT
		# MSMTP configuration file. See msmtp(1) for syntax.
		# This file was generated by $prog utility.

		#
		# Global settings section
		#
		defaults

		syslog LOG_MAIL

		tls_certcheck off
		tls $opt_tls

		# Automatic envelope-from generation. 
		# Caution: this overrides explicitly set envelope-from via --from or other means.
		auto_from on
		maildomain `$get_hostname`

		#
		# Default account.
		#
		account default

		host $opt_mail_relay
	EOT

	if [ -n "$opt_port" ]; then
		cat <<-EOT
			port $opt_port
		EOT
	fi

	echo

	if [ -z "$opt_auth_user" ]; then
		cat <<-EOT
			# No authentication - we should be added to relay whitelist.
			auth off
		EOT
	else
		cat <<-EOT
			auth on
			user $opt_auth_user
		EOT

		if [ -z "$opt_psa_crypted_passwd" -a -z "$opt_psa_passwd" ]; then
			cat <<-EOT
				password $opt_auth_passwd
			EOT
		else
			cat <<-EOT
				# Password is actually stored in $pwdeval_config
				passwordeval $PLESK_LIBEXEC_DIR/msmtp-pwdeval
			EOT
		fi
	fi
}

mc_generate_pwdeval_config()
{
	local prev_allow_users_list="$1"

	local allow_users_mode="LIST"
	[ "$opt_allow_users" = "ALL" ] && allow_users_mode="ALL"

	local allow_users_list=
	if [ "$opt_allow_users" = "ALL" -o "$opt_allow_users" = "SERVICE" ]; then
		allow_users_list="$prev_allow_users_list"
	else
		allow_users_list="$opt_allow_users"
	fi
	[ -n "$allow_users_list" ] || allow_users_list="root psaadm"


	printf "${AUTOGENERATED_CONFIGS}\n"
	cat <<-EOT
		# msmtp-pwdeval utility configuration file.

		# allow_users {ALL|LIST} - whether to restrict users that are able to send mail to allow_users_list (LIST) or not (ALL).
		allow_users $allow_users_mode

		# allow_users_mode {comma and/or space separated list of system users} - list of users that are allowed to send mail.
		# This is the only customizable parameter in this configuration file! All other parameters would be unconditionally 
		# overwritten by Plesk next time this file is updated. Note that this value is not guaranteed to be preserved after
		# upgrade (in case it becomes customizable via Plesk). 
		# Initial value: 'root psaadm'.
		allow_users_list $allow_users_list

	EOT

	if [ -n "$opt_psa_crypted_passwd" ]; then
		cat <<-EOT
			# password {password} - SMTP authentication password for mail relay.
			password $opt_psa_crypted_passwd

			# password_type {plain|sym} - SMTP authentication password type (as in Plesk DB).
			password_type sym
		EOT
	elif [ -n "$opt_psa_passwd" ]; then
		cat <<-EOT
			# password {password} - SMTP authentication password for mail relay.
			password $opt_psa_passwd

			# password_type {plain|sym} - SMTP authentication password type (as in Plesk DB).
			password_type plain
		EOT
	fi
}

mc_write_config()
{
	{
		local prev_allow_users_list="`sed -ne 's/^\s*allow_users_list\s\+\(.*\)\s*$/\1/p' $pwdeval_config | tail -n1`"

		mc_generate_msmtp_config > "$msmtp_config" &&
			touch "$pwdeval_config" && set_ac 0 0 0600 "$pwdeval_config" &&
			mc_generate_pwdeval_config "$prev_allow_users_list" > "$pwdeval_config"
	} 2>>"$product_problems_log"
}

# --- workers ---

mc_do_write_config()
{
	mc_write_config
	mc_retval="$?"
	[ "0$mc_retval" -eq 0 ] || pp_echo "Failed to overwrite MSMTP configuration file. Please check that '$msmtp_config' is accessible. See '$product_log' log for details."
	return $mc_retval
}

# --- the script ---

product_default_conf
read_conf
set_common_params

mc_do_write_config

if [ "$mc_retval" = "0" ]; then
	rm -f "$product_log"
fi

exit $mc_retval

# vim:ft=sh:
