#!/bin/sh
#
# Copyright (c) 1999-2008 Parallels
# All rights reserved
#

#
# Plesk script
#


# Migration manager tables will be managed by plesk
migrate_pmm_management_db_into_core_1011()
{
	if ! db_test_table "PMM" || ! db_test_table "PMMDefault"; then
		$mysql < ${PRODUCT_BOOTSTRAPPER_DIR}/db/pmm_db.sql
		[ "$?" = "0" ] || die "install PMM tables during upgrade"
	fi
}
# vim:syntax=sh

generate_encryption_key()
{
	local key_file="/etc/psa/private/secret_key"
	local key_dir="`dirname $key_file`"
	local rc=0

	[ -d "$key_dir" ] || mkdir -p "$key_dir"

	if [ ! -e "$key_file" ]; then
		dd if=/dev/urandom of="$key_file" bs=16 count=1 2>/dev/null
	else
		rc=1
	fi
	fix_key_permissions
	return $rc
}

fix_key_permissions()
{
	local key_file="/etc/psa/private/secret_key"
	local key_dir="`dirname $key_file`"

	if [ -e "$key_file" ]; then
		chown psaadm:0 "$key_file"
		chmod 0600 "$key_file"
	fi

	if [ -d "$key_dir" ]; then
		chown psaadm:0 "$key_dir"
		chmod 0700 "$key_dir"
	fi
}

#admin

set_admin_params()
{

	ADMIN_ROOT=$PRODUCT_ROOT_D/admin

	UTILS_DIR=$ADMIN_ROOT/bin

	admin_user="${product}adm"
	admin_UID=8444
	admin_group="${product}adm"
	admin_GID=8444

	admin_httpsd_conf="$ADMIN_ROOT/conf/httpsd.conf"
	ADMIN_CERT="$ADMIN_ROOT/conf/httpsd.pem"

	admin_pid_file=$ADMIN_ROOT/logs/httpsd.pid
	admin_lock_file=$ADMIN_ROOT/logs/httpsd.lock

	define_start_script
}

lock_keyupdate()
{
	export PLESK_KEYUPDATE_DISABLED=installation
}

## @@constructor set_admin_params
## @@constructor lock_keyupdate

set_admin_perms()
{
   	#remove stale file
	rm -f "$ADMIN_ROOT/htdocs/index.php3"

#	if [ "X$machine" != "Xlinux" -o "X$linux_distr" = "Xdebian" ]; then
#		set_admin_additional_perms
#	fi


	available_certificates=`ls -1 $ADMIN_ROOT/conf/*.pem* 2>/dev/null`
	if [ "X${available_certificates}" != "X" ]; then
		for i in ${available_certificates}; do
			chown 0:0 $i || die
			chmod 400 $i || die
		done
	fi

	[ -d $ADMIN_ROOT/man ] &&
	set_ac 0 $admin_group 755 "$ADMIN_ROOT/man/*" &&
	for i in `find $ADMIN_ROOT/man -type d -print`; do
		set_ac root $admin_group 755 "$i"
		set_ac root $admin_group 644 "$i/*"
	done

	[ -d ${DUMP_D} ] &&
		set_ac $admin_user $admin_group 755 ${DUMP_D}

	#set locales permissions
	for dir in htdocs plib; do
		chmod -R 644 "$ADMIN_ROOT/$dir/locales"
		find "$ADMIN_ROOT/$dir/locales" -type d -exec chmod 755 {} \;
	done

	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		set_ac root $admin_group 775 "$ADMIN_ROOT/htdocs/images/custom_buttons"
	else
		set_ac root $admin_group 4110 "$ADMIN_ROOT/sbin/wrapper"
		set_ac root $admin_group 4110 "$ADMIN_ROOT/sbin/mod_wrapper"
	fi
}

set_admin_additional_perms()
{
	cd "$PRODUCT_ROOT_D" || die

	chown root:0 "$ADMIN_ROOT/conf/ssl.crt"
	chmod 755 "$ADMIN_ROOT/conf/ssl.crt"

	# for BSD/OS 3.x apache can't use DSO, and there isn't libexec dir
	if [ -d "$ADMIN_ROOT/libexec" ]; then
		set_ac root $admin_group 555 "$ADMIN_ROOT/libexec/*"
		set_ac root $admin_group 444 "$ADMIN_ROOT/libexec/httpd.exp"
	fi

	####################################################
	### SETTING OWNER FOR PHP FILES (bugfix #50597)
	### TODO: it should be deprecated in nearest future
	chown -Rh root:0 $ADMIN_ROOT/htdocs
	chown -Rh root:0 $ADMIN_ROOT/plib
	chown -Rh root:0 $ADMIN_ROOT/compat
	chown -Rh root:0 $ADMIN_ROOT/javascripts
	chown -Rh root:0 $ADMIN_ROOT/auto_prepend

	set_ac root $admin_group 550 "$ADMIN_ROOT/bin"
	set_ac root $admin_group 550 "$ADMIN_ROOT/bin/*"

	set_ac root $admin_group 550 "$ADMIN_ROOT/sbin"
	set_ac root $admin_group 550 "$ADMIN_ROOT/sbin/*"
	set_ac root $admin_group 550 "$ADMIN_ROOT/sbin/server_df"

	set_ac $admin_user $admin_group 755 "$PRODUCT_ROOT_D/var"

	for i in `find $ADMIN_ROOT/conf/ssl.crt -type l -print`; do
		chown -h root:0 "$i"
		chmod 755 "$i"
	done
}

admin_start()
{
	inten="start Admin server"
	echo_try $inten

	if [ "X$machine" = "XBSD" ]; then 
		$START_SH start >> $product_log 2>&1 && suc || die $inten
	else
		$START_SH start1 >> $product_log 2>&1 && suc || die $inten
	fi
}

admin_stop()
{
	inten="stop Admin server"
	echo_try $inten

	if [ "X$machine" = "XBSD" ]; then 
		$START_SH stop >> $product_log 2>&1 && suc || warn $inten
	else
		$START_SH stop1 >> $product_log 2>&1 && suc || warn $inten
	fi
}

install_admin()
{
	p_echo

	p_echo "===> Installing Admin Server"

	# set default permissions on $ADMIN_ROOT and his contents
	set_admin_perms

	# installation
	cd "$PRODUCT_ROOT_D" || die

	get_pid $ADMIN_ROOT/bin/httpsd true root
	req_pid=$common_var
	if [ $req_pid -gt 1 ]; then
		inten="stop running Admin server"
		echo_try $inten
		kill_pids $ADMIN_ROOT/bin/httpsd root
		if [ -f "$admin_lock_file.*" ]; then
			rm -f "$admin_lock_file.*" >> $product_log 2>&1
		fi
		if [ -f "$admin_pid_file" ]; then
			rm -f "$admin_pid_file"
		fi
		suc
	fi


	if [ ! -s "$ADMIN_CERT" ] ;then
		inten="copy default SSL Certificate for admin server"
		echo_try $inten
		get_certificate "$ADMIN_CERT" || die $inten
		set_ac 0 0 0400 "$ADMIN_CERT"
		suc
	fi

	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		chown 0:psaadm $ADMIN_CERT || die
		chmod 440 $ADMIN_CERT || die
	else
		chown 0:0 $ADMIN_CERT || die
		chmod 400 $ADMIN_CERT || die
	fi
}

get_certificate()
{
	local dst="$1"
	local src="${certificate_file}"
# Check or generate new default certificate
	[ -s "$src" ] || generate_default_certificate
 	set_ac 0 0 0400 "${src}"
	cp -fp $src $dst
}

generate_default_certificate()
{
	# Currently I have no will to accurately rewrite the stuff below
	# so I just add support for (optional) file parameter. Actually
	# one need to accurately handle temporary files, directory creation
	# etc. Probably next time...
	local cert_file

	cert_file="${certificate_file}"
	if [ -s "$cert_file" ]; then
		p_echo "default certificate already exists"
		return
	fi

	# This var also can safely be made local. It's not used outside
	local OPENSSL_CNF is_temp_cnf rc

	OPENSSL_CNF=${PRODUCT_ROOT_D}/admin/conf/openssl.cnf
	is_temp_cnf=0

	if [ ! -f "${OPENSSL_CNF}" ]; then
		# Well, base psa package isn't yet installed. 
		# let's form a temporary config file
		OPENSSL_CNF=$(mktemp /tmp/openssl.cnf.XXXXXX)
		[ $? != 0 ] && die "Unable to create temporary file"
		cat >>${OPENSSL_CNF} <<EOF
[ req ]
attributes=req_attributes
distinguished_name=req_distinguished_name

[ req_attributes ]
challengePassword               = A challenge password
unstructuredName                = An optional company name

[ req_distinguished_name ]
countryName             = Country Name
stateOrProvinceName     = State or Province Name
localityName            = Locality Name
organizationName        = Organisation Name
organizationalUnitName  = Organization Unit Name
commonName              = Common Name
emailAddress            = Email Address
EOF
		is_temp_cnf=1
	fi

	echo "US
Virginia
Herndon
Parallels
Parallels Panel
Parallels Panel
info@parallels.com


" | openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
	-config ${OPENSSL_CNF} -set_serial `date +%s` -keyout "${cert_file}_" \
	-out "${cert_file}_" >> $product_log 2>&1

	# preserve exit code
	rc=$?

	if [ $rc -eq 0 ]; then
		cat "${cert_file}_" | sed -e 's/^\(-----END.*\)/\1\
/' > $cert_file
		set_ac 0 0 0400 "${cert_file}"
	fi
	# cleanup temporary files
	rm -f "${cert_file}_" ||:
	if [ "x$is_temp_cnf" = "x1" ]; then
		rm -f ${OPENSSL_CNF} ||:
	fi
	return $rc
}


register_the_old_key()
{
	local prev_key
	prev_key="$1"

	echo "Register backup $prev_key" >>"$product_log"
	ln -sf "$prev_key" "$prodkey" || die "$inten"
	export PLESK_ALLOW_BINARY_KEY=1
	export PLESK_ALLOW_KEY_VERSION_MISMATCH=1
	admin_start >/dev/null 2>&1
	unset PLESK_ALLOW_BINARY_KEY
	unset PLESK_ALLOW_KEY_VERSION_MISMATCH
	admin_stop >/dev/null 2>&1
	rm -f "$prodkey" || die "$inten"
}

register_old_keys()
{
	local prodkey_backup prev_key
	inten="register old keys"
	prodkey_backup=`mktemp "$prodkey.XXXXXXXX"`
	echo_try "$inten"
	echo >>"$product_log"
	mv -f "$prodkey" "$prodkey_backup" || die "$inten"
	ls "$prodkey.saved."*.*";"*:* |sort|while read prev_key; do
		register_the_old_key "$prev_key"
	done
	register_the_old_key "$prodkey_backup"
	mv "$prodkey_backup" "$prodkey" || die "$inten" 
	suc
}
set_apache_params()
{
	apache_user="wwwrun"
	apache_UID=80
	apache_group="www"
	apache_GID=80

	user_apxs="/usr/sbin/apxs2"

	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/local/psa/suexec
	suexec=/usr/sbin/suexec2
	suexec_dir=/usr/sbin
	suexec_file=suexec2

	rpm_httpd_bin=/usr/sbin/httpd
}

set_apache_params_freebsd()
{
	apache_pid_file="/var/run/httpd.pid"
	apache_lock_file="/var/run/httpd.pid.lock"
	product_lock_file="/var/run/cnf.lock"

	#make detect apache version in runtime
	is_apache20="`pkg_info -qO www/apache20`"
	is_apache22="`pkg_info -qO www/apache22`"

	if [ ! -z "$is_apache20" -a ! -z "$is_apache22" ]; then
	    p_echo "Two or above apache detected into system."
	    p_echo "Possibly package database is incorrect."
	    die "Please make run 'pkgdb -Fu command to fix database."
	elif [ ! -z "$is_apache20" ]; then
	    apache_suffix="apache2"
	elif [ ! -z "$is_apache22" ]; then
	    apache_suffix="apache22"
	else
	    p_echo "Unable to detect apache version"
	    die "Make sure that apache server was installed into your machine"
	fi

	if [ -f "$PRODUCT_RC_D/${apache_suffix}.sh" ]; then
	    apache_service_name="${apache_suffix}.sh"
	else
	    apache_service_name="$apache_suffix"
	fi

	#need to look
	HTTPD_CONF_D="/usr/local/etc/$apache_suffix"
	HTTPD_INCLUDE_D="$HTTPD_CONF_D/Includes"
	apache_modules_d="/usr/local/libexec/$apache_suffix"
}

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="apache2"

	apache_modules_d="/usr/lib64/apache2"
}

## @@constructor set_apache_params

fix_apache_path()
{
    fix_apache_path_linux
}

fix_apache_path_linux()
{
    :
}

# Warning. Almost hack. e.g. nedoficha. 
# Use dynamic detect apache version 
# and replace some entities into config file
fix_apache_path_freebsd()
{
    if [ ! -f $prod_conf_t ]; then
	return 0
    fi
  
    cp -f $prod_conf_t ${prod_conf_t}.bak

    awk -v var1=$HTTPD_CONF_D -v var2=$HTTPD_INCLUDE_D -v var3=$apache_service_name '	/^HTTPD_CONF_D/ {print $1" "var1; next;} 	/^HTTPD_INCLUDE_D/ {print $1" "var2; next;} 	/^HTTPD_SERVICE/  {print $1" "var3; next;} 	{print;}     ' ${prod_conf_t}.bak > $prod_conf_t
}

# mode: shell-script

remove_tmp_state()
{
	if [ -d "/tmp/.state" ]; then
		rm -Rf "/tmp/.state" >> $product_log 2>&1
	fi
}

set_apache_accounts()
{
    p_echo " Checking for the system groups and users necessary for Apache..."

    case "$machine" in
      Darwin)
        group_op "$apache_group" "$apache_GID" false
        user_op "$apache_user" "$apache_UID" "$apache_group" "Apache server" "$dummy_home" "$dummy_shell" false
      ;;
      *)
        group_op "$apache_group" "$apache_GID" false
        user_op "$apache_user" "$apache_UID" "$apache_group" "Apache server" "$dummy_home" "$dummy_shell" false
      ;;
    esac
}

set_ssl_certs()
{
    # Upgrader should not touch SSL Certificate
    if [ "X$do_upgrade" != "X1" -o "X$std_to_pkg" = "X1" ]; then
	if [ ! -f "$APACHE_CERT" ]; then
		inten="copy default SSL Certificate for Apache"
		echo_try $inten
		cp -fp "$certificate_file" "$APACHE_CERT" || die $inten
		chown 0:0 "$APACHE_CERT" || die "chown $APACHE_CERT"
		chmod 400 "$APACHE_CERT" || die "chmod $APACHE_CERT"
		suc
	fi

	if [ "$machine" = "BSD" ]; then 
	    case $apache_suffix in
		apache22)
			ssl_conf="$HTTPD_CONF_D/extra/httpd-ssl.conf"

			#uncomment Include http-ssl
			if [ -f "$apache_httpd_conf" ]; then
			    mv -f $apache_httpd_conf ${apache_httpd_conf}.default
			    cat ${apache_httpd_conf}.default | awk -F '#' '
				/Include .*httpd-ssl\.conf/ {print $2; next} 
				{print;}
			    ' > $apache_httpd_conf
			fi
		;;
		apache2)
			ssl_conf="$HTTPD_CONF_D/ssl.conf"
		;;
		*)
			warn "Unable to find config file for ssl extras"
			return 0  
		;;
	    esac
	 
	    if [ -f "$ssl_conf" -a ! -z "$ssl_conf" ]; then
		mv $ssl_conf ${ssl_conf}.default
	 
		cat ${ssl_conf}.default | 		perl -e '@lines=<STDIN>;
		    $flag=0;
		    foreach $tmp (@lines) {
			if ($tmp =~ /^<VirtualHost.*>/) {$flag=1; next;}
			if ($tmp =~ /^<\/VirtualHost.*>/) {$flag=0; next; }
			unless ($flag) { print $tmp; }   
		}' > $ssl_conf
	    fi
	fi
    fi
}

set_apache_perms()
{
	inten="set up default apache permissions"
	echo_try $inten

	chown -R 0:0 "$APACHE_ROOT"

	[ -e $APACHE_ROOT/conf/ssl.key ] && chown $apache_user:$apache_group "$APACHE_ROOT/conf/ssl.key"
	[ -e $APACHE_ROOT/proxy ] && chown $apache_user:$apache_group "$APACHE_ROOT/proxy"

	remove_tmp_state

	suc
}

apache_optim()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		return 0;
	fi

	case "$machine" in

		linux)
			#p_echo "===> Optimization Apache server"
			info_cpu=`cat /proc/cpuinfo |grep 'model name'|awk '{print $4}' -`
			info_mod=`cat /proc/cpuinfo |grep 'model name'|awk '{print $5}' -`
			info_num=`cat /proc/cpuinfo |grep 'processor'|awk '{print $3}' -`

			case "$info_num" in

			0)
				case "$info_cpu" in

				Celeron | 				05/06 )
    				sed -e "s/MaxClients[[:space:]]*640/MaxClients 256/g"     					< $apache_httpd_conf > $apache_httpd_conf.tmp
					mv -f $apache_httpd_conf.tmp $apache_httpd_conf
					;;
				*)
					;;
				esac
				;;

			*)
				sed -e "s/MaxClients[[:space:]]*640/MaxClients 1024/g" 			    	< $apache_httpd_conf > $apache_httpd_conf.tmp
				mv -f $apache_httpd_conf.tmp $apache_httpd_conf
				;;

			esac
			;;

		*)
			;;
    esac
}

apache_conf_add_dirindex()
{
        index_str="^[[:space:]]*DirectoryIndex.*[[:space:]]$1\\(\$\\|[[:space:]]\\)"
        if ! grep -q "$index_str" "$2"; then
                case "$3" in
                        after) sed -e "s|^[[:space:]]*DirectoryIndex.*\$|& $1|" ;;
                        before) sed -e "s|^\\([[:space:]]*DirectoryIndex[[:space:]]*\\)\\(.*\\)|\\1$1 \\2|" ;;
                        *) false ;;
                esac < "$2" > "$2.tmp" || die "insert $1 in DirectoryIndex directive into $2 file"
                mv -f "$2.tmp" "$2" || die "replace initial $2 file"
        fi
}

apache_conf_add_type_shtml()
{
    local config="$1"

    add_string 'AddType[[:space:]]*text/html[[:space:]]*\.shtml' 		"AddType text/html .shtml" "$config"

}

apache_conf_add_type_php()
{
    local config="$1"
    add_string 'AddType[[:space:]]*application/x-httpd-php[[:space:]]*\.php' 		"AddType application/x-httpd-php .php" "$config"
		
    add_string 'AddType[[:space:]]*application/x-httpd-php-source[[:space:]]*\.phps' 		"AddType application/x-httpd-php-source .phps" "$config"
}

apache_conf_comment_AddDefaultCharset()
{
	local config="$1"

	sed -e "s/^\(AddDefaultCharset\)/#\1/g" 		< $config > $config.tmp
	mv -f $config.tmp $config

}

apache_insert_include()
{
	local target_conf="$1"
	local include_str="Include[[:space:]]*conf/zz010_psa_httpd.conf"
	if ! grep -q "$include_str" $target_conf; then
		include_str="Include[[:space:]]*${apache_httpd_include}"
		if ! grep -q "$include_str" $target_conf; then
			include_str="*.conf"
			if ! grep -q "$include_str" $target_conf; then
				echo "" >> $target_conf
				echo "Include ${apache_httpd_include}" >> $target_conf 					|| die "insert include directive into $target_conf file"
			fi
		fi
	fi
}

apache_remove_include()
{
	local target_conf="$1"
	#remove old string
	local include_str="Include[[:space:]]*(/etc.*)?/httpd.include"
	grep -v -E "$include_str" $target_conf > $target_conf.tmp
	mv -f $target_conf.tmp $target_conf
	[ -f "$HTTPD_CONF_D/httpd.include.new" ] && rm -f "$HTTPD_CONF_D/httpd.include.new"
	[ -f "$HTTPD_CONF_D/httpd.include" ] && mv -f "$HTTPD_CONF_D/httpd.include" "$HTTPD_CONF_D/httpd.include_old_plesk_config"
	#remove new string
	local include_str="Include[[:space:]]*conf/zz010_psa_httpd.conf"
	grep -v "$include_str" $target_conf > $target_conf.tmp
	mv -f $target_conf.tmp $target_conf
}

apache_conf_addon()
{
	local target_conf
	if [ -f $apache_httpd_conf2 ]; then
		target_conf="$apache_httpd_conf2"
	else
		target_conf="$apache_httpd_conf"
	fi

	apache_conf_add_dirindex index.shtml $target_conf after
	apache_conf_add_dirindex index.cfm $target_conf after
	apache_conf_add_dirindex index.php $target_conf after
	apache_conf_add_dirindex index.htm $target_conf after

	apache_conf_add_type_shtml $target_conf
	apache_conf_add_type_php $target_conf

	apache_conf_comment_AddDefaultCharset $target_conf

	apache_insert_include $target_conf
}

apache2_conf_addon()
{
	local target_conf
	if [ -f $apache_httpd_conf2 ]; then
		target_conf="$apache_httpd_conf2"
	else
		target_conf="$apache_httpd_conf"
	fi

	add_string 'GracefulShutDownTimeout[[:space:]]*[0-9]*' 		"GracefulShutDownTimeout 3" $target_conf

	add_string 'AddOutputFilter[[:space:]]*INCLUDES[[:space:]]*\.shtml' 		"AddOutputFilter INCLUDES .shtml" $target_conf

	apache_remove_include $target_conf
	insert_load_module_logio $target_conf

	# This must be the last statement in the function
	apache_conf_addon
}

apache_platform_dependent()
{
	# for Mandrake
		apache_commonhttpd_conf="$HTTPD_CONF_D/commonhttpd.conf"
		if [ -f $apache_commonhttpd_conf ]; then
			apache_conf_add_dirindex index.shtml $apache_commonhttpd_conf after
			apache_conf_add_dirindex index.cfm $apache_commonhttpd_conf after
		fi

	# for SuSE
		apache_listen_conf="$HTTPD_CONF_D/listen.conf"
		apache_mime_default="$HTTPD_CONF_D/mod_mime-defaults.conf"
		if [ -f $apache_mime_default ]; then
			apache_conf_comment_AddDefaultCharset $apache_mime_default
			add_string 'AddOutputFilter[[:space:]]*INCLUDES[[:space:]]*\.shtml' 				"AddOutputFilter INCLUDES .shtml" $apache_mime_default
		fi

	# for Debian
		apache_listen_conf="$HTTPD_CONF_D/ports.conf"
		dir_index_conf="$HTTPD_CONF_D/mods-enabled/dir.conf"
		if [ -f $dir_index_conf ]; then
			apache_conf_add_dirindex at_domains_index.html $dir_index_conf before
			apache_conf_add_dirindex index.shtml $dir_index_conf after
			apache_conf_add_dirindex index.cfm $dir_index_conf after
			apache_conf_add_dirindex index.php $dir_index_conf after
			apache_conf_add_dirindex index.htm $dir_index_conf after
		fi

	# Add mod_ssl and mod_headers in Debian
	add_apache_module ssl
	add_apache_module headers

	# Add mod_python for FreeBSD
	if [ "X$machine" = "XBSD" ]; then
		add_apache_module python
	fi

}

install_apache()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		return 0;
	fi

	p_echo
	p_echo "===> Installing Apache Server"

	fix_apache_path
	pleskrc apache stop

	pnnl_echo " Copying apache files... "

	if [ -f "$apache_httpd_conf_in" -a ! -f "$apache_httpd_conf2" ]; then
		if [ -f "$apache_httpd_conf" ]; then
			mk_backup $apache_httpd_conf cp f
		fi
		if [ ! -f "$apache_httpd_conf" ]; then
			cp "$apache_httpd_conf_in" "$apache_httpd_conf" || die "copy httpd.conf file"
			sed -e "s|wwwrun|$apache_user|g" 				-e "s|www|$apache_group|g" 				-e "s|/srv/www/vhosts|$HTTPD_VHOSTS_D|g" 				-e "s|/usr|$APACHE_ROOT|g" 				< "$apache_httpd_conf_in" > "$apache_httpd_conf" || die
			apache_optim
		fi
	fi

	apache2_conf_addon

	# Insert things for other linux platforms
	apache_platform_dependent

	echo "ServerName $fullhost" > $apache_httpd_include 		|| die "initialize $apache_httpd_include file"

	suc

	set_ssl_certs
	
	touch /etc/apache2/sysconfig.d/include.conf || :

	# Upgrade cannot handle this situation correctly because of old database
	if [ "X${do_upgrade}" != "X1" ]; then
	    inten="reconfigure Apache"
	    echo_try $inten
	    $PRODUCT_ROOT_D/admin/sbin/httpdmng --reconfigure-all  >> $product_log 2>&1 && suc || warn "$inten. Please rerurn $PRODUCT_ROOT_D/admin/sbin/httpdmng --reconfigure-all manually"
	fi

	add_manpath "$APACHE_ROOT/man"

	move_sitebuilder_conf

}

insert_load_module_logio()
{
	local sysconfig_apache2='/etc/sysconfig/apache2'
        local modules_d=`basename $apache_modules_d`

	if [ -f "$sysconfig_apache2" ]; then
		# If $sysconfig_apache2 exists, then we are on SLES,
		# and the module has been added by the stub in psa.spec.
		true
	elif [ -d "${HTTPD_CONF_D}/mods-available" -a -d "${HTTPD_CONF_D}/mods-enabled" ]; then
		# Debian
		if [ -f "${HTTPD_CONF_D}/mods-available/logio.load" ]; then
			ln -sf "${HTTPD_CONF_D}/mods-available/logio.load" 				"${HTTPD_CONF_D}/mods-enabled/logio.load"
		fi # Otherwise, the logio module is built into Apache
	else
		if [ "$conceived_os_vendor" != "RedHat" ]; then
			add_apache_module logio
		fi # RedHat 9 and RHAS 3 don't have mod_logio.so, we ignore this
	fi
}

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

		if [ -x /usr/sbin/a2enmod ]; then
			/usr/sbin/a2enmod $module_name
		else
			warn "a2enmod utilily not found! Module $module_name was NOT enabled."
		fi
}

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

		if [ -x /usr/sbin/a2dismod ]; then
			/usr/sbin/a2dismod $module_name
		else
			warn "a2dismod utilily not found! Module $module_name was NOT disabled."
		fi
}



apache_status_linux_debian()
{
	get_pid "/usr/sbin/apache2" false
	local pid=$common_var
	if test "$pid" -ne 1; then
# running
		return 0
	fi
	return 1
}

apache_stop_BSD()
{
	local apache_script

	if [ "$std_to_pkg" -ne 0 ]; then
		apache_script="$PRODUCT_ROOT_D/rc.d/httpd"
	else
		apache_script="$PRODUCT_RC_D/$apache_service_name"
	fi

	$apache_script stop 2>/dev/null
}

defer_apache_reconfiguration()
{
	apache_need_reconfiguration="yes"
}

reconfigure_apache_if_needed()
{
	local httpdmng="$PRODUCT_ROOT_D/admin/sbin/httpdmng"
	[ -n "$apache_need_reconfiguration" ] || return
	if [ -x "$httpdmng" ]; then
		echo_try "reconfigure webserver (all)"
		"$httpdmng" --reconfigure-all >> $product_log 2>&1
		if [ $? -ne 0 ]; then
			warn "webserver reconfiguration, maybe will attempt later"
		else
			unset apache_need_reconfiguration
		fi
	fi
}
# vim:syntax=sh

set_memory_limit()
{
	local newmeml="32M"
	local inten="set memory limit to $newmeml"
	echo_try $inten

	local meml=`get_phpini_var "memory_limit"`

	if [ -z "$meml" ]; then
		p_echo "Unable to find 'memory_limit' variable in $php_ini"
		p_echo "Add new entry"
		meml="0M"
	fi

	if [ "${meml%%M}" -lt "${newmeml%%M}" ]; then
		set_phpini_var 'memory_limit' "$newmeml"
	fi
	suc
}

set_max_execution_time_limit()
{
	local new="60"
	local inten="set max_execution_time to $new"
	echo_try $inten

	local old=`get_phpini_var "max_execution_time"`

	if [ -z "$old" ]; then
		p_echo "Unable to find 'max_execution_time' variable in $php_ini"
		p_echo "Add new entry"
		old="0"
	fi

	if [ "$old" -lt "$new" ]; then
		set_phpini_var 'max_execution_time' "$new"
	fi
	suc
}

set_upload_max_filesize()
{
	local new="128M"
	local inten="set upload_max_filesize to $new"
	echo_try $inten

	local old=`get_phpini_var "upload_max_filesize"`

	if [ -z "$old" ]; then
		p_echo "Unable to find 'upload_max_filesize' variable in $php_ini"
		p_echo "Add new entry"
		old="0M"
	fi

	if [ "${old%%M}" -lt "${new%%M}" ]; then
		set_phpini_var 'upload_max_filesize' "$new"
	fi
	suc
}

set_include_path()
{
	local inten="add '.' to 'include_path'"
    echo_try $inten

	local incpath=`get_phpini_var "include_path"`

	if [ ! -z "$incpath" ]; then
		IFS_OLD=$IFS
		IFS=':'
		for i in $incpath; do
			if [ "x$i" = "x." ]; then
				IFS=$IFS_OLD;
				p_echo "nothing to be done"
				suc
				return
			fi
		done
		IFS=$IFS_OLD;
	else
		p_echo "Unable to find 'include_path' variable in $php_ini"
		p_echo "Adding new entry"
	fi

	set_phpini_var 'include_path' '".:'"$incpath"'"'
	suc
}

set_session_path()
{
    echo_try "define 'session.save_path'"

    local arg='session.save_path'
    local path="/tmp"

    grep -q "^$arg" $php_ini || 	cat $php_ini | awk -v var1="$arg" -v var2="$path" '
	    /^\[Session\]/ {
		printf("%s \n\n%s = \"%s\"\n\n", $0, var1, var2);
		next;
	    }
	    {print;}
	' > ${php_ini}.tmp

    mv -f ${php_ini}.tmp $php_ini

    grep -q "^$arg" $php_ini && suc || fail
}

set_php_session_save_path_perms()
{
	[ -r "$php_ini" ] || return
	local session_save_path=`php -c "$php_ini" -r "echo ini_get('session.save_path');" 2>/dev/null || get_phpini_var "session.save_path"`
	[ -n "$session_save_path" -a -d "$session_save_path" ] || return
	[ "$session_save_path" = "/var/lib/php/session" -o "$session_save_path" = "/var/lib/php5" ] || return

	set_ac root 0 1733 "$session_save_path"
}

set_shortag()
{
	local inten="set 'short_open_tag' to On"
    echo_try $inten

	local shorttag=`get_phpini_var "short_open_tag"`
    if [ -z "$shorttag" ]; then
        p_echo "Unable to find 'short_open_tag' variable in $php_ini"
		p_echo "Adding new entry"
    fi
	set_phpini_var 'short_open_tag' 'On'
	suc
}

set_fileuploads()
{
    local inten="set 'file_uploads' to On"
    echo_try $inten

    local fileuploads=`get_phpini_var "file_uploads"`
    if [ -z "$fileuploads" ]; then
        p_echo "Unable to find 'file_uploads' variable in $php_ini"
        p_echo "Adding new entry"
    fi
    set_phpini_var 'file_uploads' 'On'
    suc
}

set_expose_php()
{
	local inten="set 'expose_php' to Off"
	echo_try $inten

	local expose=`get_phpini_var "expose_php"`
	if [ -z "$expose" ]; then
		p_echo "Unable to find 'expose_php' variable in $php_ini"
		p_echo "Adding new entry"
	fi

	set_phpini_var 'expose_php' 'Off'
	suc
}

move_zend_extensions_to_conf_d()
{

	local php_d="$1"
	local php_inis="$2"
	local ext_conf="zend_extensions_psa.ini"

	[ -d "$php_d" ] || return 1

	echo_try "move Zend extensions from php.ini to conf.d/$ext_conf (except ionCube) if any"

	perl -n -i.bak -e '
		use strict;
		use warnings;

		sub canonize {					# strip comments and excessive spaces
			my $line = shift;
			$line =~ s|\s+| |g;
			$line =~ s|;.*$||;
			$line =~ s|^\s+||;
			$line =~ s|\s+$||;
			$line =~ s|^(\S*)\s*=\s*(.*)$|$1 = $2|;
			return $line;
		}

		BEGIN {
			our @moved;
			open(our $MOVED, "+>>", "'"$php_d/$ext_conf"'") or die $!;
			seek($MOVED, 0, 0);
			while (<$MOVED>) {			# populate @moved with canonized (zend_)?extension* lines from .ini file
				my $cline = canonize($_);
				next unless $cline;		# skip empty and comment lines
				push(@moved, $cline);
			}
			seek($MOVED, 0, 2);
			if (tell($MOVED) == 0) {	# file was just created - print header
				print $MOVED "; Following directives were moved from php.ini files by Plesk to avoid load order errors\n";
				print $MOVED "; Please do not add any zend_extension* or extension directives directly into php.ini\n";
			}
		}

		use vars qw(@moved $MOVED);
		print and next unless /^\s*(zend_)?extension(_debug)?(_ts)?\s*=/;	# do not modify anything other than (zend_)?extension* lines
		print and next if     /^\s*(zend_)?extension(_debug)?(_ts)?\s*=\s*.*ioncube_loader.*\.so/;	# do not move custom ionCube loader lines - it is ion_loader.sh responsibility
		my $line = $_;
		my $cline = canonize($_);
		s|(.*)|;$1\t; moved to conf.d/'"$ext_conf"' by Plesk|; print;		# comment out (zend_)?extension* lines
		print $MOVED $line unless (grep {$_ eq $cline} @moved);				# move allowed lines to separate .ini file unless they are already there
		push(@moved, $cline);
	' $php_inis < /dev/null || {
		p_echo "failed"
		echo_try "restore php.ini files"

		for conf in $php_inis; do
			[ -f "$conf.bak" ] && mv -f "$conf.bak" "$conf"
		done

		suc
		warn "Your PHP configuration may now contain duplicate zend_extension* directives. You may wish to fix it if 'php -v' outputs relevant warnings."

		return 1
	}

	echo_try "remove php.ini backup files"

	for conf in $php_inis; do
		[ -f "$conf" ] && rm -f "$conf.bak"
	done

	suc
}

set_suexec_perms()
{
	set_ac root ${apache_group} 4510 $suexec
}

install_suexec()
{
	[ -f "$suexec_storage/$PRODNAME-$suexec_file" ] || return 0

	p_echo "===> Installing $suexec replacement"
	if [ -x "/usr/sbin/dpkg-divert" ]; then
		dpkg-divert --package psa --add --rename \
					$suexec  >> $product_log 
	else
		local inten="backup original $suexec"
		echo_try $inten
		if [ -f $suexec ]; then
			rm -f $suexec.$product_suffo
			cp -fp $suexec $suexec.$product_suffo
			rm -f $suexec
		else
			warn "$inten"
			echo "Original suexec ($suexec) not found" >> $product_log
		fi
		suc
	fi
	cp -pfv	$suexec_storage/$PRODNAME-$suexec_file $suexec >>$product_log

	set_suexec_perms

	case $machine in
	    BSD*)
		which httpd || die "Unable to find apache server"	
		$HTTPD_BIN -V | grep -q SUEXEC_BIN
		if [ "$?" -ne "0" ]; then 
		    add_apache_module "suexec"
		fi
	    ;;
	    *)
		    add_apache_module "suexec"
	    ;;
	esac
}


create_php_ini_1011()
{
	echo_try "Create per-vhost php.ini for php over cgi/fastcgi"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/php_ini_update_1011.php && suc || warn "fail\nCannot create per-vhost php.ini for php over cgi/fastcgi.Please run $PRODUCT_ROOT_D/admin/plib/scripts/php_ini_update_1011.php.php manually."
}
api_rpc_create_persistent_tables()
{
	inten="create persistent database storage"
	echo_try $inten
	$mysql < $PRODUCT_BOOTSTRAPPER_DIR/db/api-rpc/api-rpc_db.sql

	if [ "X$?" = "X0" ]; then
		suc
	else
		warn "database initialization"
	fi
}

#
# Upgrade triggers should be clever enough to recognize necessity of upgrade
#
upgrade_api_75()
{
	if db_test_table secret_keys; then
		# secret_keys was created - at least 8.0 version
		return
	fi

	$mysql < $PRODUCT_BOOTSTRAPPER_DIR/db/api-rpc/api-rpc_db_upgrade_750.sql
}

upgrade_api_800()
{
	if db_test_column_enum_value exp_event event_type exceeded; then
		# 'exceeded' was added in 8.0.1
		return
	fi

	$mysql < $PRODUCT_BOOTSTRAPPER_DIR/db/api-rpc/api-rpc_db_upgrade_800.sql
}

upgrade_api_801()
{
	if db_test_column_enum_value exp_event obj_class domain_alias; then
		# domain_alias was added in 8.0.1 update
		return
	fi

	$mysql < $PRODUCT_BOOTSTRAPPER_DIR/db/api-rpc/api-rpc_db_upgrade_801.sql
}

upgrade_api_830()
{
  $mysql < $PRODUCT_BOOTSTRAPPER_DIR/db/api-rpc/api-rpc_db_upgrade_830.sql
}

upgrade_api_840()
{
  $mysql < $PRODUCT_BOOTSTRAPPER_DIR/db/api-rpc/api-rpc_db_upgrade_840.sql
}

upgrade_api_860()
{
  $mysql < $PRODUCT_BOOTSTRAPPER_DIR/db/api-rpc/api-rpc_db_upgrade_860.sql
}

#
# End of upgrade triggers
#

api_rpc_upgrade_persistent_tables()
{
	inten="upgrade persistent database storage"
	echo_try $inten

	# As we don't know previous version of the package (for all packaging systems)
	# all available database upgrade scripts should be executed.
	upgrade_api_75 && \
	upgrade_api_800 && \
	upgrade_api_801 && \
    upgrade_api_830 && \
    upgrade_api_840 && \
    upgrade_api_860

	if [ "X$?" = "X0" ]; then
		suc
	else
		warn "database upgrade"
	fi
}
purge_old_api_files()
{
    inten="Removing pre-7.5 PleskAgent"
	echo_try $inten

	rm -rf ${PRODUCT_ROOT_D}/admin/plib/Agent*
    rm -rf ${PRODUCT_ROOT_D}/admin/plib/Core*
    rm -rf ${PRODUCT_ROOT_D}/admin/plib/Expand*

	suc
}
apsc_import_data_1011()
{
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/aps-controller-data-import.php 2>>"$product_log"
	[ "$?" -eq 0 ] || \
		warn "cannot import data to APS controller database. Please rerun $PRODUCT_ROOT_D/admin/plib/scripts/aps-controller-data-import.php manually"
}

#-*- vim:syntax=sh

repeat_until_succeeds()
{
	local repeat_func="$1"
	local modify_func="$2"
	local max_times="$3"

	for i in `seq 1 "$max_times"`; do
		eval "$repeat_func" && return 0 || eval "$modify_func"
	done
	return 1
}

apsc_try_create_db()
{
	local mysql_db_name="mysql"
	echo "CREATE DATABASE $apsc_db_name" | mysql >> "$product_log" 2>&1
}

apsc_modify_db_name()
{
	apsc_db_name="${apsc_db_name_base}_`get_random_string 4 'a-z0-9'`"
}

apsc_try_create_db_user()
{
	local mysql_db_name="mysql"
	echo "CREATE USER '$apsc_db_user'@'localhost' IDENTIFIED BY '$apsc_db_passwd'" | mysql >> "$product_log" 2>&1 && 	echo "GRANT ALL PRIVILEGES ON $apsc_db_name.* TO '$apsc_db_user'@'localhost'" | mysql >> "$product_log" 2>&1
}

apsc_modify_db_user()
{
	apsc_db_user="${apsc_db_user_base}_`get_random_string 4 'a-z0-9'`"
}

apsc_init_db()
{
	local mysql_db_name="$apsc_db_name"
	local mysql_user="--user=$apsc_db_user"
	local mysql_passwd="--password=$apsc_db_passwd"
	local sql_dump_file="$PRODUCT_BOOTSTRAPPER_DIR/db/apsc_mysql_db.sql"

	[ -r "$sql_dump_file" ] || return 1
	mysql < "$sql_dump_file" >> "$product_log" 2>&1
}

apsc_remove_db()
{
	[ -n "$apsc_db_name" ] || return
	local mysql_db_name="mysql"
	echo "DROP DATABASE $apsc_db_name" | mysql >> "$product_log" 2>&1
}

apsc_remove_db_user()
{
	[ -n "$apsc_db_user" ] || return
	local mysql_db_name="mysql"
	echo "DROP USER '$apsc_db_user'@'localhost'" | mysql >> "$product_log" 2>&1
}

set_apsc_params()
{
	odbc_config_bin="/usr/bin/odbc_config" # present at least on CentOS 5
	if [ -x "$odbc_config_bin" ]; then
		odbc_dsn_conf=`$odbc_config_bin --odbcini 2>> "$product_log"`
		odbc_drivers_conf=`$odbc_config_bin --odbcinstini 2>> "$product_log"`
	fi
	if [ -z "$odbc_dsn_conf" ]; then
		odbc_dsn_conf="/etc/odbc.ini"
	fi
	if [ -z "$odbc_drivers_conf" ]; then
		odbc_drivers_conf="/etc/odbcinst.ini"
	fi

	odbc_isql_bin="/usr/bin/isql"
	odbc_iusql_bin="/usr/bin/iusql"

	odbc_mysql_driver="/usr/lib64/libmyodbc5.so"
	odbc_isql_bin=

	apsc_driver_library="/usr/lib64/libmysqlserver.so.2"
}

apsc_sanity_check_binaries()
{
	# To easily detect breakage on new OSes
	[ -f "$odbc_mysql_driver" ] || die "find MySQL ODBC driver"
	[ -f "$apsc_driver_library" ] || die "find MySQL platform driver library"
}

read_apsc_connection_param_db()
{
	local param="$1"
	db_select "SELECT val FROM misc WHERE param like 'aps_$param'"
	echo "$db_select_output"
}

read_apsc_connection_params_db()
{
	# Warning : password can be encrypted.
	apsc_db_name=`read_apsc_connection_param_db "database"`
	apsc_db_user=`read_apsc_connection_param_db "login"`
	apsc_db_passwd=`read_apsc_connection_param_db "password"`
	apsc_db_host=`read_apsc_connection_param_db "host"`
}

save_apsc_connection_params_db()
{
	local register_script="$PRODUCT_ROOT_D/admin/plib/scripts/register_apsc_database.php"
	[ -f "$register_script" ] || die 'can not find "register_apsc_database.php"'

	sw_engine_pleskrun "$register_script" --register 		-host 'localhost' 		-port 3306 		-database "$apsc_db_name" 		-login "$apsc_db_user" 		-password "$apsc_db_passwd" >> "$product_log" 2>&1
}

save_apsc_connection_params_conf()
{
	conf_setval "$prod_conf_t" APS_DB_DRIVER_LIBRARY "$apsc_driver_library"
}

save_apsc_connection_params()
{
	save_apsc_connection_params_conf || die "store driver library path for APS controller db connection"
	save_apsc_connection_params_db || die "store APS controller db connection parameters into product db"
}

check_ini_section_exists()
{
	local section="$1"
	local file="$2"
	grep -q "\[$section\]" "$file" >/dev/null 2>&1
}

check_odbc_driver_exists()
{
	# We could use odbcinst here, but it wouldn't save us much trouble
	local driver="$1"
	check_ini_section_exists "$driver" "$odbc_drivers_conf"
}

check_odbc_dsn_exists()
{
	local dsn="$1"
	check_ini_section_exists "$dsn" "$odbc_dsn_conf"
}

remove_ini_section()
{
	local section="$1"
	local file="$2"
	[ -r "$file" ] || return 0
	awk "/\[.*\]/ { del = 0 } /\[$section\]/ { del = 1 } ( del != 1 ) { print }" "$file" > "$file.new" && 	mv -f "$file.new" "$file"
}

remove_odbc_driver()
{
	local driver="$1"
	remove_ini_section "$driver" "$odbc_drivers_conf"
}

remove_odbc_dsn()
{
	local dsn="$1"
	remove_ini_section "$dsn" "$odbc_dsn_conf"
}

apsc_try_create_odbc_driver()
{
	check_odbc_driver_exists "$apsc_odbc_driver_name" && return 1

	local odbc_mysql_driver64=
	if echo "$odbc_mysql_driver" | grep -q lib64 2>/dev/null ; then
		odbc_mysql_driver64="$odbc_mysql_driver"
	fi

	cp -f "$odbc_drivers_conf" "$odbc_drivers_conf.new" && 	cat <<EOF >> "$odbc_drivers_conf.new" && mv -f "$odbc_drivers_conf.new" "$odbc_drivers_conf"
[$apsc_odbc_driver_name]
Description = MySQL driver for Plesk
Driver      = $odbc_mysql_driver
Setup       = 
FileUsage   = 1
Driver64    = $odbc_mysql_driver64
Setup64     = 
UsageCount  = 1

EOF
	local rc="$?"
	[ "$rc" -eq 0 ] || rm -f "$odbc_drivers_conf.new"
	return "$rc"
}

apsc_try_create_odbc_dsn()
{
	check_odbc_dsn_exists "$apsc_dsn_name" && return 1

	cp -f "$odbc_dsn_conf" "$odbc_dsn_conf.new" && 	cat <<EOF >> "$odbc_dsn_conf.new" && mv -f "$odbc_dsn_conf.new" "$odbc_dsn_conf"
[$apsc_dsn_name]
Description = MySQL APS controller database (temporary DSN)
Driver      = $apsc_odbc_driver_name
SERVER      = localhost
USER        = $apsc_db_user
PASSWORD    = $apsc_db_passwd
PORT        = 3306
DATABASE    = $apsc_db_name

EOF
	local rc="$?"
	[ "$rc" -eq 0 ] || rm -f "$odbc_dsn_conf.new"
	return "$rc"
}

apsc_modify_odbc_driver()
{
	# just remove the one that bothers us
	remove_odbc_driver "$apsc_odbc_driver_name"
}

apsc_modify_odbc_dsn()
{
	apsc_dsn_name="${apsc_dsn_name_base}_`get_random_string 4 'a-z0-9'`"
}

check_apsc_installed()
{
	local db_name=`read_apsc_connection_param_db "database"`

	[ -n "$db_name" ] || return 1
	db_test_database "$db_name"
}

odbc_test_connection_using_dsn()
{
	local dsn="$1"
	local isql_bin="$2"
	[ -n "$isql_bin" ] || return 1
	p_echo "Attempting to check APS db connection via ODBC, using $isql_bin (empty output is good)"
	if [ ! -x "$isql_bin" ]; then
		p_echo " Executable $isql_bin was not found, skipped."
		return 1
	fi

	echo "" | $isql_bin -b "$dsn" >> "$product_log" 2>&1
	local rc="$?"

	[ "$rc" -eq 0 ] || p_echo " Failed, rc = $rc."
	return $rc
}

odbc_test_connection()
{
	if [ ! -x "$odbc_isql_bin" -a ! -x "$odbc_iusql_bin" ]; then
		warn "isql utilities were not found. APS db accessibility check was skipped."
		return 0
	fi

	local apsc_dsn_name_base="apsc"
	local apsc_dsn_name="$apsc_dsn_name_base"

	[ -r "$odbc_dsn_conf" ] || die "find ODBC config"
	repeat_until_succeeds apsc_try_create_odbc_dsn apsc_modify_odbc_dsn 50 || die "create ODBC DSN"

	odbc_test_connection_using_dsn "$apsc_dsn_name" "$odbc_isql_bin" || 	odbc_test_connection_using_dsn "$apsc_dsn_name" "$odbc_iusql_bin"
	local rc="$?"

	remove_odbc_dsn "$apsc_dsn_name"

	return $rc
}

upgrade_apsc()
{
	:
}

install_apsc()
{
	set_apsc_params

	if check_apsc_installed; then
		inten="upgrade APS controller database"
		echo_try "$inten"
		upgrade_apsc && 		suc || warn "$inten"
	else
		inten="set up APS controller database"
		echo_try "$inten"

		apsc_db_name_base="apsc"
		apsc_db_name="$apsc_db_name_base"
		apsc_db_user_base="apsc"
		apsc_db_user="$apsc_db_user_base"
		apsc_db_passwd=`get_random_string 12 'A-Za-z0-9_'`

		repeat_until_succeeds apsc_try_create_db      apsc_modify_db_name 50 && 		repeat_until_succeeds apsc_try_create_db_user apsc_modify_db_user 50 && 		apsc_init_db || die "create database for APS controller"

		apsc_odbc_driver_name="MySQL"

		[ -r "$odbc_drivers_conf" ] || die "find ODBC drivers config"
		apsc_sanity_check_binaries
		repeat_until_succeeds apsc_try_create_odbc_driver apsc_modify_odbc_driver 50 || die "create ODBC driver configuration"

		if odbc_test_connection ; then
			save_apsc_connection_params

			suc
		else
			p_echo "Failed to establish test connection. Cleaning up."

			remove_odbc_driver "$apsc_odbc_driver_name"
			apsc_remove_db_user
			apsc_remove_db

			die "establish test connection to APS database via ODBC"
		fi
	fi
}


#awstats

set_awstats_params()
{
	AWSTATS_ROOT_D="$PRODUCT_ROOT_D/awstats"
}

## @@constructor set_awstats_params

set_awstats_perms_debian()
{
	[ -d "$AWSTATS_ETC_D" ] || mkdir -p "$AWSTATS_ETC_D"
	[ -f "$AWSTATS_ETC_D/awstats.model.conf" ] || gunzip -c /usr/share/doc/awstats/examples/awstats.model.conf.gz > "$AWSTATS_ETC_D/awstats.model.conf"
	chmod 644 "$AWSTATS_ETC_D/awstats.model.conf"

	[ -f "$AWSTATS_ETC_D/awstats.conf" ] && sed -e "s|\(SiteDomain=\).*|\1\"$fullhost\"|g" \
		"$AWSTATS_ETC_D/awstats.conf" > "$AWSTATS_ETC_D/awstats.conf.tmp" \
	&& mv -f "$AWSTATS_ETC_D/awstats.conf.tmp" "$AWSTATS_ETC_D/awstats.conf" \
	&& chmod 644 "$AWSTATS_ETC_D/awstats.conf"
}

set_awstats_perms_freebsd()
{
	[ -d "$AWSTATS_ETC_D" ] || mkdir -p "$AWSTATS_ETC_D"
	[ -f "$AWSTATS_ETC_D/awstats.model.conf" ] || cp -f "$AWSTATS_BIN_D/awstats.model.conf" "$AWSTATS_ETC_D"
	chmod 644 "$AWSTATS_ETC_D/awstats.model.conf"
}

upgrade_awstats_82()
{
	# domains with physical hosting and 'awstats' statistics
	query="SELECT d.id FROM domains d, hosting h WHERE d.id=h.dom_id AND d.htype='vrt_hst' AND h.webstat='awstats';"

	for dom_id in `echo "$query" | ${mysql}`; do   

		query1="select name from domains where id='$dom_id';"
		dom_name=`echo "$query1" | ${mysql}`

		for dir in webstat anon_ftpstat ftpstat webstat-ssl ; do
			cd $HTTPD_VHOSTS_D/$dom_name/statistics/$dir
			year_month=`date +%Y-%m`
			if [ ! -d $year_month ]; then
				mkdir -p $year_month
				mv * $year_month >/dev/null 2>&1
				ln -sf $year_month current
			fi
		done

		inten="set awstats configs on virtual host $dom_name"
		"$UTILS_DIR"/webstatmng --set-configs --stat-prog=awstats --domain-name=${dom_name} \
				>> "$product_log" 2>&1 \
				|| report_problem "$inten" "Probably set awstats configs on '$dom_name' is broken"
	done

}

upgrade_awstats_84()
{
	local f
	echo_try "fix awstats domain configs"

# Get DirData="/<VHOSTS_D>/<domain_name>/statistics/<stat_type>/current" from 
# evry awstats-enabled dowain statistics; strip '/current' and copy data to
# new location
	for f in $PRODUCT_ROOT_D/etc/awstats/*.conf;do
		local datadir=`cat $f | perl -n -e 'next if(/^;/);  print $5 if(/^(\s*)DirData(\s*)=(\s*)("*)(.*?)("|\s|;)/);'`
		[ -n "$datadir" ] || continue
		[ "`basename $datadir`" = "current" ] || continue

		local tmp_file=`mktemp /tmp/aws-confXXXXXX`
		cat $f | awk -v datadir="`dirname $datadir`" '
		{
			if ($0 ~ /^[ \t]*DirData[ \t]*=/) {
				printf("DirData=%s\n", datadir);
			} else {
				print $0;
			}
		}' >$tmp_file && mv -f $tmp_file $f >> $product_log 2>&1
		if [ "$?" -ne "0" ];then
			warn "Unable to fix $f"
			continue
		fi
   		rm -f $tmp_file 
		cp -fv $datadir/*.txt `dirname $datadir` >> $product_log 2>&1
	done
}
# Backup manager tables will be managed by plesk

migrate_backup_management_db_into_core_1011()
{
# Remove backupmng from root crontab. Will be moved to system /etc/cron.d
	remove_from_crontab "$PRODUCT_ROOT_D/admin/sbin/backupmng"

	if ! db_test_table "BackupsScheduled"; then
# Perform installation of backup manager schema
		$mysql < ${PRODUCT_BOOTSTRAPPER_DIR}/db/pbm_db.sql
		[ "$?" = "0" ] || die "install backup manager tables during upgrade"
	else
# Perform upgrade of backup manager schema
		upgrade_pbm_80
		upgrade_pbm_801
		upgrade_pbm_900
	fi
# preserve number of simultaneously running backups
	db_select "SELECT val FROM misc WHERE param='max_bu_proc_number'"
	[ -n "$db_select_output" ] || \
		db_do "INSERT INTO misc VALUES('max_bu_proc_number', 10)"

# remove BackupsRunning
	db_fix_drop_table "BackupsRunning"
}

upgrade_pbm_80()
{
	if db_test_column BackupsScheduled repository; then
		# repository appeared in 8.1
		return
	fi

	$mysql < ${PRODUCT_BOOTSTRAPPER_DIR}/db/pbm_db_upgrade_80.sql
}

upgrade_pbm_801()
{
	if db_test_column BackupsScheduled split_size; then
		# split_size appeared in 8.1
		return
	fi

	$mysql < ${PRODUCT_BOOTSTRAPPER_DIR}/db/pbm_db_upgrade_801.sql
}

upgrade_pbm_900()
{
	if db_test_column_enum_value BackupsScheduled obj_type reseller; then
		# resseller type appeared in 9.0
		return
	fi

	$mysql < ${PRODUCT_BOOTSTRAPPER_DIR}/db/pbm_db_upgrade_900.sql
}

pbm_create_certificate()
{
	local inten="generate certificate for backup signing"

	[ -x "$PRODUCT_ROOT_D/admin/sbin/backup_sign" ] || return 0

	if db_select "select val from misc where param='bu_cert_id'" && [ -n "$db_select_output"  ]; then
#	Nothing to be done
		return
	fi

	echo_try $inten

	if $PRODUCT_ROOT_D/admin/sbin/backup_sign generate >> $product_log 2>&1; then
		warn "backup certificate generation"
		return 1
	fi

	suc
}

install_cron_backup()
{
	[ ! -s "/etc/cron.d/plesk-backup-manager" ] || return
	minutes=`get_random_number 15`

	cat >/etc/cron.d/plesk-backup-manager <<-EOF
$minutes,`expr $minutes + 15`,`expr $minutes + 30`,`expr $minutes + 45`	*	*	*	*	root [ -x $PRODUCT_ROOT_D/admin/sbin/backupmng ] && $PRODUCT_ROOT_D/admin/sbin/backupmng >/dev/null 2>&1
EOF
}

remove_cron_backup()
{
	rm -f "/etc/cron.d/plesk-backup-manager"
}
move_sitebuilder_conf()
{
	if [ ! -f "$HTTPD_INCLUDE_D/zz011_sitebuilder.conf" -a -f "$HTTPD_INCLUDE_D/sitebuilder.conf" ]; then
		mv -f "$HTTPD_INCLUDE_D/sitebuilder.conf" "$HTTPD_INCLUDE_D/zz011_sitebuilder.conf"
	fi

	if [ ! -f "$HTTPD_INCLUDE_D/zz011_sitebuilder.conf" -a -f "$HTTPD_CONF_D/sitebuilder.conf" ]; then
		mv -f "$HTTPD_CONF_D/sitebuilder.conf" "$HTTPD_INCLUDE_D/zz011_sitebuilder.conf"
	fi
}
#!/bin/sh

chroot_warning_prgtype()
{
	local prg type
	prg="$1"
	type="$2"

	p_echo "$prg: $type"
	p_echo "probably it will not work in chrooted accounts"
	warn "register $prg in chrooted environment"
}

install_chroot_program()
{
	local inten prg cp_update filetype libdir libdir64
	inten="register $1 in chroot"
	prg="$1"
	libdir="$2"
	libdir64="$3"

	filetype=`file -ib "$prg"`

	case "$filetype" in
	application/x-executable*statically' 'linked*) 	;;
	application/x-shellscript*|text/x-shellscript*) ;;
	application/x-executable*|application/x-sharedlib*)
		# sometimes 'file' say the executable is a shared library
		# newer OSes also say just "executable" without distibguishind between static and dynamic
		ldd "$prg" | awk '/not found/ { print; exit 1; }
						/not a dynamic executable/ { exit 0; }
						NR=4 && $1 !~ /^\// && $2=="=>" && $4 ~ /\(0x[[:xdigit:]]*\)/ {
							  if ($3 ~ /\/lib64\//) {
								dir = DIR64;
							  } else {
								dir = DIR;
							  }
							  if (system("cp -v -p " CP_UPDATE " " $3 " " dir "/" $1)!=0)
								{ exit 1; }
							}
					' DIR="$libdir" DIR64="$libdir64" CP_UPDATE="$cp_update" >> "$product_log" 2>&1 || report_problem "$inten"
		;;
	application/octet-strea*)
		;;
	*)
		chroot_warning_prgtype "$prg" "$filetype"
		;;
	esac
}

install_chroot_base()
{
	local libdir libdir64

	CHROOT_ROOT_D="$HTTPD_VHOSTS_D/chroot"
	CHROOT_PROGRAMS="bash cat cp grep head id less ln ls mkdir more \
			mv pwd rm rmdir sash sh tail touch du vi true false scp groups"
	if [ -z "chrootmng_executable" ] ; then
		chrootmng_executable="$PRODUCT_ROOT_D/admin/sbin/chrootmng"
	fi
	os=`uname -s`
	case "$os" in
		Linux)
			cp_update=-u
			libdir="$CHROOT_ROOT_D/lib"
			libdir64="$CHROOT_ROOT_D/lib64"
			;;
		FreeBSD)
			cp_update=-n
			libdir="$CHROOT_ROOT_D/usr/lib"
			;;
		*) die "unknown system $os" ;;
	esac
	copy="cp -v -p $cp_update"
	echo_try "install chrooted environment"

# see http://plesk-process.parallels.com/TargetProcess2/Project/Planning/UserStory/View.aspx?UserStoryID=70752&list=STATE_62904_ctl00_mainArea_us_userStoryGridCOMPLETE&ProjectID=62904
#	if test -d "$CHROOT_ROOT_D/etc"; then
#		"$chrootmng_executable" \
#				--remove --target=all --source="$CHROOT_ROOT_D" >>"$product_log" 2>&1 \
#			|| report_problem "cleanup chrooted environments on existing domains"
#	fi

	mkdir -m 755 -p "$CHROOT_ROOT_D"
	chown 0:0 "$CHROOT_ROOT_D"

	mkdir -m 755 -p "$CHROOT_ROOT_D/bin"
	mkdir -m 755 -p "$CHROOT_ROOT_D/dev"
	mkdir -m 755 -p "$CHROOT_ROOT_D/lib"
	[ -d /lib64 ] && mkdir -m 755 -p "$CHROOT_ROOT_D/lib64"
	mkdir -m 755 -p "$CHROOT_ROOT_D/usr"
	mkdir -m 755 -p "$CHROOT_ROOT_D/usr/lib"
	[ -d /usr/libexec ] && mkdir -m 755 -p "$CHROOT_ROOT_D/usr/libexec"
	[ -d /libexec ] && mkdir -m 755 -p "$CHROOT_ROOT_D/libexec"
	mkdir -m 755 -p "$CHROOT_ROOT_D/etc"
	mkdir -m 1777 -p "$CHROOT_ROOT_D/tmp"
	mkdir -m 755 -p "$CHROOT_ROOT_D/var"
	mkdir -m 1777 -p "$CHROOT_ROOT_D/var/tmp"

	case "$os" in
	Linux)
		mknod -m 666 "$CHROOT_ROOT_D/dev/null" c 1 3
		chown root:root "$CHROOT_ROOT_D/dev/null"
		;;
	FreeBSD)
		mknod "$CHROOT_ROOT_D/dev/null" c 1 3 root:wheel
		chmod 666 "$CHROOT_ROOT_D/dev/null"
		;;
	*) die "unknown system $os" ;;
	esac

	cd "$CHROOT_ROOT_D/bin"
	for f in $CHROOT_PROGRAMS; do
		path=`which "$f" 2>>"$product_log"`
		found=$?
		if test $found -eq 0 -a -x "$path"; then
			cp -v -p "$path" "$f" >> "$product_log" 2>&1
			install_chroot_program "$f" "$libdir" "$libdir64"
		fi
	done

	echo_try "install sftp-server binary into chroot environment"

	sftp_path="$(awk '/^Subsystem[[:space:]]sftp.*$/ {print $3}' < /etc/ssh/sshd_config)"
	sftp_dir="${sftp_path%/*}"

	if [ -z "$sftp_dir" ]; then
		echo "Warning: sftp-server binary not found" >> "$product_log"
		echo "+ sftp connections will not be available for chrooted accounts" >> "$product_log"
		warn "installation of sftp-server binary into chroot environment"
	else
		mkdir -p "$CHROOT_ROOT_D$sftp_dir" >> "$product_log" 2>&1
		cp -v -p "$sftp_path" "$CHROOT_ROOT_D$sftp_path" >> "$product_log" 2>&1
		suc
		install_chroot_program "$CHROOT_ROOT_D$sftp_path" "$libdir" "$libdir64"
	fi

	case "$os" in
	Linux)
		$copy /lib/ld-linux* /lib/libnss_*.so.2  "$CHROOT_ROOT_D/lib" >> "$product_log" 2>&1
		if [ -d /lib64 ]; then
			$copy /lib64/ld-linux* /lib64/libnss_*.so.2  "$CHROOT_ROOT_D/lib64" >> "$product_log" 2>&1
		fi
		;;
	FreeBSD)
		$copy /usr/libexec/ld-elf.so.* "$CHROOT_ROOT_D/usr/libexec" >> "$product_log" 2>&1
		$copy /libexec/ld-elf.so.* "$CHROOT_ROOT_D/libexec" >> "$product_log" 2>&1
		mkdir -m 755 -p "$CHROOT_ROOT_D/usr/share"
		mkdir -m 755 -p "$CHROOT_ROOT_D/usr/share/misc"
		cp -v -p /etc/termcap "$CHROOT_ROOT_D/usr/share/misc/termcap" >> "$product_log" 2>&1
		;;
	esac

	if test -r /etc/termcap; then
		cp -v -p /etc/termcap "$CHROOT_ROOT_D/etc/termcap" >> "$product_log" 2>&1
	fi
	touch "$CHROOT_ROOT_D/etc/passwd"
	touch "$CHROOT_ROOT_D/etc/group"

	if test -d "$PRODUCT_ROOT_D/chroot"; then
		cd "$PRODUCT_ROOT_D/chroot"

		for f in *; do
			tar cpf - -C "$f" . | tar xpf - -C "$CHROOT_ROOT_D" || report_problem "copy $f to chroot parttern"
			find $d -type f -perm +111 | while read p; do
				install_chroot_program "$p" "$libdir" "$libdir64"
			done
		done
	fi

	# noschg flag does not allow hardlinking security
	if test "$os" = "FreeBSD"; then
		chflags -R noschg "$CHROOT_ROOT_D"
	fi

# see http://plesk-process.parallels.com/TargetProcess2/Project/Planning/UserStory/View.aspx?UserStoryID=70752&list=STATE_62904_ctl00_mainArea_us_userStoryGridCOMPLETE&ProjectID=62904
#	"$chrootmng_executable" \
#			--create --target=all --source="$CHROOT_ROOT_D" --safe >>"$product_log" 2>&1 \
#		|| report_problem "distribute chrooted environments on existing domains"

	suc

	selinux_relabel_dir -F "$CHROOT_ROOT_D"
}

set_chrootsh_perms()
{
	chgrp psacln $PRODUCT_ROOT_D/bin/chrootsh
	chmod 4750 $PRODUCT_ROOT_D/bin/chrootsh
}

# import certificate into database when installing
import_default_certificate()
{
	db_select "SELECT val FROM misc WHERE param = 'default_certificate_id'"

	local default_certificate_id="$db_select_output"

	if [ -z "$default_certificate_id" ]; then
# Update misc table if needed
		echo_try "import default certificate"
		import_certificate "$certificate_file"  "default certificate"

		db_do "REPLACE INTO misc set param='default_certificate_id', val='$last_certificate_id'"
		default_certificate_id="$last_certificate_id"
		suc
	fi

	db_select "SELECT val FROM misc WHERE param = 'cert_rep_id'"
	local admin_repository_id="$db_select_output"

	if [ -z "$admin_repository_id" ]; then
		echo_try "push default certificate into repository"
		db_select "REPLACE INTO Repository SET component_id='${default_certificate_id}';SELECT LAST_INSERT_ID();"
		admin_repository_id="$db_select_output"
		db_do "REPLACE INTO misc set param='cert_rep_id', val='${admin_repository_id}'"
	else
#	simple certificate insertion to repository
		db_do "REPLACE INTO Repository SET rep_id='${admin_repository_id}', component_id='${default_certificate_id}'"
	fi
}

# import certificate from a file to certificates table
# $1 - certoificate file path
# $2 - short description of certificate
# last_certificate_id variable will contain its identifier
import_certificate()
{
	local certificate_file certificate_comment inten

	certificate_file=$1
	certificate_comment=$2

	cert_pub_val=`cat ${certificate_file} |
		awk 'BEGIN { state=0 }
		{
			if (state == 0) {
				if (index($0, "-BEGIN CERTIFICATE-") != 0) state = 1;
			};
			if (state == 1) {
				print $0;
				if (index($0, "-END CERTIFICATE-") != 0) state = 2;
			}
		}' |
		perl -n -e 's/([^ A-Za-z0-9])/"%" . sprintf("%02X", unpack("C", $1))/ge; s/ /\+/g; print $_;'`

	cert_priv_val=`cat ${certificate_file} |
		awk 'BEGIN { state=0 }
		{
			if (state == 0) {
				if ((index($0, "-BEGIN ") != 0) &&
					(index($0, " PRIVATE KEY-") != 0)) state = 1;
			};

			if (state == 1) {
				print $0;
				if ((index($0, "-END ") != 0) &&
					(index($0, " PRIVATE KEY-") != 0)) state = 2;
			}
		}' |
		perl -n -e 's/([^ A-Za-z0-9])/"%" . sprintf("%02X", unpack("C", $1))/ge; s/ /\+/g; print $_;'`

	if [ ! -d "${PRODUCT_ROOT_D}"/var/certificates ]; then
		inten="creating directory for certificates"
		mkdir -p "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}
		chown root:0 "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}
		chmod 500 "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}
	fi

	# copy certificate file to file repository
	newcertfile=`mktemp "${PRODUCT_ROOT_D}"/var/certificates/certXXXXXXX`

	cp "${certificate_file}" "${newcertfile}"  || die "place certificate to its directory"
	chown root:0 "${newcertfile}"
	chmod 400 "${newcertfile}"

	newcertfile=`basename ${newcertfile}`
	db_select "INSERT INTO certificates (pvt_key, cert, name, ca_cert, csr, cert_file, ca_file)
		VALUES ('${cert_priv_val}', '${cert_pub_val}', '${certificate_comment}', '', '',
			'${newcertfile}', '');
		SELECT LAST_INSERT_ID()"

	last_certificate_id="$db_select_output"
}

install_rbash()
{
	p_echo

	p_echo "===> Installing rbash"

	p_echo " Checking that $rbash_shell registered as login shell..."
	egrep "^$rbash_shell" /etc/shells >> $product_log 2>&1
	case $? in
		0)	p_echo " $rbash_shell is already registered as login shell"
			;;
		*)	
			if [ -f $bash_shell ]; then
				ln -sf $bash_shell $rbash_shell
				inten="add $rbash_shell to /etc/shells"
				echo_try $inten
				echo "$rbash_shell" >> /etc/shells && suc || die $inten
			fi
			;;
	esac
	p_echo
}
get_old_domain()
{
    if [ "X$domain" = "X" ]; then
		get_config_parameters
    fi
}

stop_before_upgrade()
{
	$START_SH stop 2>/dev/null || /usr/bin/killall -9 httpsd >> $product_log 2>&1
}

backup_directories()
{
	local BACKUP_F="$1"
	local BACKUP_D="`dirname $BACKUP_F`";

	shift 1
	local DIRS="$*"
	do_backup=1


	if [ -f "$BACKUP_F" ]; then
		p_echo
		p_echo "There is old backup file $BACKUP_F exists on your disk."
		p_echo

		if [ "X${interactive_allowed}" = "X1" ]; then
			pnnl_echo "Are you sure you wish to overwrite it? [N] "
			if [ "x$PLESK_AUTOINSTALLER" != "x" ]; then
				answer="YES";
			else
				read answer
			fi
		else
			if [ "X${PLESK_NO_BACKUP}" = "X" ]; then
				p_echo "ERROR!"
				p_echo "Cannot continue without new backup."
				p_echo "Please remove or rename "$BACKUP_F" and try again"
				exit 1
			fi
		fi

		echo "$answer"  >> $product_log 2>&1

		case "$answer" in
			y*|Y*)
				do_backup=1
				rm -f "$BACKUP_F"
			;;
			*)
				p_echo "OK. Continue without backup ..."
				do_backup=0
			;;
		esac
	fi

	if [ "X$do_backup" = "X1"  ]; then

		k_occupy=`du -sk $DIRS | awk 'BEGIN {sum=0} {sum+=$1} END {print sum}' -`
		k_space=`df -k $BACKUP_D | tail +2 | awk '{print $4}' -`

		if [ $k_occupy -gt $k_space ]; then

		    p_echo "There isn't enough disk space to back up your"
		    p_echo "existing contents of Plesk."
		    p_echo
			if [ "X${interactive_allowed}" = "X1" ]; then
			    p_echo "Are you sure that you have already backed up"
			    pnnl_echo "the current installation of Plesk? [N] "
			else
				p_echo "ERROR!"
				p_echo "Check the error reason, fix and try again"
				exit 1
			fi

		    case "$answer" in
			y*|Y*)
			    do_backup=0
			    ;;
			*)
			    p_echo "Thank you for choosing our products!"
			    p_echo
			    exit 1
			    ;;
		    esac
		fi
	fi

	if [ "X$do_backup" = "X1"  ]; then
	    pnnl_echo "===> Copying old contents of $DIRS ... "
	    cd ..
	    tar cvf $BACKUP_F $DIRS >> $product_log 2>&1
	    case "$?" in
		0)
		    if [ -f "$BACKUP_F" ]; then
			chmod 600 "$BACKUP_F"
		    fi
		    ;;
		*)
		    if [ -f "$BACKUP_F" ]; then
			chmod 600 "$BACKUP_F"
		    fi

    		    echo
		    p_echo
		    p_echo "ERROR:  saving of files to $BACKUP_F has failed."

			if [ "X${interactive_allowed}" = "X1" ]; then
			    p_echo "        Please save them manually."
			    p_echo

			    p_echo "Are you sure that you have already backed up"
			    pnnl_echo " the $product_full files? [N] "
				if [ "x$PLESK_AUTOINSTALLER" != "x" ]; then
					answer="YES";
				else
					read answer
				fi
			else
				p_echo "Check the error reason, fix and try again."
				p_echo "log file: ${product_log}"
				exit 1
			fi

		    case "$answer" in
			y*|Y*)

			    ;;
			*)
			    p_echo "Thank you for choosing our products!"
	    		    p_echo
	    		    exit 1
			    ;;
		    esac

		    ;;
	    esac
	else
	    p_echo "	Saving is not performed ..."
	fi
	p_echo
}

# returns 0 if $2 is subdirectory of $1

subdir()
{
	local dir="$1" subdir="$2"

	case $subdir in
		$dir*)
			return 0
		;;
	esac
	return 1
}

# if $1 is subdir any of $2 .. $n, then echo "$2 .. $n"; else echo "$2 .. $n $1"

add_backup_dir()
{
	local NEW="$1"

	shift 1
	local DIRS="$*" RESULT="" dir=""

	for dir in $DIRS; do

		if subdir $dir $NEW; then
			echo $DIRS
			return 0
		fi

		if ! subdir $NEW $dir; then
			RESULT="$RESULT $dir"
		fi
	done;

	echo $RESULT $NEW
}

get_backup_dirs()
{
	local DIRS="" dir=""
	local LIST="$PRODUCT_ROOT_D $HTTPD_VHOSTS_D $PLESK_MAILNAMES_D $MYSQL_VAR_D"

	for dir in $LIST; do
		if [ -n "$dir" -a -d "$dir" ]; then
			DIRS=`add_backup_dir $dir $DIRS`
		fi
	done;
	echo $DIRS
}

backup_old_root_131()
{

	if [ "X${backup_required}" = "X1" ]; then
		product_sav_tar="$PRODUCT_ROOT_D.sav_1.3.1.tar"

		backup_directories $product_sav_tar $PREV_PRODUCT_ROOT_D

		super_server_action remove smtp
		super_server_action remove smtps
		super_server_action remove pop3
		super_server_action remove ftp

		if [ ! -d "$PRODUCT_ROOT_D" ]; then
			inten="make $PRODUCT_ROOT_D directory"
			echo_try $inten
			mkdir -p "$PRODUCT_ROOT_D" && suc || die $inten
		else
			$START_SH stop >> $product_log 2>&1
			sleep 3
			pnnl_echo "===> Removing old contents of $PRODUCT_ROOT_D... "
			rm -Rf "$PRODUCT_ROOT_D"/* && suc || die $inten
		fi

		p_echo
	fi

}

backup_old_root_200()
{
	if [ "X${backup_required}" = "X1" ]; then
		product_sav_tar="$PRODUCT_ROOT_D.sav_2.0.tar"

		local DIRS="`get_backup_dirs`"
		backup_directories $product_sav_tar $DIRS
	fi
}

backup_old_root_250()
{
	if [ "X${backup_required}" = "X1" ]; then
		product_sav_tar="$PRODUCT_ROOT_D.sav_2.5.tar"

		local DIRS="`get_backup_dirs`"
		backup_directories $product_sav_tar $DIRS
	fi
}

backup_old_root_500()
{
	if [ "X${backup_required}" = "X1" ]; then
		product_sav_tar="$PRODUCT_ROOT_D.sav_5.0.tar"

		local DIRS="`get_backup_dirs`"
		backup_directories $product_sav_tar $DIRS
	fi
}

backup_old_root_750()
{
	if [ "X${backup_required}" = "X1" ]; then
		product_sav_tar="$1/psa.sav_7.5.tar"

		local DIRS="`get_backup_dirs`"
		backup_directories $product_sav_tar $DIRS
	fi
}

install_default_key()
{
	die "install default key - it's disabled"
}

map_new_locales_files()
{
	if test -e "$PRODUCT_ROOT_D/admin/plib/locales/$3/$1_$3.php"; then
		ln -s "$PRODUCT_ROOT_D/admin/plib/locales/$3/$1_$3.php" \
			"$PRODUCT_ROOT_D/admin/plib/locale/$1_$2.php3"
	fi
}

map_new_locales()
{
	map_new_locales_files messages "$1" "$2"
	map_new_locales_files conhelp "$1" "$2"

	if test -e "$PRODUCT_ROOT_D/admin/htdocs/locales/$2"; then
		ln -s "$PRODUCT_ROOT_D/admin/htdocs/locales/$2" \
			"$PRODUCT_ROOT_D/admin/htdocs/locale/$1"
	fi
}

install_new_key()
{
	die "install new key - it's disabled"
}
update_components_table()
{
	if [ "X${do_upgrade}" != "X1" ]; then
		return
	fi

	local inten="update Components"
	echo_try "$inten"

	db_do --inten "$inten" "DELETE FROM ServiceNodeProperties WHERE name LIKE 'server.packages.%'"
	suc

	packagemng_set_dirty_flag
}

configure_courier_authpsa()
{
    local action conf rc err_count restart_needed
    action=$1
    restart_needed=0
    err_count=0
    for conf in pop3d pop3d-ssl imapd imapd-ssl; do
	/usr/local/psa//admin/bin/courier_authpsa_configure "$conf" "$action" 2>>"$product_log"
	rc=$?
	case "$rc" in
	    0)
		;;
	    110)
		restart_needed=110
		;;
	    *)
		err_count=$(($err_count + 1)) # error was already reported in stderr
		;;
	esac
    done

    if [ $err_count -gt 0 ]; then
	echo "Some configuration files weren't processed successfully. See \"$product_log\" for details" >&2
    fi

    return $restart_needed
}


#courier-imap

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

	courier_service="courier-imap"
}

## @@constructor set_courier_imap_params

configure_courier()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		return 0;
	fi

	p_echo
	p_echo
	cd "$PRODUCT_ROOT_D" || die "cd $PRODUCT_ROOT_D"
	p_echo "===> Configuring Courier-IMAP server"
	p_echo

	local restart_needed
	restart_needed=0

	set_courier_imap_params

	if [ ! -f "$IMAPD_CERT" ]; then
		inten="generate Certificate for Courier-IMAP server for IMAP-SSL"
		echo_try $inten
		get_certificate "$IMAPD_CERT" || die $inten
		set_ac 0 0 0400 "$IMAPD_CERT"
		suc
		restart_needed=110
	fi

	if [ ! -f "$POP3D_CERT" ]; then
		inten="copy default SSL Certificate for Courier-IMAP server for POP3-SSL"
		echo_try $inten
		cp -fp "$IMAPD_CERT" "$POP3D_CERT" || die $inten
		suc
		restart_needed=110
	fi

	# Comment services for imap, imaps pop3, pop3s in super server internet [x]inetd
	# Should inetd/xinetd be restarted after this operation?
	courier_imap_comment_inetd_services

	inten="Configure Courier IMAP for Plesk-specific authentication"
	echo_try $inten
	configure_courier_authpsa add
	rc=$?
	if [ $rc -eq 110 ]; then
		restart_needed=110
	fi
	suc

	# always restart upon fresh installation
	if [ "X$do_upgrade" != "X1" -o $restart_needed -eq 110 ]; then
		pleskrc courier restart
	fi
}

courier_imap_comment_inetd_services()
{
	set_super_server_params
	super_server_action comment "imap"
	super_server_action comment "imap2"
	super_server_action comment "imap4"
	super_server_action comment "imaps"

	super_server_action comment "pop3"
	super_server_action comment "pop-3"
	super_server_action comment "pop3s"
}
upgrade_courier_imap_auth_1013()
{
	set_courier_imap_params
	local IMAP_CFG="$COURIERIMAP_CONFDIR/imapd"
	local POP3_CFG="$COURIERIMAP_CONFDIR/pop3d"
	local imap_pci_comp pop3_pci_comp

	ls $IMAP_CFG.pci.* 1>/dev/null 2>&1 && imap_pci_comp="on"
	ls $POP3_CFG.pci.* 1>/dev/null 2>&1 && pop3_pci_comp="on"

	# sed code is taken from 10.4.4/MU5/MU-imapd.sh
	if [ "$imap_pci_comp" != "on" ]; then
		if ! egrep -q '^IMAP_CAPABILITY="?[^"]*AUTH=[^"]*"?\s*$' $IMAP_CFG 2>/dev/null ; then
			cp $IMAP_CFG $IMAP_CFG.plesk.bak && \
			sed -e "s/^IMAP_CAPABILITY=\(.*\) IDLE\\\"$/IMAP_CAPABILITY=\\1 AUTH=CRAM-MD5 AUTH=PLAIN IDLE\\\"/g" \
				-e "s/^IMAP_CAPABILITY_ORIG=\(.*\) IDLE\\\"$/IMAP_CAPABILITY_ORIG=\\1 AUTH=PLAIN IDLE\\\"/g" \
				-e "s/^IMAP_CAPABILITY_TLS=.*$/IMAP_CAPABILITY_TLS=\\\"\\\$IMAP_CAPABILITY\\\"/g" \
				-e "s/^IMAP_CAPABILITY_TLS_ORIG=.*$/IMAP_CAPABILITY_TLS_ORIG=\\\"\\\$IMAP_CAPABILITY_ORIG\\\"/g" \
				<$IMAP_CFG >$IMAP_CFG.plesk.tmp &&
			mv $IMAP_CFG.plesk.tmp $IMAP_CFG || rm -f $IMAP_CFG.plesk.{tmp,bak}
		fi
	fi

	if [ "$pop3_pci_comp" != "on" ]; then
		if egrep -q '^POP3AUTH(_TLS)?=("\s*")?\s*$' $POP3_CFG 2>/dev/null ; then
			cp $POP3_CFG $POP3_CFG.plesk.bak && \
			sed -e "s/^POP3AUTH=.*$/POP3AUTH=\\\"LOGIN CRAM-MD5 PLAIN\\\"/g" \
				-e "s/^POP3AUTH_ORIG=.*$/POP3AUTH_ORIG=\\\"LOGIN CRAM-MD5 PLAIN\\\"/g" \
				-e "s/^POP3AUTH_TLS=.*$/POP3AUTH_TLS=\\\"LOGIN CRAM-MD5 PLAIN\\\"/g" \
				-e "s/^POP3AUTH_TLS_ORIG=.*$/POP3AUTH_TLS_ORIG=\\\"LOGIN CRAM-MD5 PLAIN\\\"/g" \
				<$POP3_CFG >$POP3_CFG.plesk.tmp && \
			mv $POP3_CFG.plesk.tmp $POP3_CFG || rm -f $POP3_CFG.plesk.{tmp,bak}
		fi
	fi
}
# vim:syntax=sh

install_cron_somely()
{
	install_cron_somely_perform
}

remove_cron_somely()
{
	remove_cron_somely_perform
}

set_cron_params()
{
    CRON_SOMELY_DIR_PREFIX=/etc/psa/plesk-cron
}

configure_crond_auth()
{
	cat >> /etc/pam.d/crond << EOF
# Added by Parallels Plesk Panel
session include common-session
EOF
}

install_cron_somely_perform()
{
	set_cron_params
	set_cron_somely_params

	daily_minute=`get_random_number 60`
	weekly_minute=`get_random_number 60`
	monthly_minute=`get_random_number 60`
	daily_hour=`get_random_number 6`
	weekly_hour=`get_random_number 7`
	monthly_hour=`get_random_number 7`

	# monthly must be after daily
	if [ $monthly_hour -lt $daily_hour ]; then
		swap=$daily_hour
		daily_hour=$monthly_hour
		monthly_hour=$swap
	elif [ $monthly_hour -eq $daily_hour ]; then
		monthly_hour=$(($monthly_hour + 1))
	fi

	install_cron_somely_entry "$daily_minute $daily_hour * * *" daily
	install_cron_somely_entry "$weekly_minute $weekly_hour * * 7" weekly
	install_cron_somely_entry "$monthly_minute $monthly_hour 1 * *" monthly
}

remove_cron_somely_perform()
{
	set_cron_somely_params
	remove_from_crontab "$cron_somely_run_parts"
}

install_cron_somely_noop()
{
	:
}

remove_cron_somely_noop()
{
	:
}

set_cron_somely_params()
{
	cron_somely_run_parts="$PRODUCT_ROOT_D/bin/run-parts.sh"
}

install_cron_somely_entry()
{
	add_to_crontab "$1 $cron_somely_run_parts $CRON_SOMELY_DIR_PREFIX.$2" \
		"$cron_somely_run_parts" "$CRON_SOMELY_DIR_PREFIX.$2" "root" "add $2 task"
}

install_cron_task()
{
	local mshift period minutes_str msg prog prog_run
	period=$(($1 + 0)) # make sure it's integer
	msg=$2
	prog=$3
	prog_run=$4
	[ -n "$prog_run" ] || prog_run=$prog
	if [ $period -eq 0 -o -z "$prog" ]; then
		simply_die "invalid arguments to install_cron_simple_task(): $@"
	fi

	mshift=$(get_random_number $period)
	minutes_str=$(form_crontab_fraction_period $period $mshift 60)
	add_to_crontab "$minutes_str *  *  *  * $prog_run" "$prog" "" "" "install $msg cron task"
}

remove_cron_task()
{
    remove_from_crontab "$@"
}

add_to_crontab()
{
	local cron_string egrep_programm egrep_additional inten

	cron_string=$1
	egrep_programm=$2
	egrep_additional=$3
	user=$4
	inten=$5
	
	if [ "X$DEMO_VERSION" = "Xyes" ]; then 
		return 0;
	fi

	p_echo
	p_echo "===> Updating crontab..."
	
	$crontab -l 2>/dev/null > /tmp/crontab.${product}
	egrep "$egrep_programm" /tmp/crontab.${product} | egrep "$egrep_additional" | egrep -v "^#" > /dev/null 2>&1
	case "$?" in
		0)
			p_echo "$inten is already performed by cron"
			;;
		1)
			echo_try $inten
			echo "$1" >> /tmp/crontab.${product} || die $inten
			$crontab /tmp/crontab.${product} && suc || die $inten
			;;
		*)
			err
			;;
	esac

	rm -f /tmp/crontab.${product} || die
}

remove_from_crontab()
{
	program=$1

	echo_try "remove $program from crontab"

	cron_file=`mktemp /tmp/cronXXXXXX`
	$crontab -l 2>/dev/null | egrep -v "^[^#].*$program" > $cron_file
	$crontab $cron_file

	rm -f $cron_file
	suc
}

form_crontab_fraction_period()
{
	local period mshift total current result
	period=$1
	mshift=$2
	total=$3
	result="$mshift"
	current=$(( $mshift + $period ))
	while [ $current -lt $total ]; do
		result="$result,$current"
		current=$(( $current + $period ))
	done
	echo $result
}
fix_crontab_109()
{
    remove_from_crontab "ttsmailparse.php"
}

remove_cron_somely_80()
{
    remove_from_crontab "$PRODUCT_ROOT_D/admin/sbin/statistics"
    remove_from_crontab "$PRODUCT_ROOT_D/bin/mysqldump.sh"
    remove_from_crontab "$PRODUCT_ROOT_D/admin/plib/report/autoreport.php"
}

fix_crontab_810()
{
    remove_from_crontab "$PRODUCT_ROOT_D/psa/run-parts.sh"
}

insert_fullhostname()
{
#	replace FullHostName
	inten="insert Hostname to the MySQL database"
	echo_try $inten

	query="select val from misc where param='FullHostName'"
	tmp="`echo \"$query\" | mysql`"

	if [ "X$tmp" = "X" ]; then
		query="replace into misc (param,val) values('FullHostName','$fullhost')"
		echo $query | mysql && suc || die $inten
	fi

	suc
}

license_show_request()
{
	inten="shedule license displaying for admin login"
	echo_try $inten

	query="DELETE FROM misc where param='not_showLicense'"
	echo $query | mysql || die "$inten"

	suc
}

setup_support_url()
{
	local support_url

	support_url="$1"
	db_do "REPLACE INTO misc (param,val) values('support_url', '$support_url')"
}


update_mysql4_permissions()
{
	local query major_version

	# determine mysql version (for 4.x there is additional set of permissions/privileges)
	query="USE mysql; SHOW VARIABLES LIKE 'version';"
	major_version=`echo "${query}" | mysql | sed -e 's/^version[ \t]\([0-9]*\)\..*$/\1/'`

	if [ "X$major_version" != "X4" ]; then
		# don't need to update permissions
		return
	fi

	inten="update administrators permissions for MySQL 4"
	echo_try $inten

	query="	USE mysql;
			UPDATE user SET Super_priv='Y', Create_tmp_table_priv='Y', Lock_tables_priv='Y', Execute_priv='Y', Repl_slave_priv='Y', Repl_client_priv='Y' WHERE User='admin';
			FLUSH PRIVILEGES;"
	echo $query | mysql || warn "$inten"

	suc
}

# add_db_changes [--fix] version
# Runs ${PRODNAME}_db_upgrade_${version}.sql
# (with --fix, runs ${PRODNAME}_db_upgrade_${version}_fix.sql)
add_db_changes()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local inten upgrade_db_sql fix
	fix=""
	eval `sh_get_args '--fix) fix="_fix";;'`
	inten="upgrade SQL database from $1"
	upgrade_db_sql="$PRODUCT_BOOTSTRAPPER_DIR/db/${PRODNAME}_db_upgrade_${1}${fix}.sql"
	mysql < $upgrade_db_sql >> "$product_log" 2>&1 || die "$inten"
}

# db_fix_add_column [--init def_value] table column type
# Adds a column of the specified type to the table, optionally
# initializing it with def_value, which is an SQL expression. If the
# column already exists, does nothing
db_fix_add_column()
{
	local def_value=""
	eval `sh_get_args '--init) def_value="$2"; shift;;'`
	local table="$1"
	local column="$2"
	local type="$3"

	if [ "$db_fix_check_stage" = "yes" ]; then
		if ! db_test "DESC $table" "\$1 == \"$column\""; then
			if [ -z "$db_added_columns" ]; then
				db_added_columns="$table.$column"
			else
				db_added_columns="$db_added_columns|$table.$column"
			fi
		fi
		return
	fi

	local query="ALTER TABLE \`$table\` ADD \`$column\` $type"
	if [ -n "$def_value" ]; then
		query="$query; UPDATE \`$table\` SET \`$column\`=$def_value"
	fi
	db_do_if_not "DESC $table" "\$1 == \"$column\"" "$query"
}

# db_fix_change_column [--init def_value] table column type
# Changes a column of the specified type to the table, optionally
# initializing it with def_value, which is an SQL expression.
# Changes a column from the table if it exists
db_fix_change_column()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local def_value=""
	eval `sh_get_args '--init) def_value="$2"; shift;;'`
	local table="$1"
	local old_column="$2"
	local new_column="$3"
	local type="$4"

	local query="ALTER TABLE \`$table\` CHANGE \`$old_column\` \`$new_column\` $type"
	if [ -n "$def_value" ]; then
		query="$query; UPDATE \`$table\` SET \`$new_column\`=$def_value"
	fi
	db_do_if "DESC \`$table\`" "\$1 == \"$old_column\"" "$query"
}

# db_fix_del_column table column
# Deletes a column from the table if it exists
db_fix_del_column()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local table="$1"
	local column="$2"

	db_do_if "DESC \`$table\`" "\$1 == \"$column\"" "ALTER TABLE \`$table\` DROP \`$column\`"
}

# db_fix_add_key table column [column ...]
# Adds a non-unique [compound] key on the specified columns of the
# table. If the key already exists, or there is another key that
# substitutes this one, nothing is done. Existing keys that are
# substituted by the new one are dropped
db_fix_add_key()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local table="$1"
	local columns="$2"
	shift 2
	local i
	for i; do
		columns="$columns,\`$i\`"
	done
	local type name icolumns
	local found=no
	db_get_keys "$table" | (
		while read type name icolumns; do
			case "$icolumns" in
				"$columns"|"$columns",*)
					found=yes
					break
					;;
			esac
			case "$columns" in
				"$icolumns",*)
					if [ "$type" = "KEY" ]; then
						db_do "ALTER TABLE \`$table\` DROP KEY \`$name\`"
					fi
					;;
			esac
		done
		if [ "$found" = no ]; then
			db_do "ALTER TABLE \`$table\` ADD KEY ($columns)"
		fi
		exit 0
	)
	local status="$?"
	if [ "$status" -ne 0 ]; then
		exit "$status"
	fi
}

# db_fix_drop_key table column [column ...]
# Drops a non-unique [compound] key on the specified columns of the
# table. If the key does not exist, nothing is done
db_fix_drop_key()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local table="$1"
	local columns="$2"
	shift 2
	local i
	for i; do
		columns="$columns,$i"
	done
	local type name icolumns
	local found=no
	db_get_keys "$table" | (
		while read type name icolumns; do
			if [ "$icolumns" = "$columns" ] && [ "$type" = "KEY" ]; then
				db_do "ALTER TABLE $table DROP KEY $name"
				break
			fi
		done
		exit 0
	)
	local status="$?"
	if [ "$status" -ne 0 ]; then
		exit "$status"
	fi
}

# db_fix_add_unique_key [--check-where condition] table column [column ...]
# Adds a unique [compound] key on the specified columns of the table.
# If the key already exists, or there is another key that substitutes
# this one, nothing is done. Existing keys that are substituted by the
# new one are dropped. If --check-where is specified, limit checking
# to rows that satisfy the given SQL condition
db_fix_add_unique_key()
{
	local check_where=""
	eval `sh_get_args '--check-where) check_where="--where \"$2\""; shift;;'`
	if [ "$db_fix_check_stage" = "yes" ]; then
		eval db_check_unique $check_where "$@"
		return
	fi

	local table="$1"
	local columns="$2"
	local esc_columns="$2"
	shift 2
	local i
	for i; do
		columns="$columns,$i"
		esc_columns="$esc_columns,\`$i\`"
	done
	local type name icolumns
	local found=no
	db_get_keys "$table" | (
		while read type name icolumns; do
			case "$icolumns" in
				"$columns"|"$columns",*)
					if [ "$type" != "KEY" ]; then
						found=yes
						break
					fi
					;;
			esac
			case "$columns" in
				"$icolumns"|"$icolumns",*)
					if [ "$type" != "PRIMARY" ]; then
						db_do "ALTER TABLE \`$table\` DROP KEY \`$name\`"
					fi
					;;
			esac
		done
		if [ "$found" = no ]; then
			db_do "ALTER TABLE \`$table\` ADD UNIQUE ($esc_columns)"
		fi
		exit 0
	)
	local status="$?"
	if [ "$status" -ne 0 ]; then
		exit "$status"
	fi
}

# db_fix_drop_unique_key table column [column ...]
# Drops an unique [compound] key on the specified columns of the
# table. If the key does not exist, nothing is done
db_fix_drop_unique_key()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local table="$1"
	local columns="$2"
	shift 2
	local i
	for i; do
		columns="$columns,$i"
	done
	local type name icolumns
	local found=no
	db_get_keys "$table" | (
		while read type name icolumns; do
			if [ "$icolumns" = "$columns" ] && [ "$type" = "UNIQUE" ]; then
				db_do "ALTER TABLE $table DROP KEY $name"
				break
			fi
		done
		exit 0
	)
	local status="$?"
	if [ "$status" -ne 0 ]; then
		exit "$status"
	fi
}

# db_fix_add_primary_key [--check-where condition] table column [column ...]
# Adds a primary [compound] key on the specified columns of the table.
# If the key already exists, or there is another key that substitutes
# this one, nothing is done. Existing keys that are substituted by the
# new one are dropped. If --check-where is specified, limit checking
# to rows that satisfy the given SQL condition
db_fix_add_primary_key()
{
	local check_where=""
	local where=""
	eval `sh_get_args '--check-where) check_where="--where \"$2\""; where="AND $2"; shift;;'`
	local table="$1"
	shift
	local i

	if [ "$db_fix_check_stage" = "yes" ]; then
		for i; do
			db_check_not "SELECT * FROM \`$table\` WHERE \`$i\` IS NULL $where LIMIT 1" 1 \
				"Database integrity check failed: $table.$i contains NULL values"
		done
		eval db_check_unique $check_where "$table" "$@"
		return
	fi

	local columns="$1"
	local esc_columns=$1
	shift
	for i; do
		columns="$columns,$i"
		esc_columns="$esc_columns,\`$i\`"
	done
	local type name icolumns
	local found=no
	db_get_keys "$table" | (
		while read type name icolumns; do
			case "$icolumns" in
				"$columns"|"$columns",*)
					if [ "$type" = "PRIMARY" ]; then
						found=yes
						break
					fi
					;;
			esac
			case "$columns" in
				"$icolumns"|"$icolumns",*)
					if [ "$type" = "PRIMARY" ]; then
						db_do "ALTER TABLE \`$table\` DROP PRIMARY KEY"
					else
						db_do "ALTER TABLE \`$table\` DROP KEY \`$name\`"
					fi
					;;
			esac
		done
		if [ "$found" = no ]; then
			db_do "ALTER TABLE \`$table\` ADD PRIMARY KEY ($esc_columns)"
		fi
		exit 0
	)
	local status="$?"
	if [ "$status" -ne 0 ]; then
		exit "$status"
	fi
}

# db_fix_drop_primary_key table column [column ...]
# Drops a [compound] primary key on the specified columns of the
# table. If the key does not exist, nothing is done
db_fix_drop_primary_key()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local table="$1"
	local columns="$2"
	shift 2
	local i
	for i; do
		columns="$columns,$i"
	done
	local type name icolumns
	local found=no
	db_get_keys "$table" | (
		while read type name icolumns; do
			if [ "$icolumns" = "$columns" ] && [ "$type" = "PRIMARY" ]; then
				db_do "ALTER TABLE $table DROP PRIMARY KEY"
				break
			fi
		done
		exit 0
	)
	local status="$?"
	if [ "$status" -ne 0 ]; then
		exit "$status"
	fi
}

# db_fix_add_foreign_key table column reftable refcolumn [option]
# Adds a foreign key constraint from table.column referencing
# reftable.refcolumn. If the column type is INT [UNSIGNED] and it
# allows NULL, coerce 0 to NULL in the referencing column. An option
# like "ON DELETE CASCADE" may be specified
db_fix_add_foreign_key()
{
	local table="$1"
	local column="$2"
	local reftable="$3"
	local refcolumn="$4"
	local option="$5"

	if [ "$db_fix_check_stage" = "yes" ]; then
		db_check_foreign_key "$table" "$column" "$reftable" "$refcolumn"
		return
	fi

	db_do_if "SHOW COLUMNS FROM \`$table\`" \
		"\$1 == \"$column\" && \$2 ~ /^int[(]/ && \$3 == \"YES\"" \
		"UPDATE \`$table\` SET \`$column\` = NULL WHERE \`$column\` = 0"

	db_fix_add_key "$table" "$column"

	# TODO: uncomment this when 8.0 development starts.

	# db_do_if_not "SHOW CREATE TABLE \`$table\`" \
	#	"/FOREIGN KEY [(]\`?$column\`?[)] REFERENCES \`?(psa\.)?$reftable\`? [(]\`?$refcolumn\`?[)]/" \
	#	"ALTER TABLE \`$table\` ADD FOREIGN KEY (\`$column\`) REFERENCES \`$reftable\` (\`$refcolumn\`) $option"
}

# db_fix_drop_table table_name
db_fix_drop_table()
{
	local table_name
	table_name="$1"

	db_do "DROP TABLE IF EXISTS \`$table_name\`"
}

# db_test test_query awk_script
# Runs test_query and processes it with awk_script. If the output is
# not empty, return 0, otherwise return 1. Hint: supply '1' for
# awk_script to test just for the presence of any output.
db_test()
{
	local any_db=
	eval `sh_get_args '--any-db) any_db=yes;;'`

	local test_query="$1"
	local awk_script="$2"

	if [ -n "$any_db" ]; then
		local output="`mysql_raw_anydb -e \"$test_query\" 2>>\"$product_log\"`"
	else
		local output="`mysql_raw -e \"$test_query\" 2>>\"$product_log\"`"
	fi
	local status=$?
	if [ "$status" -ne 0 ]; then
		p_echo "$output"
		die "run the following SQL query: $1"
	fi

	echo -n "$output" | awk -F '\t' -- "$awk_script" | test `wc -l` -ne 0
}

# db_do [--inten <inten>] query
# Runs query. If it fails, die
# the inten string describes the query reason (to make finding the bug simpler)
db_do()
{
	local desc="execute SQL query"
	eval `sh_get_args '--inten) desc=" (to $2)"; shift;;'`
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local query="$1"

	mysql -e "$query" >>"$product_log" 2>&1 || die "$desc, the query was: $query"
}

# db_select <query>
# runs <query> via mysql_raw
# writes output to db_select_output
# if query fails, output errors and return 1
db_select()
{
	local desc="execute SQL query"
	local query="$1"
	local output="`mysql_raw -e \"$query\" 2>>\"$product_log\"`"
	local status="$?"
	if [ "$status" -ne "0" ]; then
		p_echo "$output"
		die "run the following SQL query: $query"
	fi

	db_select_output="$output"
	return 0
}

# db_do_if test_query awk_script query
# If db_test test_query awk_script returns zero (true), run the query.
# If any query fails, die
db_do_if()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local test_query="$1"
	local awk_script="$2"
	local query="$3"

	if db_test "$test_query" "$awk_script"; then
		db_do "$query"
	fi
}

# db_do_if_not test_query awk_script query
# If db_test test_query awk_script returns nonzero (false), run the
# query. If any query fails, die
db_do_if_not()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local test_query="$1"
	local awk_script="$2"
	local query="$3"

	if ! db_test "$test_query" "$awk_script"; then
		db_do "$query"
	fi
}

# db_check test_query awk_script message
# If db_test test_query awk_script returns nonzero (false), die with
# message
db_check()
{
	local test_query="$1"
	local awk_script="$2"
	local message="$3"

	if ! db_test "$test_query" "$awk_script"; then
		p_echo "$message"
		die
	fi
}

# db_check_not test_query awk_script message
# If db_test test_query awk_script returns zero (true), die with
# message
db_check_not()
{
	local test_query="$1"
	local awk_script="$2"
	local message="$3"

	if db_test "$test_query" "$awk_script"; then
		p_echo "$message"
		die
	fi
}

# db_check_unique [--where condition] table column [column ...]
# If the table contains duplicate tuples of values in the specified
# columns, die. If --where is specified, limit checking to rows that
# satisfy the given SQL condition
db_check_unique()
{
	local where=""
	eval `sh_get_args '--where) where="WHERE $2"; shift;;'`
	local table="$1"
	shift
	local columns="$1"
	shift
	local i
	for i; do
		if [ -n "$db_added_columns" ]; then
			eval "case $table.$i in $db_added_columns) return ;; esac"
		fi
		columns="$columns, \`$i\`"
	done
	db_check_not "SELECT COUNT(*) FROM \`$table\` $where GROUP BY $columns HAVING COUNT(*) > 1 LIMIT 1" 1 \
		"Database integrity check failed: duplicate values of ($columns) exist in table $table"
}

# db_check_foreign_key table column reftable refcolumn [condition]
# If some values from table.column (from rows matching an optional
# condition) do not exist in reftable.refcolumn, die
db_check_foreign_key()
{
	local table="$1"
	local col="$2"
	local reftable="$3"
	local refcolumn="$4"
	local condition="$5"

	if [ -n "$db_added_columns" ]; then
		eval "case $table.$col in $db_added_columns) return ;; esac"
		eval "case $reftable.$refcol in $db_added_columns) return ;; esac"
	fi

	# TODO: uncomment this when 8.0 development starts.

	# db_check_not "SELECT 1 FROM \`$reftable\'
	#	LEFT JOIN \`$table\` ON \`$table\`.\`$column\` = \`$reftable\`.\`$refcolumn\` ${condition:+AND $condition}
	#	WHERE \`$reftable\`.\`$refcolumn\` IS NULL" 1 \
	#	"Database integrity check failed: some values from $table.$column do not exist in $reftable.$refcolumn"
}

# db_get_keys table
# Outputs the list of keys for a table, one on a row, in the following format:
# name type columns
# Where type is one of PRIMARY, UNIQUE, and KEY, name is always
# PRIMARY for primary keys, and columns is a comma-separated list of
# columns without embedded spaces. All backtick characters are removed
db_get_keys()
{
	local table="$1"
	local query="SHOW CREATE TABLE \`$table\`"
	local output="`mysql_raw -e "$query"`"
	local status=$?
	if [ "$status" -ne 0 ]; then
		p_echo "$output"
		die "run the following SQL query: $1"
	fi

	echo "$output" | awk '
		$1 == "PRIMARY"	{ print "PRIMARY", "PRIMARY", $3 }
		$1 == "UNIQUE"	{ print "UNIQUE", $3, $4 }
		$1 == "KEY"		{ print "KEY", $2, $3 }' | \
		sed -e 's/[`()]//g' -e 's/,[[:space:]]*$//g'
}

# db_test_database database
# Returns 0 if the database exists
db_test_database()
{
	local database="$1"

	local mysql_db_name="mysql"
	db_test "SHOW DATABASES" "\$1 == \"$database\""
}

# db_test_table table
# Returns 0 if the table exists
db_test_table()
{
	local table="$1"

	db_test "SHOW TABLES LIKE '$table'" 1
}

# db_test_column table column
# Returns 0 if table.column exists
db_test_column()
{
	local table="$1"
	local column="$2"

	db_test "DESC \`$table\`" "\$1 == \"$column\""
}

# db_test_column_enum_value <table> <column> <value awaited in enum>
# Returns O if table.column contains value in enum description
db_test_column_enum_value()
{
	local table="$1"
	local column="$2"
	local value="$3"

	db_test "DESC \`$table\` \`$column\`" "/[\'\"]$value[\'\"]/ { print 1 }"
}

db_create_default_templates()
{
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/create_default_templates.php 2>>"$product_log"
	[ "$?" -eq 0 ] || \
		warn "default tempaltes cannot be created"
}

db_update_notifications()
{
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/update_notifications.php 2>>"$product_log"
	[ "$?" -eq 0 ] || \
		warn "cannot update notifications. Please rerun $PRODUCT_ROOT_D/admin/plib/scripts/update_notifications.php manually"
}

db_update_plesk10()
{
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/db-update-plesk10.php 2>>"$product_log"
	[ "$?" -eq 0 ] || \
		warn "cannot update db. Please rerun $PRODUCT_ROOT_D/admin/plib/scripts/db-update-plesk10.php manually"
}

smb_install_db()
{
	$PRODUCT_ROOT_D/admin/smb/application/utils/dbupgrade >>"$product_log" 2>&1
	[ "$?" -eq 0 ] || \
		die "SMB database not created"

}


db_upgrade_ip_addresses_1010()
{
    db_fix_add_column IP_Addresses main "ENUM('true', 'false') NOT NULL DEFAULT 'false'"
    db_fix_add_column IP_Addresses status "BIGINT UNSIGNED NOT NULL DEFAULT 0"
}

fix_ip_addresses_1010()
{
    echo_try "Set missing main property to IP addresses"
    sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_ip_addresses_1010.php && suc || warn "fail\nCannot update IP addresses information. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_ip_addresses_1010.php manually."
}

db_upgrade_dns_recs_t_1010()
{
    db_do_if_not \
        "SELECT id FROM dns_recs_t WHERE type IN ('AAAA', 'CNAME') AND host='ns.<domain>.'" 1 \
        "REPLACE INTO dns_recs_t(displayHost, host, type, displayVal, val, time_stamp) VALUES('ns.<domain>.', 'ns.<domain>.', 'AAAA', '<ipv6>', '<ipv6>', NOW());"

    db_do_if_not \
        "SELECT id FROM dns_recs_t WHERE type IN ('AAAA', 'CNAME') AND host='<domain>.'" 1 \
        "REPLACE INTO dns_recs_t(displayHost, host, type, displayVal, val, time_stamp) VALUES('<domain>.', '<domain>.', 'AAAA', '<ipv6>', '<ipv6>', NOW()+1);"

    db_do_if_not \
        "SELECT id FROM dns_recs_t WHERE type IN ('AAAA', 'CNAME') AND host='webmail.<domain>.'" 1 \
        "REPLACE INTO dns_recs_t(displayHost, host, type, displayVal, val, time_stamp) VALUES('webmail.<domain>.', 'webmail.<domain>.', 'AAAA', '<ipv6>', '<ipv6>', NOW()+2);"

    db_do_if_not \
        "SELECT id FROM dns_recs_t WHERE type IN ('AAAA', 'CNAME') AND host='mail.<domain>.'" 1 \
        "REPLACE INTO dns_recs_t(displayHost, host, type, displayVal, val, time_stamp) VALUES('mail.<domain>.', 'mail.<domain>.', 'AAAA', '<ipv6>', '<ipv6>', NOW()+3);"

    db_do_if_not \
        "SELECT id FROM dns_recs_t WHERE type IN ('A', 'CNAME') AND host='ipv4.<domain>.'" 1 \
        "REPLACE INTO dns_recs_t(displayHost, host, type, displayVal, val, time_stamp) VALUES('ipv4.<domain>.', 'ipv4.<domain>.', 'A', '<ip>', '<ip>', NOW()+4);"

    db_do_if_not \
        "SELECT id FROM dns_recs_t WHERE type IN ('AAAA', 'CNAME') AND host='ipv6.<domain>.'" 1 \
        "REPLACE INTO dns_recs_t(displayHost, host, type, displayVal, val, time_stamp) VALUES('ipv6.<domain>.', 'ipv6.<domain>.', 'AAAA', '<ipv6>', '<ipv6>', NOW()+5);"
}

db_upgrade_domain_services_1010()
{
     db_fix_add_column DomainServices ipCollectionId "INT UNSIGNED"
}

db_upgrade_web_domain_services_1010()
{
    echo_try "Create web domain services"
    sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_web_domain_services_1010.php && suc || warn "fail\nCannot update web domain services information. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_web_domain_services_1010.php manually."
#TODO: drop of ip_address_id column from psa.hosting and psa.forwarding tables
}

db_upgrade_hosting_1010()
{
     db_fix_add_column hosting certificate_id "INT UNSIGNED DEFAULT 0"
}

db_upgrade_subdomains_1010()
{
     db_fix_add_column subdomains certificate_id "INT UNSIGNED DEFAULT 0"
}

db_upgrade_check_local_sso_is_used()
{
	# if sso is not installed locally - it is remote
	[ -f /etc/sso/sso_config.ini ] || return 1

	# if sso_server hostname matches full hostname of this machine - it is local
	db_select "SELECT val FROM misc WHERE param like 'sso_server'"
	local sso_hostname=`echo "$db_select_output" | sed -ne 's|.*://\([^:/]*\).*|\1|p'`
	[ -n "$sso_hostname" ] || return 1
	[ -n "$fullhost" ] || {
		warn "Failed to determine whether SSO is local (full hostname not defined), assuming remote."
		return 1
	}
	if [ "$sso_hostname" = "$fullhost" ]; then
		return 0
	fi

	# check whether sso_server hostname resolves to one of our ip addresses
	local ipv4_sso_addrs=""
	local ipv6_sso_addrs=""
	local host_query=""
	host_query=`host -t A "$sso_hostname" 2>/dev/null`
	if [ "$?" -eq 0 ]; then
		ipv4_sso_addrs=`echo "$host_query" | awk '{ print $NF }'`
	fi
	host_query=`host -t AAAA "$sso_hostname" 2>/dev/null`
	if [ "$?" -eq 0 ]; then
		ipv6_sso_addrs=`echo "$host_query" | awk '{ print $NF }'`
	fi

	local sso_addrs_list=`echo $ipv4_sso_addrs $ipv6_sso_addrs $sso_hostname | \
						  sed -e 's|\([^ ]*\)|"\1",|g' | \
						  sed -e 's|^[ ,]*\(.*\)|\1|' | sed -e 's|\(.*\)[ ,]$|\1|'`
	if [ -z "$sso_addrs_list" ]; then
		sso_addrs_list="null"
	fi
	db_select "SELECT ip_address FROM IP_Addresses WHERE ip_address in ($sso_addrs_list)"
	if [ -n "$db_select_output" ]; then
		return 0
	fi

	# if it does not - sso is most probably remote
	return 1
}

db_upgrade_sso_port_1010()
{
	db_upgrade_check_local_sso_is_used || return
	db_do "UPDATE misc SET val=REPLACE(val, ':11443', ':8443') WHERE param like 'sso%'";
	db_do "UPDATE misc SET val=REPLACE(val, ':11444', ':8443') WHERE param like 'sso%'";
}

db_optimize_configurations_table_1010()
{
    db_do "ALTER TABLE Configurations CHANGE objectId objectId INT UNSIGNED";
    db_do_if_not "SHOW INDEX FROM Configurations" "\$3 == \"objectTypeAndId_index\"" "CREATE INDEX objectTypeAndId_index ON Configurations (objectType, objectId)"
}

db_cleanup_exp_event_1010()
{
	db_test_table "exp_event" || return
	db_do "DELETE FROM exp_event WHERE obj_class=''"
}

db_upgrade_backups_scheduled_1011()
{
    db_fix_add_column BackupsScheduled content_type "ENUM('backup_content_all_at_domain', 'backup_content_vhost_only', 'backup_content_mail_only') DEFAULT 'backup_content_all_at_domain'"
}

db_upgrade_exp_event_obj_class_1011()
{
    db_fix_change_column "exp_event" "obj_class" "obj_class" "VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL"
}

db_upgrade_ssobranding_port_1011()
{
	db_upgrade_check_local_sso_is_used || return
	db_do "UPDATE SSOBranding SET idp_url=REPLACE(idp_url, ':11444', ':8443')"
}

db_upgrade_filesharing_1011()
{
	echo_try "Update filesharing data"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_filesharing_1011.php && suc || warn "fail\nCannot update filesharing information. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_filesharing_1011.php manually."
}

db_upgrade_resp_attach_1012()
{
    db_fix_change_column "resp_attach" "filename" "filename" "VARCHAR(245) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL"
}

db_upgrade_permissions_1012()
{
	echo_try "Setting default values of new permissions in subscriptions and service plans"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_permissions_1012.php && suc || warn "fail\nCannot set default values of new permissions in subscriptions and service plans. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_permissions_1012.php manually."
}

db_upgrade_add_simple_plan_1012()
{
	echo_try "create simple service plan"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/create_default_simple_template.php && suc || warn "fail\nCannot create simple service plan. Please run $PRODUCT_ROOT_D/admin/plib/scripts/create_default_simple_template.php manually."
}

db_upgrade_dns_reverse_ptr_ipv6_1012()
{
	db_do_if_not "SHOW INDEX FROM dns_recs" "\$3 == \"host\"" "CREATE INDEX host ON dns_recs (host)"

	db_do_if_not \
		"SELECT id FROM dns_recs_t WHERE type='PTR' AND host='<ipv6>'" 1 \
		"REPLACE INTO dns_recs_t(displayHost, host, type, displayVal, val, opt, time_stamp) VALUES('<ipv6>', '<ipv6>', 'PTR', '<domain>.', '<domain>.', 64, NOW())"
}

db_upgrade_php_settings_1012()
{
	echo_try "Update existing PHP settings information in service plans and hostings"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_php_settings_1012.php && suc || warn "fail\nCannot convert PHP settings. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_php_settings_1012.php manually."
}

db_upgrade_mail_domain_services_1012()
{
	echo_try "Upgrade mail domain services"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_mail_domain_services_1012.php && suc || warn "fail\nCannot upgrade mail domain services. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_mail_domain_services_1012.php manually."
}

db_upgrade_dns_wwwprefix_1012()
{
	echo_try "update www records for domain aliases"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_dns_1012.php && suc || warn "fail\nnCannot upgrade dns for domain aliases. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_dns_1012.php manually."
}

db_upgrade_upgrade_history_1012()
{
	db_fix_change_column "upgrade_history" "db_version" "db_version" "VARCHAR(50) CHARACTER SET ascii COLLATE ascii_bin NOT NULL"
}
db_upgrade_configurations_1013()
{
	db_fix_add_column "Configurations" "active" "enum('false', 'true') NOT NULL DEFAULT 'true'"
}

db_upgrade_subdomains_zones_1013()
{
	echo_try "Upgrade mode of DNS zones for subdomains"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_subdomains_zones_1013.php && suc || warn "fail\nnCannot upgrade mode of DNS zones for subdomains. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_subdomains_zones_1013.php manually."
}

db_upgrade_admin_simple_plan_permissions_1013()
{
	echo_try "Upgrade permissions for Admin Simple Plan"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_admin_simple_plan_permissions_1013.php && suc || warn "fail\nnCannot upgrade permissions for Admin Simple Plan. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_admin_simple_plan_permissions_1013.php manually."
}

db_upgrade_secret_key_1013()
{
	db_fix_add_column "secret_keys" "client_id" "INT UNSIGNED NOT NULL DEFAULT 1"
	db_do_if_not "SHOW INDEX FROM secret_keys" "\$3 == \"client_id\"" "ALTER TABLE secret_keys ADD INDEX (client_id)"
}

db_upgrade_dns_1013()
{
    db_do "delete from dns_refs where status = 'syn'"
    sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_dns_1011.php && suc || warn "fail\nfix upgrade dns"
    db_do "update dns_zone set syncSoa='skip', syncRecords='skip' where id not in (select val from misc where param='default_dns_zone_id')"
}

db_upgrade_sessions_1013()
{
	db_fix_add_column "sessions" "ip_dual_stack" "VARCHAR(39) CHARACTER SET ascii COLLATE ascii_general_ci"
}

db_upgrade_aps_settings_1013()
{
    db_do "delete from smb_apsSettings"
}
db_add_ftp_sys_users()
{
    db_fix_add_column sys_users mapped_to "INT UNSIGNED"
    db_do_if_not "SHOW INDEX FROM sys_users" "\$3 == \"mapped_to\"" "ALTER TABLE sys_users ADD INDEX (mapped_to)"
}

db_add_plans_schema()
{
    db_fix_add_column "clients" "vendor_id" "INT UNSIGNED"
    db_do "UPDATE clients SET vendor_id = parent_id WHERE ISNULL(vendor_id) AND !ISNULL(parent_id)"

    db_fix_add_column "domains" "vendor_id" "INT UNSIGNED"
    db_do "UPDATE domains SET vendor_id = cl_id WHERE ISNULL(vendor_id)"

    db_fix_del_column "Templates" "note_id"

    db_fix_add_column "Templates" "owner_id" "INT UNSIGNED"
    db_fix_add_column "Templates" "type" "ENUM('reseller', 'client', 'domain', 'domain_addon')"
    db_fix_add_column "Templates" "uuid" "VARCHAR(36)"
}

db_add_plans_data()
{
    script="$PRODUCT_ROOT_D/admin/plib/scripts/upgrade_plans.php"
    if [ -f "$script" ]; then
        sw_engine_pleskrun "$script" >> "$product_log" 2>&1
    fi

    db_do_if_not "SHOW INDEX FROM clients" "\$3 == \"vendor_id\"" "ALTER TABLE clients ADD INDEX (vendor_id)"

    db_fix_change_column "domains" "vendor_id" "vendor_id" "INT UNSIGNED NOT NULL"
    db_do_if_not "SHOW INDEX FROM domains" "\$3 == \"vendor_id\"" "ALTER TABLE domains ADD INDEX (vendor_id)"

    db_fix_change_column "Templates" "uuid" "uuid" "VARCHAR(36) NOT NULL"
    db_fix_change_column "Templates" "owner_id" "owner_id" "INT UNSIGNED NOT NULL"
    db_fix_change_column "Templates" "type" "type" "ENUM('reseller', 'client', 'domain', 'domain_addon') NOT NULL"
    db_do_if_not "SHOW INDEX FROM Templates" "\$3 == \"owner_id\"" "ALTER TABLE Templates ADD INDEX (owner_id)"
    db_do_if_not "SHOW INDEX FROM Templates" "\$3 == \"uuid\"" "ALTER TABLE Templates ADD UNIQUE(uuid)"

    script="$PRODUCT_ROOT_D/admin/plib/scripts/upgrade_plans_shared.php"
    if [ -f "$script" ]; then
		sw_engine_pleskrun "$script" >> "$product_log" 2>&1
    fi
}

db_add_webspaces()
{
# Add and populate www_root for domains
	if ! db_test_column "hosting"  "www_root"; then
		db_fix_add_column "hosting" "www_root" "TEXT CHARACTER SET ascii COLLATE ascii_bin NOT NULL"
		db_do 'UPDATE hosting, domains SET hosting.www_root=CONCAT("'$HTTPD_VHOSTS_D'/", domains.name, "/httpdocs") WHERE hosting.dom_id=domains.id'
	fi

# Add and populate www_root for subdomains
	db_fix_add_column "subdomains" "www_root" "TEXT CHARACTER SET ascii COLLATE ascii_bin NOT NULL"
	db_do 'UPDATE subdomains, domains SET subdomains.www_root=CONCAT("'$HTTPD_VHOSTS_D'/", domains.name, "/subdomains/", subdomains.name, "/httpdocs") WHERE subdomains.dom_id=domains.id'

# webspace_id for domains + index. 0 by default
	db_fix_add_column "domains"	"webspace_id" "INT UNSIGNED NOT NULL DEFAULT 0"
	db_do_if_not "SHOW INDEX FROM domains" "\$3 == \"webspace_id\"" "ALTER TABLE domains ADD INDEX (webspace_id)"

# webspace_status, if status !=0 it will be 2
	if ! db_test_column "domains" "webspace_status"; then
		db_fix_add_column "domains" "webspace_status" "BIGINT UNSIGNED NOT NULL DEFAULT 0"
		db_do "UPDATE domains SET webspace_status=status, status=2 WHERE status <> 0"
	fi

# Migrate 'native' users of subdomains to additional-ftp-accounts and drop 'sys_user_type' from subdomains
	if db_test_column "subdomains" "sys_user_type"; then
		sw_engine_pleskrun $PRODUCT_BOOTSTRAPPER_DIR/db/convert_sysusers_107.php "subdomains" && \
		db_fix_del_column "subdomains" "sys_user_type" || warn "Cannot convert 'native' subdomain users to additional ftp accounts"
	fi

# Remove uniq(sys_user_id) from hosting
	db_do_if "SHOW INDEX FROM hosting" "\$3 == \"sys_user_id\"" "ALTER TABLE hosting DROP INDEX sys_user_id"

# Map all webuser's sysusers to main domain's ftp system users
# and chown vhost's dir data are owned by webusers
	sw_engine_pleskrun $PRODUCT_BOOTSTRAPPER_DIR/db/convert_sysusers_107.php "webusers" || warn "Cannot map webusers to domain ftp users"

	db_fix_add_column "disk_usage" "www_root" "BIGINT UNSIGNED DEFAULT 0"
}

db_add_domain_permissions()
{
    db_fix_add_column "domains" "permissions_id" "INT UNSIGNED NOT NULL DEFAULT 0"
}

db_migrate_sb_data_107()
{
	if ! db_test_table "SBSites" || ! db_test_table "SBConfig"; then
		return
	fi

	echo_try "save legacy sitebuilder url data"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/save_sb_links.php && suc || warn "migration of legacy sitebuilder url data"
}

db_default_skin_107()
{
	echo_try "register default skin"
	db_do "DELETE from Skins"
	db_do "REPLACE INTO Skins (id, name, place) values (1, 'Default', 'default')"

# Update client, domains, mailnames
	db_do "UPDATE cl_param SET val=1 WHERE param='skin_id'"
	db_do "UPDATE dom_param SET val=1 WHERE param='skin_id'"
	db_do "UPDATE mn_param SET val=1 WHERE param='skin_id'"

# Update misc
	db_do "UPDATE misc SET val=1 WHERE param='admin_skin_id'"
	db_do "UPDATE misc SET val=1 WHERE param='def_skin_id'"

	suc
}

db_unlimited_client_expiration_107()
{
	echo_try "change client/reseller expiration to unlimited"
	db_do "UPDATE Limits SET value=-1 WHERE limit_name='expiration' AND id IN (SELECT limits_id FROM clients WHERE limits_id IS NOT NULL)"
	suc
}

db_clean_up_ip_pool_107()
{
	echo_try "clean up unused ip adresses from client ip pools"
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/ip_clean_107.php && suc || warn "fail\nCannot clean up clients ip pools"
}

db_billing_integration_107()
{
	db_fix_drop_table "BillingCache"
	db_fix_add_column "clients" "external_id" "VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT ''"
	db_fix_add_column "domains" "external_id" "VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT ''"
	db_fix_add_column "Templates" "external_id" "VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT ''"
}

db_upgrade_hp_mail_107()
{
	db_fix_add_column "mail" "userId" "INT UNSIGNED NOT NULL DEFAULT 0"
}

db_update_sessions_107()
{
	echo_try "Update sessions"
	db_do "DELETE from sessions"

	db_fix_add_column "sessions" "modified" "INT UNSIGNED"
	db_fix_add_column "sessions" "lifetime" "INT UNSIGNED"
	db_fix_add_column "sessions" "data" "TEXT CHARACTER SET binary"

	suc
}

db_migrate_sa_prefs_107()
{
	echo_try "Update SA preferences"

	if ! db_test_column "spamfilter" "reject_spam"; then
		pnnl_echo "already done"
		return
	fi

	if ! sw_engine_pleskrun $PRODUCT_BOOTSTRAPPER_DIR/db/migrate_sa_prefs_107.php; then
		die "Cannot migrate spamasassin preferences"
	fi

	db_fix_del_column "spamfilter" "reject_spam"
	suc
}
db_change_domain_admins_length_108()
{
	db_fix_change_column "clients" "login" "login" "VARCHAR(255)"
}

db_subscription_limits_default_values_108()
{
        local subscription_id;
        local limit_name="$1";
        local limit_default_value="$2";
        db_select "select d.id from domains d LEFT join Limits l on l.id = d.limits_id AND l.limit_name = '$limit_name' WHERE 0 = d.webspace_id AND l.value IS NULL";
        for subscription_id in $db_select_output; do
            db_do "INSERT INTO Limits (id, limit_name, value) SELECT d.limits_id, '$limit_name', $limit_default_value FROM domains d WHERE d.id=$subscription_id"
            db_select "SELECT d.limits_id FROM domains d WHERE d.id=$subscription_id";
            if [ "X${db_select_output}" = "X0" ]; then
                db_do "UPDATE domains SET limits_id=last_insert_id() WHERE id=$subscription_id";
            fi
        done
}

db_upgrade_clients_idn_109()
{
    db_fix_change_column "clients" "login" "login" "VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL"
}

db_upgrade_subscriptions_109()
{
    db_fix_add_column Subscriptions custom "ENUM('true', 'false') NOT NULL DEFAULT 'false'"
    db_fix_add_column Subscriptions uuid "VARCHAR(36) CHARACTER SET ascii COLLATE ascii_general_ci"
    
    echo_try "Assign missing UUIDs to subscriptions"

# Note, script is named *_108.php, because we change version of core 
# from 10.8.1 to 10.9.0. Renaming script is wrong idea, because it is
# executed on windows side
    sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_subscriptions_108.php && suc || warn "fail\nCannot update subscriptions information. Please run $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_subscriptions_108.php manually."
}

db_upgrade_custom_buttons_109()
{
    db_fix_add_column custom_buttons plan_item_name "VARCHAR(255) CHARACTER SET ascii COLLATE ascii_general_ci"
}

db_upgrade_maintenance_mode_109()
{
    db_fix_add_column hosting maintenance_mode "ENUM('false','true') NOT NULL DEFAULT 'false'"
    db_fix_add_column subdomains maintenance_mode "ENUM('false','true') NOT NULL DEFAULT 'false'"
}

insert_localhost_poplock_500()
{
	inten="enable localhost SMTP relaying for Mailman"

	query="select count(ip_address) from smtp_poplocks where
		ip_address='127.0.0.0' and ip_mask='8' and lock_time is NULL"
	rcd_number=`echo ${query} | ${mysql}`;

	if [ 0$rcd_number -lt 1 ]; then
		query="insert into smtp_poplocks (ip_address, ip_mask)
			values('127.0.0.0','8')"
		echo ${query} | ${mysql} || die ${inten};
	fi
}

fix_database_names_500()
{
	inten="fix database names"
	echo_try ${inten}

	query="USE mysql; SELECT Db FROM db"
	data_bases=`echo ${query} | ${mysql_raw}`

	for i in ${data_bases}; do

		# check the database to have underscores
		chk_usc=`echo ${i} | grep "_"`

		if [ "X${chk_usc}" != "X" ]; then

			fixed_name=`echo ${i} | awk '{ gsub("[\x5c\x5c]_","_"); gsub("_","\\\\_"); print $0}'`
			query="USE mysql; UPDATE db set Db='${fixed_name}' where Db='${i}'"
			echo ${query} | ${mysql} || die ${inten};
		fi
	done >> "${product_log}" 2>&1 || die "${inten}"

	query="USE mysql; FLUSH PRIVILEGES"
	echo ${query} | ${mysql} || die ${inten};

	suc
}

add_changes_500()
{
	inten="upgrade SQL database"
	echo_try "$inten"
	$mysql < $upgrade_db_sql >> "$product_log" 2>&1 && suc || die "$inten"
}

# Task: Client-Domain Expiration
# setting 'status' field with flags
update_domain_status_500()
{
        inten="set required flags in domain status"
        echo_try ${inten}

        tabs="Parameters p, dom_param dp, domains d, clients c"
        cond="p.parameter='turned_off' AND p.id=dp.val AND
                  dp.param='param_id' AND dp.dom_id=d.id  AND
                  d.cl_id=c.id AND c.status<>0" # client status already upgraded to be int flag

        # process all the domains which were turned off with client (parent)
        query_w_parent="SELECT d.id FROM domains d, clients c WHERE c.id=d.cl_id AND c.status<>0;"
        for dom_id in `echo "$query_w_parent" | $mysql`; do
                # detect real  STATUS_ADMIN flag
                query_status="SELECT p.value FROM $tabs WHERE $cond AND d.id='$dom_id';"
                stored_status=`echo "$query_status" | $mysql`
                if [ "X$stored_status" = "X" ]; then
                    stored_status='false'
                fi
                # set appropriate STATUS_WITH_PARENT & STATUS_ADMIN flag
                query_update="UPDATE domains SET status = (status | (2 + 16*('$stored_status'='false'))*(admin_status='false')) WHERE id='$dom_id';"   # STATUS_WITH_PARENT=2
                echo "$query_update" | $mysql
        done >> "$product_log" 2>&1 || die "$inten"

		# process all the domains which were NOT turned off with client
        query_wo_parent="SELECT d.id FROM domains d, clients c WHERE c.id=d.cl_id AND c.status=0;"
        for dom_id in `echo "$query_wo_parent" | $mysql`; do
			query_admin="UPDATE domains SET status = (status | (16 * (admin_status = 'false'))) WHERE id='$dom_id'"
			echo "$query_admin" | $mysql >> "$product_log" 2>&1 || die "$inten"
		done

		# drop unrequired column
		query_drop="ALTER TABLE domains DROP COLUMN admin_status"
		echo "$query_drop" | $mysql >> "$product_log" 2>&1 || die "$inten"
		# remove unrequired parameter
		query_delete="DELETE FROM Parameters WHERE parameter='turned_off'"
		echo "$query_delete" | $mysql >> "$product_log" 2>&1 || die "$inten"

        suc
}

# Task: Client-Domain Expiration
# transferring IDs of objects corresponded to client & domain
move_corresp_ids_500()
{
	inten="transfer corresponded ID for client&domain objects"
	echo_try "$inten"


 	move_id_500 'dom_param'	'lim_id'			'domains'	'limits_id'	'dom_id'	"$inten"	# domain limits
 	move_id_500 'dom_param'	'param_id'			'domains'	'params_id'	'dom_id'	"$inten"	# domain params

 	move_id_500 'cl_param'	'lim_id'			'clients'	'limits_id'	'cl_id'		"$inten"	# client limits
 	move_id_500 'cl_param'	'param_id'			'clients'	'params_id'	'cl_id'		"$inten"	# client params
 	move_id_500 'cl_param'	'perm_id'			'clients'	'perm_id'	'cl_id'		"$inten"	# client permissions
 	move_id_500 'cl_param'	'pool_id'			'clients'	'pool_id'	'cl_id'		"$inten"	# client ip pool
 	move_id_500 'cl_param'	'logo_id'			'clients'	'logo_id'	'cl_id'		"$inten"	# client logo
 	move_id_500 'cl_param'	'dom_tmpl_list_id'	'clients'	'tmpl_id'	'cl_id'		"$inten"	# client template
	suc
}

move_id_500()
{
	# Trasfer data from table-list to table-object
	src_table="$1"	# name of table-list
	src_param="$2"	# name of parameter in table-list
	dst_table="$3"	# name of table-object
	dst_param="$4"	# name of parameter (column) in table-object
	refer_col="$5"	# name of table-list column which refers to table-object

	inten="$6"

    query="SELECT t.id FROM $dst_table t, $src_table tp WHERE t.id=tp.$refer_col AND tp.param='$src_param';"
    for id in `echo "$query" | $mysql`; do
    	query_pvalue="SELECT val FROM $src_table WHERE $refer_col='$id' AND param='$src_param';"
		param_val=`echo "$query_pvalue" | $mysql`
		query_update="UPDATE $dst_table SET $dst_param='$param_val' where id='$id';"
		echo "$query_update" | $mysql >> "$product_log" 2>&1 || die "$inten"
	done >> "$product_log" 2>&1

	# clean table-list
	query_delete="DELETE FROM $src_table WHERE param = '$src_param';"
	echo "$query_delete" | $mysql >> "$product_log" 2>&1 || die "$inten"
}

check_ip_matching_500()
{
	local first_byte second_byte third_byte fourth_byte

	# Arguments:
	# $1 - first IP address
	# $2 - second IP address
	# $3 - netmask

	# Return values:
	# 0 - addresses are in same network
	# 1 - addresses are in different networks

	first_byte1=`echo $1 | awk -F "." '{ print $1; }'`
	second_byte1=`echo $1 | awk -F "." '{ print $2; }'`
	third_byte1=`echo $1 | awk -F "." '{ print $3; }'`
	fourth_byte1=`echo $1 | awk -F "." '{ print $4; }'`

	first_byte2=`echo $2 | awk -F "." '{ print $1; }'`
	second_byte2=`echo $2 | awk -F "." '{ print $2; }'`
	third_byte2=`echo $2 | awk -F "." '{ print $3; }'`
	fourth_byte2=`echo $2 | awk -F "." '{ print $4; }'`

	first_byte3=`echo $3 | awk -F "." '{ print $1; }'`
	second_byte3=`echo $3 | awk -F "." '{ print $2; }'`
	third_byte3=`echo $3 | awk -F "." '{ print $3; }'`
	fourth_byte3=`echo $3 | awk -F "." '{ print $4; }'`

	let first_byte1="${first_byte1}&${first_byte3}"
	let second_byte1="${second_byte1}&${second_byte3}"
	let third_byte1="${third_byte1}&${third_byte3}"
	let fourth_byte1="${fourth_byte1}&${fourth_byte3}"

	let first_byte2="${first_byte2}&${first_byte3}"
	let second_byte2="${second_byte2}&${second_byte3}"
	let third_byte2="${third_byte2}&${third_byte3}"
	let fourth_byte2="${fourth_byte2}&${fourth_byte3}"

	if [ 0${first_byte1} -eq 0${first_byte2} -a \
			0${second_byte1} -eq 0${second_byte2} -a \
			0${third_byte1} -eq 0${third_byte2} -a \
			0${fourth_byte1} -eq 0${fourth_byte2} ]; then
		return 0
	fi

	return 1
}

find_appropriate_iface_500()
{
	local ip ip_list ip_mask

	# Arguments:
	# $1 - IP address

	# Return values:
	# $APPROPRIATE_IFACE - recommented interface
	# $APPROPRIATE_NETMASK - recommented netmask

	query="SELECT DISTINCT iface FROM IP_Addresses ORDER by iface LIMIT 1"

	APPROPRIATE_IFACE=`echo ${query} | ${mysql}`
	APPROPRIATE_NETMASK="255.255.255.0"

	query="SELECT ip_address FROM IP_Addresses"
	ip_list=`echo ${query} | ${mysql}`

	for ip in ${ip_list}; do

		query="SELECT mask FROM IP_Addresses WHERE ip_address='${ip}'"
		ip_mask=`echo ${query} | ${mysql}`

		check_ip_matching_500 $1 ${ip} ${ip_mask}
		if [ $? -eq 0 ]; then

			# we found the interface
			query="SELECT iface FROM IP_Addresses WHERE ip_address='${ip}'"
			APPROPRIATE_IFACE=`echo ${query} | ${mysql}`
			APPROPRIATE_NETMASK=${ip_mask}
			break
		fi
	done
}

rebuild_ip_pool_500()
{
	inten="reread IP addresses from network interfaces"
	echo_try $inten

	# remember NameVirtualHost value for type definition
	query="select val from misc where param='NameVirtualHost'"
	NameVirtualHost=`echo ${query} | ${mysql}`

	"${PRODUCT_ROOT_D}"/admin/sbin/ifmng -r >/dev/null && suc || die "$inten"

	inten="restore lost IP addresses from hosting table"

	# select all domains with hosting
	query="SELECT dom_id FROM hosting"
	dom_list=`echo ${query} | ${mysql}`

	for dom_id in ${dom_list}; do

		# get IP address of hosting
		query="SELECT ip_address FROM hosting where dom_id='${dom_id}'"
		ip=`echo ${query} | ${mysql}`

		query="SELECT ip_address FROM IP_Addresses WHERE ip_address='${ip}'"
		ip_active=`echo ${query} | ${mysql}`

		if [ "X${ip_active}" = "X" ]; then
			# lost ip is detected

			find_appropriate_iface_500 ${ip}

			query="INSERT into IP_Addresses (ip_address, mask, iface,
				type, ssl_certificate_id, default_domain_id)
				VALUES ('${ip}', '${APPROPRIATE_NETMASK}',
				'${APPROPRIATE_IFACE}', 'Exclusive', '0', '${dom_id}')"
			echo ${query} | ${mysql} || die ${inten}
		fi
	done >> "${product_log}" 2>&1 || die "${inten}"

	inten="restore lost IP addresses from IP pools"

	query="SELECT ip from IPPool"
	ip_list=`echo ${query} | ${mysql}`

	for ip in ${ip_list}; do

		query="SELECT ip_address FROM IP_Addresses WHERE ip_address='${ip}'"
		ip_active=`echo ${query} | ${mysql}`

		if [ "X${ip_active}" = "X" ]; then
			# lost ip is detected

			find_appropriate_iface_500 ${ip}

			query="INSERT into IP_Addresses (ip_address, mask, iface,
				type, ssl_certificate_id)
				VALUES ('${ip}', '${APPROPRIATE_NETMASK}',
				'${APPROPRIATE_IFACE}', 'Exclusive', '0')"
			echo ${query} | ${mysql} || die ${inten};

		fi
	done >> "${product_log}" 2>&1 || die "${inten}"

	inten="defince types of available IP addresses"
	query="UPDATE IP_Addresses SET type='Shared' WHERE ip_address = '${NameVirtualHost}'"
	echo ${query} | ${mysql} || die ${inten};

	query="UPDATE IP_Addresses SET type='Exclusive' WHERE ip_address != '${NameVirtualHost}'"
	echo ${query} | ${mysql} || die ${inten};

}

multiple_nb_ip_500()
{
	local dom_list dom_id ip ip_active address_type hosting_list ip_id pool_list pool_id ip_list client_repository_id cl_id cl_list perm_id

	# fetch default certificate id
	query="select val from misc where param='default_certificate_id'"
	default_certificate_id=`echo ${query} | ${mysql}`

	if [ "X${default_certificate_id}" = "X" ]; then
		die "define default certificate id for virtual hosting upgrade"
	fi

	inten="replace ip addresses by ip identifiers in hosting table"

	query="SELECT dom_id from hosting"
	hosting_list=`echo ${query} | ${mysql}`

	for dom_id in ${hosting_list}; do

		query="select IP_Addresses.id from IP_Addresses, hosting where
			IP_Addresses.ip_address = hosting.ip_address and hosting.dom_id=${dom_id}"
		ip_id=`echo ${query} | ${mysql}`

		if [ "X${ip_id}" = "X" ]; then
			die ${inten}". IP address missing for hosting #${dom_id}"
		fi

		query="UPDATE hosting SET ip_address_id='${ip_id}' WHERE dom_id='${dom_id}'"
		echo ${query} | ${mysql} || die ${inten};

	done >> "${product_log}" 2>&1 || die "${inten}"

	# remove deprecated column ip_address
	query="ALTER TABLE hosting DROP COLUMN ip_address"
	echo ${query} | ${mysql} || die ${inten}


	inten="update forwarding table table"

	query="SELECT id FROM IP_Addresses WHERE ip_address = '${NameVirtualHost}'"
	ip_id=`echo ${query} | ${mysql}`

	query="UPDATE forwarding SET ip_address_id='${ip_id}'"
	echo ${query} | ${mysql} || die ${inten};

	inten="remove unnecessary NameVirtualHost parameter from misc table"

	query="DELETE FROM misc WHERE param='NameVirtualHost'"
	echo ${query} | ${mysql} || die ${inten};

	inten="move IP pools to Repository"

	query="SELECT DISTINCT id FROM IPPool"
	pool_list=`echo ${query} | ${mysql}`

	# transfer each IP pool to Repository
	for pool_id in ${pool_list}; do

		client_repository_id=0

		# select id of pool owner
		query="SELECT cl_id FROM cl_param WHERE param='pool_id' and val='${pool_id}'"
		cl_id=`echo ${query} | ${mysql}`

		# select all IPs from pool
		query="SELECT ip FROM IPPool WHERE id='${pool_id}'"
		ip_list=`echo ${query} | ${mysql}`

		for ip in ${ip_list}; do

			# get id for this address
			query="SELECT id FROM IP_Addresses WHERE ip_address='${ip}'"
			ip_id=`echo ${query} | ${mysql}`

			if [ ${client_repository_id} -eq 0 ]; then

				# register new ip pool in Repository for client
				query="REPLACE INTO Repository SET component_id='${ip_id}';
						SELECT LAST_INSERT_ID()"
				client_repository_id=`echo ${query} | ${mysql}`

				if [ "X${client_repository_id}" = "X" ]; then
					die $inten
				fi
			else

				query="REPLACE INTO Repository SET rep_id='${client_repository_id}',
						component_id='${ip_id}'"
				echo ${query} | ${mysql} || die ${inten};
			fi

		done

		# Link client to new IP repository
		query="REPLACE INTO cl_param SET val='${client_repository_id}',
				param='repository_pool_id', cl_id='${cl_id}'"
		echo ${query} | ${mysql} || die ${inten};

	done >> "${product_log}" 2>&1 || die "${inten}"

	query="DELETE FROM cl_param where param='pool_id'"
	echo ${query} | ${mysql} || die ${inten};

	query="UPDATE cl_param SET param='pool_id' WHERE param='repository_pool_id'"
	echo ${query} | ${mysql} || die ${inten};

	inten="drop deprecated IPPool table"

	query="DROP TABLE IPPool"
	echo ${query} | ${mysql} || die ${inten};

	inten="fill IP Pools of clients with addresses from hosting"

	query="SELECT dom_id FROM hosting"
	hosting_list=`echo ${query} | ${mysql}`

	# each ip in hosting must be in corresponding ip pool in repository
	for dom_id in ${hosting_list}; do

		query="SELECT ip_address_id FROM hosting WHERE dom_id='${dom_id}'"
		ip_id=`echo ${query} | ${mysql}`

		# get repository id for owner of this hosting
		query="SELECT cl_id FROM domains WHERE id='${dom_id}'"
		cl_id=`echo ${query} | ${mysql}`

		query="SELECT val FROM cl_param WHERE cl_id='${cl_id}' and param='pool_id'"
		client_repository_id=`echo ${query} | ${mysql}`

		if [ "X${client_repository_id}" = "X" -o 0${client_repository_id} -eq 0 ]; then

			# register new ip pool in repository for client
			query="REPLACE INTO Repository SET component_id='${ip_id}';
					SELECT LAST_INSERT_ID()"
			client_repository_id=`echo ${query} | ${mysql}`
			if [ "X${client_repository_id}" = "X" ]; then
				die $inten
			fi

			# tie new pool in client's parameters
			query="REPLACE INTO cl_param SET cl_id='${cl_id}', param='pool_id',
			 val='${client_repository_id}'"
			echo ${query} | ${mysql} || die ${inten};

		else

			# insert this IP in client's pool, if it is not in pool already
			query="REPLACE INTO Repository SET rep_id='${client_repository_id}',
				component_id='${ip_id}'"
			echo ${query} | ${mysql} || die ${inten};
		fi

	done >> "${product_log}" 2>&1 || die "${inten}"

	inten="insert former NameVirtualHost IP to pools of clients"

	# get list of clients with NB hosting creation permission
	query="SELECT cl_param.cl_id FROM cl_param, Permissions
			WHERE cl_param.param='perm_id'
				AND Permissions.id=cl_param.val
				AND Permissions.permission='nb_allow'
				AND Permissions.value='true'"
	cl_list=`echo ${query} | ${mysql}`

	query="SELECT id FROM IP_Addresses WHERE ip_address = '${NameVirtualHost}'"
	ip_id=`echo ${query} | ${mysql}`

	for cl_id in ${cl_list}; do

		# check that client has ip pool
		query="SELECT val FROM cl_param WHERE cl_id='${cl_id}' and param='pool_id'"
		client_repository_id=`echo ${query} | ${mysql}`

		if [ "X${client_repository_id}" = "X" -o 0${client_repository_id} -eq 0 ]; then

			# create new pool in repository and register it for client
			query="REPLACE INTO Repository
					SET component_id='${ip_id}';
					SELECT LAST_INSERT_ID()"

			client_repository_id=`echo ${query} | ${mysql}`
			if [ "X${client_repository_id}" = "X" ]; then
				die $inten
			fi

			# tie new pool in client's parameters
			query="REPLACE INTO cl_param SET param='pool_id',
			 val='${client_repository_id}', cl_id='${cl_id}'"
			echo ${query} | ${mysql} || die ${inten};

		else

			# insert NameVirtualHost to client's pool
			query="REPLACE INTO Repository
					SET rep_id='${client_repository_id}', component_id='${ip_id}'"
			echo ${query} | ${mysql} || die ${inten};
		fi

	done

	inten="upgrade clients permissions"

	# remove deprecated permissions
	query="DELETE FROM Permissions WHERE permission='ipb_allow' OR permission='nb_allow'"
	echo ${query} | ${mysql} || die ${inten};

	# get list of clients with permission of domain creation
	query="SELECT cl_param.cl_id FROM cl_param, Permissions
			WHERE cl_param.param='perm_id'
				AND Permissions.id=cl_param.val
				AND Permissions.permission='create_domains'
				AND Permissions.value='true'"
	cl_list=`echo ${query} | ${mysql}`

	# enable hosting management for clients, that have domain creation permission
	for cl_id in ${cl_list}; do

		# get permission id of client
		query="SELECT val FROM cl_param WHERE param='perm_id' and cl_id='${cl_id}'"
		perm_id=`echo ${query} | ${mysql}`

		query="REPLACE INTO Permissions SET id='${perm_id}', permission='manage_phosting', value='true'"
		echo ${query} | ${mysql} || die ${inten};

	done

	# delete deprecated parameters
	query="DELETE FROM Parameters WHERE parameter='ip_set'"
	echo ${query} | ${mysql} || die ${inten};

	# upgrade domain templates
	inten="upgrade domain templates hosting types"

	query="UPDATE TmplData SET value = 'physical' WHERE element = 'vh_type' AND value != 'none'"
	echo ${query} | ${mysql} || die ${inten};

	suc
}

# import certificate from a file to certificates table
# $1 - certoificate file path
# $2 - short description of certificate
# last_certificate_id variable will contain its identifier
import_certificate_500()
{
	local certificate_file certificate_comment inten

	certificate_file=$1
	certificate_comment=$2

	cert_pub_val=`cat ${certificate_file} |
		awk 'BEGIN { state=0 }
		{
			if (state == 0) {
			 	if (index($0, "-BEGIN CERTIFICATE-") != 0) state = 1;
			};

			if (state == 1) {
				print $0;
				if (index($0, "-END CERTIFICATE-") != 0) state = 2;
			 }
		}' |
		perl -n -e 's/([^ A-Za-z0-9])/"%" . sprintf("%02X", unpack("C", $1))/ge; s/ /\+/g; print $_;'`

	cert_priv_val=`cat ${certificate_file} |
		awk 'BEGIN { state=0 }
		{
			if (state == 0) {
			 	if ((index($0, "-BEGIN ") != 0) &&
					(index($0, " PRIVATE KEY-") != 0)) state = 1;
			};

			if (state == 1) {
				print $0;
				if ((index($0, "-END ") != 0) &&
					(index($0, " PRIVATE KEY-") != 0)) state = 2;
			 }
		}' |
		perl -n -e 's/([^ A-Za-z0-9])/"%" . sprintf("%02X", unpack("C", $1))/ge; s/ /\+/g; print $_;'`

	if [ ! -d "${PRODUCT_ROOT_D}"/var/certificates ]; then

		inten="creating directory for certificates"
		mkdir -p "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}
		chown root:0 "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}
		chmod 500 "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}

	fi

	# copy certificate file to file repository
	newcertfile=`mktemp "${PRODUCT_ROOT_D}"/var/certificates/certXXXXXXX`

	cp "${certificate_file}" "${newcertfile}"  || die "place certificate to its directory"
	chown root:0 "${newcertfile}"
	chmod 400 "${newcertfile}"

	newcertfile=`basename ${newcertfile}`
	query="INSERT INTO certificates (pvt_key, cert, name, ca_cert, csr, cert_file, ca_file)
		VALUES ('${cert_priv_val}', '${cert_pub_val}', '${certificate_comment}', '', '',
					'${newcertfile}', '');
		SELECT LAST_INSERT_ID()"

	last_certificate_id=`printf "%s" "${query}" | ${mysql}`
}

# import rootchain certificate from a file to certificates table
# ARGUMENTS:
#	$1 - certoificate file path
#	$2 - short description of certificate
# RETURN:
#	last_certificate_id variable will contain its identifier
import_rootchain_certificate_500()
{
	local certificate_file certificate_comment inten

	certificate_file=$1
	certificate_id=$2
	certificate_comment=$3

	ca_cert_val=`cat "${certificate_file}" |
		awk 'BEGIN { state=0 }
		{
			if (state == 0) {
			 	if (index($0, "-BEGIN CERTIFICATE-") != 0) state = 1;
			};

			if (state == 1) {
				print $0;
				if (index($0, "-END CERTIFICATE-") != 0) state = 2;
			 }
		}' |
		perl -n -e 's/([^ A-Za-z0-9])/"%" . sprintf("%02X", unpack("C", $1))/ge; s/ /\+/g; print $_;'`


	if [ ! -d "${PRODUCT_ROOT_D}"/var/certificates ]; then

		inten="create directory for certificates"
		mkdir -p "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}
		chown root:0 "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}
		chmod 500 "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}

	fi

	inten="import rootchain certificate of ${certificate_comment}"

	# copy certificate file to file repository
	newcertfile=`mktemp "${PRODUCT_ROOT_D}"/var/certificates/certXXXXXXX`

	cp "${certificate_file}" "${newcertfile}" || die "place certificate to its directory"
	chown root:0 "${newcertfile}"
	chmod 400 "${newcertfile}"

	newcertfile=`basename ${newcertfile}`
	query="UPDATE certificates SET ca_cert='${ca_cert_val}', ca_file='${newcertfile}' WHERE id='${certificate_id}'"

	printf "%s" "${query}" | ${mysql} || die ${inten};
}

# import certificate to database when installing
_import_default_certificate()
{
	inten="import default certificate"

	if [ "X${do_upgrade}" = "X1" -a -f ${HTTPD_VHOSTS_D}/.skel/cert/httpd.pem ]; then
		default_certificate=${HTTPD_VHOSTS_D}/.skel/cert/httpd.pem
	else
		default_certificate=${certificate_file}
	fi

	query="SELECT val FROM misc WHERE param = 'default_certificate_id'"
	default_certificate_id=`echo ${query} | ${mysql}`

	if [ "X${default_certificate_id}" = "X" ]; then

		import_certificate_500 "${default_certificate}" "default certificate"

		default_certificate_id=${last_certificate_id}

		query="REPLACE INTO misc set param='default_certificate_id', val='${default_certificate_id}'"
		echo ${query} | ${mysql} || die ${inten};
	fi

	query="SELECT val FROM misc WHERE param = 'cert_rep_id'"
	admin_repository_id=`echo ${query} | ${mysql}`

	if [ "X${admin_repository_id}" = "X" ]; then

		# register new repository for admin
		query="REPLACE INTO Repository
				SET component_id='${default_certificate_id}';
				SELECT LAST_INSERT_ID();"

		admin_repository_id=`echo ${query} | ${mysql}`

		query="REPLACE INTO misc set param='cert_rep_id', val='${admin_repository_id}'"
		echo ${query} | ${mysql} || die ${inten};
	else
		# simple certificate insertion to repository
		query="REPLACE INTO Repository SET
				rep_id='${admin_repository_id}',
				component_id='${default_certificate_id}'"
		echo ${query} | ${mysql} || die ${inten};
	fi
}

# import certificate to database when upgrading
import_default_certificate_500()
{
	if [ "X${do_upgrade}" = "X1" ]; then

		inten="import default certificate"

		default_certificate=${HTTPD_VHOSTS_D}/.skel/cert/httpd.pem

		query="SELECT val FROM misc WHERE param = 'default_certificate_id'"
		default_certificate_id=`echo ${query} | ${mysql}`

		if [ "X${default_certificate_id}" = "X" ]; then

			import_certificate_500 "${default_certificate}" "default certificate"

			default_certificate_id=${last_certificate_id}

			query="REPLACE INTO misc set param='default_certificate_id', val='${default_certificate_id}'"
			echo ${query} | ${mysql} || die ${inten};

			query="UPDATE IP_Addresses SET ssl_certificate_id='${default_certificate_id}'"
			echo ${query} | ${mysql} || die ${inten};
		fi

		query="SELECT val FROM misc WHERE param = 'cert_rep_id'"
		admin_repository_id=`echo ${query} | ${mysql}`

		if [ "X${admin_repository_id}" = "X" ]; then

			# register new repository for admin
			query="REPLACE INTO Repository
					SET component_id='${default_certificate_id}';
					SELECT LAST_INSERT_ID();"

			admin_repository_id=`echo ${query} | ${mysql}`

			query="REPLACE INTO misc set param='cert_rep_id', val='${admin_repository_id}'"
			echo ${query} | ${mysql} || die ${inten};
		else
			# simple certificate insertion to repository
			query="REPLACE INTO Repository SET
					rep_id='${admin_repository_id}',
					component_id='${default_certificate_id}'"
			echo ${query} | ${mysql} || die ${inten};
		fi

		# here is also certificate for name-based hosting
		# that may be different with default certificate
		cert_path="${HTTPD_CONF_D}"/httpd.pem

		if [ -f "${cert_path}" ]; then

			# check, that it is not default certificate
			cert_diff=`diff ${cert_path} ${default_certificate}`

			# place certificate to admin repository
			if [ "X${cert_diff}" != "X" ]; then
				import_certificate_500 "${cert_path}" "former name-based hosting certificate"
				nbip_certificate_id=${last_certificate_id}

				# register certificate in repository of admin
				query="REPLACE INTO Repository
					SET rep_id='${admin_repository_id}',
					component_id='${nbip_certificate_id}';"

			else
				nbip_certificate_id=${default_certificate_id}
			fi

		else

			p_echo
			p_echo "***********************************************"
			p_echo "WARNING! Cannot find ${cert_path} certificate"
			p_echo "You may have problems with Apache SSL extension"
			p_echo "***********************************************"
			p_echo

		fi

		# last certificate - from admin apache
		cert_path="${PRODUCT_ROOT_D}"/admin/conf/httpsd.pem

		if [ -f "${cert_path}" ]; then

			# check, that it is not default certificate
			cert_diff=`diff ${cert_path} ${default_certificate}`

			# place certificate to admin repository
			if [ "X${cert_diff}" != "X" ]; then
				import_certificate_500 "${cert_path}" "certificate of control panel"
				admin_certificate_id=${last_certificate_id}

				# register certificate in repository of admin
				query="REPLACE INTO Repository
					SET rep_id='${admin_repository_id}',
					component_id='${admin_certificate_id}';"

			else
				admin_certificate_id=${default_certificate_id}
			fi

			# import rootchain certificate, if available
			cert_path="${PRODUCT_ROOT_D}"/admin/conf/rootchain.pem

			if [ -f ${cert_path} ]; then

				import_rootchain_certificate_500 "${cert_path}" "${admin_certificate_id}" "control panel"

			fi

		else

			p_echo
			p_echo "************************************************"
			p_echo "WARNING! Cannot find ${cert_path} certificate"
			p_echo "You may have connection problem to control panel"
			p_echo "************************************************"
			p_echo

		fi

	fi
}

rebuild_certificates_repository_500()
{
	local cert_dom_list cert_dom dom_name slave_id

	inten="rebuild certificates repository"

	query="UPDATE certificates SET name='certificate' WHERE dom_id='0'"
	echo ${query} | ${mysql} || die ${inten}

	query="SELECT DISTINCT dom_id FROM certificates"
	cert_dom_list=`echo ${query} | ${mysql}`

	# for each domain, that has certificates...
	for cert_dom in ${cert_dom_list}; do

		if [ "X${cert_dom}" != "X0" ]; then

			# get domain name for setup certificates name
			query="SELECT name FROM domains where id='${cert_dom}'"
			dom_name=`echo ${query} | ${mysql}`

			# set certificates name for this domain
			query="UPDATE certificates SET name='${dom_name}' WHERE dom_id='${cert_dom}'"
			echo ${query} | ${mysql} || die ${inten}

			# check, that repository is created for this domain
			query="SELECT cert_rep_id FROM domains where id='${cert_dom}'"
			repository_id=`echo ${query} | ${mysql}`
		else

			query="SELECT val FROM misc WHERE param = 'cert_rep_id'"
			repository_id=`echo ${query} | ${mysql}`
		fi

		query="SELECT id FROM certificates WHERE dom_id='${cert_dom}'"
		domain_certificates=`echo ${query} | ${mysql}`

		# each certificate in domain...
		for certificate_id in ${domain_certificates}; do

			# check, that certificate is not from slave (master feature)
			slave_id=""

			if [ "X${cert_dom}" = "X0" ]; then
				query="SELECT slave_id FROM slave_params WHERE parameter='cert_id' AND value='${certificate_id}'"
				slave_id=`echo ${query} | ${mysql}`
			fi

			if [ "X${slave_id}" = "X" ]; then

				# insert certificate into Repository
				if [ "X${repository_id}" = "X" -o "X${repository_id}" = "XNULL" -o "X${repository_id}" = "X0" ]; then

					# repository registration is required

					# insert certificate and create new Repository object
					query="INSERT INTO Repository (component_id)
						VALUES (${certificate_id});
						SELECT LAST_INSERT_ID()"
					repository_id=`echo ${query} | ${mysql}`

					if [ "X${cert_dom}" != "X0" ]; then
						# register new Repository in domain record
						query="UPDATE domains set cert_rep_id='${repository_id}'
							WHERE id='${cert_dom}'"
						echo ${query} | ${mysql} || die ${inten};
					else
						# register new repository for admin
						query="REPLACE INTO misc SET param = 'cert_rep_id', val='${repository_id}'"
						echo ${query} | ${mysql}
					fi

				else
					# simple certificate insertion to repository
					query="REPLACE INTO Repository SET
						rep_id='${repository_id}',
						component_id='${certificate_id}'"
					echo ${query} | ${mysql} || die ${inten};
				fi
			fi
		done
	done
}

ssl_cert_management_500()
{
	local repository_id cert_pub_val cert_priv_val cert_dom_list cert_dom domain_certificates certificate_id domains dom_name cert_path cert_diff cert_list

	inten="import hosting certificates to new repository"
	echo_try $inten

	# import certificates from hosting to certificate repositories
	query="SELECT domains.id FROM domains, hosting WHERE domains.id = hosting.dom_id"
	domains=`echo ${query} | ${mysql}`

	# for each domain with hosting
	for dom_id in ${domains}; do

		query="SELECT name FROM domains WHERE id='${dom_id}'"
		dom_name=`echo ${query} | ${mysql}`

		cert_path=${HTTPD_VHOSTS_D}/$dom_name/cert/httpd.pem

		if [ -f ${cert_path} ]; then

			import_certificate_500 "${cert_path}" "${dom_name}"
			certificate_id=${last_certificate_id}

			# update ip address with certificate id, used for this hosting
			query="SELECT ip_address FROM hosting WHERE dom_id='${dom_id}'"
			ip_address=`echo ${query} | ${mysql}`

			if [ "X${ip_address}" != "X${NameVirtualHost}" ]; then
				query="UPDATE IP_Addresses SET ssl_certificate_id='${certificate_id}'
					WHERE ip_address='${ip_address}'"
				echo ${query} | ${mysql} || die ${inten};
			fi

			# check, that certificates repository is created for this domain
			query="SELECT cert_rep_id FROM domains where id='${dom_id}'"
			repository_id=`echo ${query} | ${mysql}`

			# insert certificate into Repository
			if [ "X${repository_id}" = "X" -o "X${repository_id}" = "XNULL" -o "X${repository_id}" = "X0" ]; then

				# repository registration is required

				# insert certificate and create new Repository object
				query="INSERT INTO Repository (component_id)
					VALUES (${certificate_id});
					SELECT LAST_INSERT_ID()"
				repository_id=`echo ${query} | ${mysql}`

				# register new Repository in domain record
				query="UPDATE domains set cert_rep_id='${repository_id}'
					WHERE id='${dom_id}'"
				echo ${query} | ${mysql} || die ${inten};

			else
				# simple certificate insertion to repository
				query="REPLACE INTO Repository SET
						rep_id='${repository_id}',
						component_id='${certificate_id}'"
				echo ${query} | ${mysql} || die ${inten};
			fi

			# import rootchain certificate for domain, if available
			cert_path=${HTTPD_VHOSTS_D}/$dom_name/cert/rootchain.pem

			if [ -f ${cert_path} ]; then

				import_rootchain_certificate_500 "${cert_path}" "${certificate_id}" "${dom_name}"

			fi

		fi

	done

	# update former nb hosting with its certficate, if it differs from default
	if [ "X${nbip_certificate_id}" != "X${default_certificate_id}" ]; then
		query="UPDATE IP_Addresses SET ssl_certificate_id='${nbip_certificate_id}'
				WHERE ip_address='${NameVirtualHost}'"
		echo ${query} | ${mysql} || die ${inten};
	fi

	# move pub_key to cert field and urlencode them for master feature certificates
	inten="upgrade master feature SSL certificates"

	query="SELECT value FROM slave_params WHERE parameter='cert_id'"
	cert_list=`echo ${query} | ${mysql}`

	for certificate_id in ${cert_list}; do

		query="SELECT slave_id FROM slave_params WHERE parameter='cert_id' and value='${certificate_id}'"
		slave_id=`echo ${query} | ${mysql}`

		query="SELECT value FROM slave_params WHERE parameter='cert_file' and slave_id='${slave_id}'"
		cert_file=`echo ${query} | ${mysql}`

		# enterprise query will regenerate certificates after its first request
		rm -f "${cert_file}"

		query="SELECT pub_key FROM certificates WHERE id='${certificate_id}'"
		cert_pub_val=`echo ${query} | ${mysql_raw} |
				perl -n -e 's/([^ A-Za-z0-9])/"%" . sprintf("%02X", unpack("C", $1))/ge; s/ /\+/g; print $_;'`

		query="UPDATE certificates SET cert='${cert_pub_val}' WHERE id='${certificate_id}'"
		printf "%s" "${query}" | ${mysql} || die ${inten}

	done

	query="DELETE FROM slave_params WHERE parameter='cert_file'"
	echo ${query} | ${mysql} || die ${inten};


	inten="upgrade certificates table"

	query="ALTER TABLE certificates
			DROP COLUMN pub_key
		,	DROP COLUMN dom_id
		;"
	echo ${query} | ${mysql} || die ${inten};

	suc
}

fix_country_names_500()
{
	query="UPDATE clients SET country='GB' WHERE country='UK'"
	echo $query | ${mysql}

	query="UPDATE Cards SET country='GB' WHERE country='UK'"
	echo $query | ${mysql}

	query="UPDATE misc SET val='GB' WHERE param='admin_country' and val='UK'"
	echo $query | ${mysql}
}

fix_slave_timeout_500()
{
	local slave_request_timeout

	inten="set up default value for slave_request_timeout"

	query="SELECT val FROM misc WHERE param='slave_request_timeout'"
	slave_request_timeout=`echo ${query} | ${mysql}`

	if [ "X${slave_request_timeout}" = "X" ]; then

		query="replace into misc (param,val) values('slave_request_timeout', '20');"
		echo ${query} | ${mysql} || die ${inten};
	fi
}

move_passwords_500()
{
	inten="move passwords to 'accounts' table"
	echo_try ${inten}

	# table mail (passwd may be NULL or empty string)
	query="ALTER TABLE mail ADD COLUMN account_id INT UNSIGNED NOT NULL REFERENCES accounts (id);"
	echo ${query} | ${mysql} || die ${inten} >> "$product_log" 2>&1

	query="UPDATE mail SET account_id=0 WHERE password IS NULL OR password=''"
	echo ${query} | ${mysql} || die ${inten} >> "$product_log" 2>&1

	# process mail users with non-empty password
	query="SELECT id FROM mail WHERE password <> ''";
	for mail_id in `echo ${query} | ${mysql}`; do
		get_free_id 'accounts'
		query_sel="SELECT password FROM mail WHERE id='$mail_id'"
		passwd=`echo ${query_sel} | ${mysql}`
		query_ins="INSERT INTO accounts(id, type, password) VALUES ('$common_var', 'plain', '$passwd')"
		echo ${query_ins} | ${mysql} || die ${inten}
		query_upd="UPDATE mail SET account_id='$common_var' WHERE id='$mail_id'"
		echo ${query_upd} | ${mysql} || die ${inten}
	done >> "$product_log" 2>&1

	query="ALTER TABLE mail DROP COLUMN password;"
	echo ${query} | ${mysql} || die ${inten} >> "$product_log" 2>&1

	# table sys_users (passwd may empty string, not NULL)
	query="ALTER TABLE sys_users ADD COLUMN account_id INT UNSIGNED NOT NULL REFERENCES accounts (id);"
	echo ${query} | ${mysql} || die ${inten} >> "$product_log" 2>&1

	query="UPDATE sys_users SET account_id=0 WHERE passwd=''"
	echo ${query} | ${mysql} || die ${inten} >> "$product_log" 2>&1

	# process system users with non-empty password
	query="SELECT id FROM sys_users WHERE passwd <> ''";
	for user_id in `echo ${query} | ${mysql}`; do
		get_free_id 'accounts'
		query_sel="SELECT passwd FROM sys_users WHERE id='$user_id'"
		passwd=`echo ${query_sel} | ${mysql}`
		query_ins="INSERT INTO accounts(id, type, password) VALUES ('$common_var', 'plain', '$passwd')"
		echo ${query_ins} | ${mysql} || die ${inten}
		query_upd="UPDATE sys_users SET account_id='$common_var' WHERE id='$user_id'"
		echo ${query_upd} | ${mysql} || die ${inten}
	done >> "$product_log" 2>&1

	query="ALTER TABLE sys_users DROP COLUMN passwd;"
	echo ${query} | ${mysql} || die ${inten} >> "$product_log" 2>&1

	suc
}

fill_domain_services_500()
{
	local  dom_list dom_id

	inten="turn off mail service for disabled domains"

	query="SELECT id FROM domains WHERE status != '0'"
	dom_list=`echo ${query} | ${mysql}`

	for dom_id in ${dom_list}; do

		query="UPDATE DomainServices SET status='2' WHERE dom_id='${dom_id}'"
		echo ${query} | ${mysql} || die ${inten}

	done || die ${inten} >> "${product_log}" 2>&1
}

upgrade_client_perm_500()
{
	# PSA 5.0.x				PSA 6.0
	# -----------------------------------------
	# create_domains 	=> 	create_domains
	#						+ manage_phosting
	#						+ change_limits
	#						+ manage_anonftp
	#						+ deploy_webapps
	inten="upgrade client permissions"
	echo_try ${inten}

	query_select_perm="SELECT DISTINCT id FROM Permissions WHERE permission='create_domains' AND value='true'"
	for id in `echo ${query_select_perm} | ${mysql}`; do
		insert="REPLACE INTO Permissions(id,permission,value) VALUES"
		echo "$insert ($id, 'manage_phosting', 'true')" | ${mysql} || die ${inten}
		echo "$insert ($id, 'change_limits',   'true')" | ${mysql} || die ${inten}
		echo "$insert ($id, 'manage_anonftp',  'true')" | ${mysql} || die ${inten}
	done >> "${product_log}" 2>&1 || die ${inten}

	suc
}

upgrade_domain_templates_500()
{
	inten="upgrade domain templates"
	echo_try ${inten}

	query="replace TmplData (tmpl_id, element, value) select id, 'dns_type', 'master' from Templates"
	echo ${query} | ${mysql} || die ${inten};

	suc
}

upgrade_disabled_domains_mysql_users_500()
{
	local inten dom_list dom_id param_id user_save_id db_save_id user_list user user_host db_list db db_host fixed_db_name

	inten="upgrade database users from turned off domains"

	# select all disabled domains
	query="SELECT id FROM domains WHERE status != '0'"
	dom_list=`echo ${query} | ${mysql}`

	if [ "X${dom_list}" = "X" ]; then
		return 0
	fi

	for dom_id in ${dom_list}; do

		query="SELECT params_id FROM domains WHERE id='${dom_id}'"
		param_id=`echo ${query} | ${mysql}`

		if [ "X${param_id}" != "X" ]; then

			query="SELECT value FROM Parameters WHERE parameter='user_save_id' AND id='${param_id}'"
			user_save_id=`echo ${query} | ${mysql}`

			if [ "X${user_save_id}" != "X" ]; then

				if [ 0${user_save_id} -ne 0 ]; then

					# there is specific ip-addresses for domain database users
					query="SELECT parameter FROM Parameters WHERE id='${user_save_id}'"
					user_list=`echo ${query} | ${mysql}`

					if [ "X${user_list}" != "X" ]; then

						for user in ${user_list}; do

							query="SELECT value FROM Parameters WHERE id='${user_save_id}' AND parameter='${user}'"
							user_host=`echo ${query} | ${mysql}`

							query="UPDATE mysql.user SET Host='${user_host}', Password='!!'
									WHERE User='${user}' AND Host='0.0.0.0'"
							echo ${query} | ${mysql} || die ${inten}

							query="DELETE FROM Parameters WHERE id='${user_save_id}' AND parameter='${user}'"
							echo ${query} | ${mysql} || die ${inten}
						done
					fi
				fi

				# walk on other users of domain databases, that are disabled and has 'localhost' Host field value
				query="SELECT db_users.login FROM db_users, data_bases, mysql.user
						WHERE data_bases.dom_id='${dom_id}'
							AND db_users.db_id=data_bases.id
							AND mysql.user.User=db_users.login
							AND mysql.user.Host='0.0.0.0';"

				user_list=`echo ${query} | ${mysql}`

				if [ "X${user_list}" != "X" ]; then

					for user in ${user_list}; do

						query="UPDATE mysql.user SET Host='localhost', Password='!!' WHERE User='${user}' AND Host='0.0.0.0'"
						echo ${query} | ${mysql} || die ${inten}
					done
				fi
			fi

			query="DELETE FROM Parameters WHERE parameter='user_save_id' AND id='${param_id}'"
			echo ${query} | ${mysql} || die ${inten}

			query="SELECT value FROM Parameters WHERE parameter='db_save_id' AND id='${param_id}'"
			db_save_id=`echo ${query} | ${mysql}`

			if [ "X${db_save_id}" != "X" ]; then

				if [ 0${db_save_id} -ne 0 ]; then

					# there is specific ip-addresses for domain databases
					query="SELECT parameter FROM Parameters WHERE id='${db_save_id}'"
					user_list=`echo ${query} | ${mysql}`

					if [ "X${user_list}" != "X" ]; then

						for user in ${user_list}; do

							query="SELECT value FROM Parameters WHERE id='${db_save_id}' AND parameter='${user}'"
							db_host=`echo ${query} | ${mysql}`

							query="UPDATE mysql.db SET Host='${db_host}'
									WHERE User='${user}' AND Host='0.0.0.0'"
							echo ${query} | ${mysql} || die ${inten}

							query="DELETE FROM Parameters WHERE id='${db_save_id}' AND parameter='${user}'"
							echo ${query} | ${mysql} || die ${inten}

						done
					fi
				fi

				# walk on other domain databases, that are disabled and has 'localhost' Host field value
				query="SELECT name FROM data_bases WHERE data_bases.dom_id='${dom_id}'"
				db_list=`echo ${query} | ${mysql}`

				if [ "X${db_list}" != "X" ]; then

					for db in ${db_list}; do

						fixed_db_name=`echo ${db} | awk '{ gsub("[\x5c\x5c]_","_"); gsub("_","\\\\_"); print $0}'`

						query="UPDATE mysql.db SET Host='localhost'
									WHERE Db='${fixed_db_name}' AND Host='0.0.0.0'"
						echo ${query} | ${mysql} || die ${inten}
					done
				fi
			fi

			query="DELETE FROM Parameters WHERE parameter='db_save_id' AND id='${param_id}'"
			echo ${query} | ${mysql} || die ${inten}
		fi
	done
}

upgrade_statistics_data_500()
{
	inten="upgrade statistics data"

	query="INSERT INTO DomainsTraffic (dom_id, date, http_out) SELECT dom_id, date, transfer FROM stat"
	echo ${query} | ${mysql} || die ${inten}

	query="DROP TABLE stat"
	echo ${query} | ${mysql} || die ${inten}
}

set_default_skin_500()
{
	local inten default_skin_id

	inten="set default skin 'Silver Bullet'"

	# select all disabled domains
	query="SELECT id FROM Skins WHERE name = 'Silver Bullet'"
	default_skin_id=`echo ${query} | ${mysql}`

	if [ "X${default_skin_id}" = "X" ]; then
		return 0
	fi

	query="DELETE FROM misc WHERE param='skin_id'"
	echo ${query} | ${mysql} || die ${inten}

	query="replace into misc (param,val) values('def_skin_id', '${default_skin_id}')"
	echo ${query} | ${mysql} || die ${inten}

	query="replace into misc (param,val) values('admin_skin_id', '${default_skin_id}')"
	echo ${query} | ${mysql} || die ${inten}
}

upgrade_bounce_catch_id_500()
{
	local inten query query1 row dom_id dom_params_id ds_params_id

	inten="upgrade bounce and catch IDs in Parameters"

	query="SELECT d.id, d.params_id, ds.parameters_id FROM domains d LEFT JOIN DomainServices ds on (ds.dom_id=d.id AND ds.type='mail'), Parameters p WHERE d.params_id=p.id AND p.parameter='nonexist_mail'"
	for row in `echo ${query} | ${mysql} | awk '{print $1","$2","$3}'`; do

		dom_id=`echo $row | sed -e 's/,/ /g' | awk '{print $1}'`
		dom_params_id=`echo $row | sed -e 's/,/ /g' | awk '{print $2}'`
		ds_params_id=`echo $row | sed -e 's/,/ /g' | awk '{print $3}'`

		if [ "0$ds_params_id" -gt "0" ]; then
			### delete old "catch-all" preferences (for "domains") if new preferences exists (for "DomainServices")
			query1="DELETE FROM Parameters WHERE id='$dom_params_id' AND parameter IN ('nonexist_mail', 'bounce_mess', 'catch_addr')"
			echo ${query1} | ${mysql}
		else
			### copy old "catch-all" preferences (from "domains" to "DomainServices")
			query1="INSERT INTO Parameters(parameter, value) VALUES('fake', 'fake'); select LAST_INSERT_ID();"
			ds_params_id=`echo ${query1} | ${mysql}`
			query1="DELETE FROM Parameters WHERE parameter='fake'"
			echo ${query1} | ${mysql}

			if [ "0$ds_params_id" -gt "0" ]; then
				### set id of parameters for DomainServices
				query1="UPDATE DomainServices set parameters_id=$ds_params_id WHERE type='mail' AND dom_id=$dom_id"
				echo ${query1} | ${mysql} || continue;

				### move old "catch-all" preferences from "domains" to "DomainServices"
				query1="UPDATE Parameters SET id=$ds_params_id WHERE id=$dom_params_id AND parameter IN ('nonexist_mail', 'bounce_mess', 'catch_addr');"
				echo ${query1} | ${mysql}
			else
				continue;
			fi
		fi
	done

}

upgrade_db_500()
{
	p_echo
	p_echo
	p_echo "===> Upgrading MySQL Database from version 5.0 to 6.0"

	upgrade_db_sql="$PRODUCT_ETC_D/db/${PRODNAME}_db_upgrade_500.sql"

	# small fixes, that are not changing database scheme
	fix_database_names_500
	fix_country_names_500
	fix_slave_timeout_500
	insert_localhost_poplock_500

	# primary database upgrade
	add_changes_500

	# 2.8. SSL certificate management

	# prepare directory for certificates
	if [ ! -d "${PRODUCT_ROOT_D}"/var/certificates ]; then

		inten="creating directory for certificates"
		mkdir -p "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}

	fi
	inten="set permissions to directory for certificates"
	chown root:0 "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}
	chmod 500 "${PRODUCT_ROOT_D}"/var/certificates || die ${inten}


	rebuild_certificates_repository_500
	import_default_certificate_500
	rebuild_ip_pool_500
	ssl_cert_management_500

	# 2.1. muiltiple NB IP (must be after certs, but before id's tossing)
	multiple_nb_ip_500

	# 2.11 Client/Domain Expiration
	update_domain_status_500 # must be before 'move_corresp_ids_500'


	fill_domain_services_500 # must come after domain status update
	move_corresp_ids_500

	# Passwords
	move_passwords_500

	# Templates
	upgrade_domain_templates_500

	# Mysql database users
	upgrade_disabled_domains_mysql_users_500

	# new scheme of traffic counting
	upgrade_statistics_data_500

	upgrade_client_perm_500

	# Set default skin "Silver Bullet"
	set_default_skin_500

	# upgrade bounce and catch IDs in Parameters
	upgrade_bounce_catch_id_500
}

db_fix_bf1492_column_types_80()
{
	if db_test "SHOW TABLES" '$1 == "module_bf1942_servers"' \
		&& db_test "DESCRIBE module_bf1942_servers" '$1 == "srv_bandwidth"'
	then
		db_do "ALTER TABLE module_bf1942_servers
				MODIFY srv_bandwidth
					ENUM('0', '8', '16', '32', '64', '128', '256', '512')
					NOT NULL
					DEFAULT '0'"
	fi
}

db_fix_set_dns_recursion()
{

 db_do_if_not \
 "SELECT * FROM misc WHERE param = 'dns_recursion'" 1 \
 "INSERT INTO misc(param, val) VALUES('dns_recursion', 'any')"
}

db_cleanup_zombie_domain_templates_80()
{
	db_select "SELECT tmpl_id FROM clients WHERE tmpl_id IS NOT NULL"

	for tmpl_id in $db_select_output; do
		db_select "SELECT rep.component_id
					FROM Repository rep LEFT JOIN Templates t
									ON t.id = rep.component_id
					WHERE rep.rep_id = $tmpl_id AND t.id IS NULL"
		for component_id in $db_select_output; do
			db_do "DELETE FROM Repository
					WHERE rep_id = $tmpl_id AND component_id = $component_id"
		done
	done
}

db_enable_spamfilter_on_mailnames_80()
{
	local mail_id

	db_select "SELECT m.id FROM mail m, domains d, sa_conf c WHERE m.dom_id = d.id AND CONCAT(m.mail_name, '@', d.name) = c.mailname AND c.flt_enabled IN ('user', 'both')"
	for mail_id in $db_select_output; do
		db_do "UPDATE mail SET spamfilter = 'true' WHERE id = $mail_id"
	done
}

db_drop_obsolete_spamfilter_tables_80()
{
	db_fix_drop_table sa_conf
	db_fix_drop_table sa_list
}

db_set_drweb_management_permissions_80()
{
	local perm_id
	local query

	if ! db_test "SELECT * FROM Permissions WHERE permission='manage_virusfilter'" 1; then
            query="SELECT perm_id FROM mail WHERE perm_id IS NOT NULL"
	    db_select "$query"
    	        for perm_id in $db_select_output; do
    		    db_do_if_not "SELECT * from Permissions WHERE id = $perm_id AND permission = 'manage_drweb'" 1 \
            	            "INSERT Permissions (id, permission, value) VALUES ($perm_id, 'manage_drweb', 'true')"
		done


		for query in \
			"SELECT m.perm_id FROM mail m, dom_level_usrs d, Permissions p WHERE m.dom_id = d.dom_id AND d.perm_id = p.id AND p.permission = 'manage_drweb' AND p.value = 'false'" \
			"SELECT m.perm_id FROM mail m, domains d, clients c, Permissions p WHERE m.dom_id = d.id AND d.cl_id = c.id AND c.perm_id = p.id AND p.permission = 'manage_drweb' AND p.value = 'false'"
		do
			db_select "$query"
			for perm_id in $db_select_output; do
				db_do "UPDATE Permissions SET value = 'false' WHERE permission = 'manage_drweb' AND id = $perm_id"
			done
		done
	fi	
}

db_max_dom_alias_init_80()
{
	
        local limits_id
        local query

        query="SELECT limits_id FROM clients WHERE limits_id IS NOT NULL"
        db_select "$query"
        for limits_id in $db_select_output; do
            db_do_if_not "SELECT * from Limits WHERE id = $limits_id AND limit_name = 'max_doman_alises'" 1 \
                        "INSERT INTO Limits(id, limit_name, value) VALUES ($limits_id, 'max_doman_alises', -1 )"
        done

        query="SELECT limits_id FROM domains WHERE limits_id IS NOT NULL"
        db_select "$query"
        for limits_id in $db_select_output; do
            db_do_if_not "SELECT * from Limits WHERE id = $limits_id AND limit_name = 'max_doman_alises'" 1 \
                        "INSERT INTO Limits(id, limit_name, value) VALUES ($limits_id, 'max_doman_alises', -1 )"
        done
}

db_replace_make_dumps_permission_80()
{
        local perm_id
	local query
	
	query="SELECT id FROM Permissions where permission = 'make_dumps' AND value = 'true'"
	db_select "$query"
	for perm_id in $db_select_output; do
		db_do "REPLACE INTO Permissions(id, permission, value) VALUES ($perm_id, 'allow_local_backups', 'true')"
		db_do "REPLACE INTO Permissions(id, permission, value) VALUES ($perm_id, 'allow_ftp_backups', 'true')"
	done
	
	query="SELECT id FROM Permissions where permission = 'make_dumps' AND value = 'false'"
	db_select "$query"
	for perm_id in $db_select_output; do
		db_do "REPLACE INTO Permissions(id, permission, value) VALUES ($perm_id, 'allow_local_backups', 'false')"
		db_do "REPLACE INTO Permissions(id, permission, value) VALUES ($perm_id, 'allow_ftp_backups', 'false')"
	done	
	
	db_do "DELETE FROM Permissions WHERE permission = 'make_dumps'"
	
}

db_fastcgi_support_80()
{
	db_fix_add_column hosting fastcgi "ENUM('false','true') NOT NULL DEFAULT 'false'" 
	db_fix_add_column subdomains fastcgi "ENUM('false','true') NOT NULL DEFAULT 'false'"
	db_fix_add_column web_users fastcgi "ENUM('false','true') NOT NULL DEFAULT 'false'"
}

db_migrate_spamfilter_configuration_80()
{
	# Migrate sa_conf and sa_list tables 
	if db_test_table sa_conf && db_test_table sa_list; then
		db_do "INSERT INTO spamfilter (username, preferences, reject_spam) VALUES ('*@*', 'true', 'false')"

		db_do "INSERT INTO spamfilter (username, preferences, reject_spam) 
			SELECT CONCAT(m.mail_name, '@', d.name), 'true', IF(c.spam_action = 'delete', 'true', 'false') 
			FROM mail m INNER JOIN domains d ON m.dom_id = d.id 
			LEFT JOIN sa_conf c ON CONCAT(m.mail_name, '@', d.name) = c.mailname"

		db_do "INSERT INTO spamfilter_preferences (spamfilter_id, preference, value) SELECT sf.id, 'required_score', IFNULL(c.hits_required, '7.00') 
			FROM spamfilter sf LEFT JOIN sa_conf c ON sf.username = '*@*' AND c.mailname = '' OR sf.username = c.mailname"
		db_do "INSERT INTO spamfilter_preferences (spamfilter_id, preference, value) SELECT sf.id, 'rewrite_header', CONCAT('subject ', IFNULL(c.rw_subject_tag, '*****SPAM*****')) 
			FROM spamfilter sf LEFT JOIN sa_conf c ON sf.username = '*@*' AND c.mailname = '' OR sf.username = c.mailname"
		db_do "INSERT INTO spamfilter_preferences (spamfilter_id, preference, value) 
			SELECT sf.id, CONCAT('un', sl.color, 'list_from'), ul.pattern FROM spamfilter sf, sa_list ul, sa_list sl 
			WHERE sf.username = ul.mailname AND ul.pattern = sl.pattern AND ul.color IS NULL AND sl.color IN ('black', 'white') AND sl.mailname = ''"

		db_do "INSERT INTO spamfilter_preferences (spamfilter_id, preference, value) 
			SELECT sf.id, CONCAT(l.color, 'list_from'), l.pattern FROM spamfilter sf, sa_list l 
			WHERE l.color IN ('black', 'white') AND (sf.username = '*@*' AND l.mailname = '' OR sf.username = l.mailname)"

		db_do "REPLACE INTO misc (param, val) SELECT 'spamfilter_enabled', 
			IF(flt_enabled IN ('user', 'serv', 'both'), 'true', 'false') FROM sa_conf WHERE mailname = ''"

		db_do "REPLACE INTO misc (param, val) SELECT 'spamfilter_use_mailuser_prefs', 
			IF(flt_enabled IN ('user', 'both'), 'true', 'false') FROM sa_conf WHERE mailname = ''"

		db_do "REPLACE INTO misc (param, val) VALUES ('spamfilter_max_children', 5)"

		db_do "INSERT Permissions (id, permission, value) SELECT perm_id, 'manage_spamfilter', 'true' FROM clients"
		db_do "INSERT Permissions (id, permission, value) SELECT perm_id, 'manage_spamfilter', 'true' FROM dom_level_usrs"
		db_do "INSERT Permissions (id, permission, value) SELECT perm_id, 'manage_spamfilter', 'true' FROM mail"

		db_do "REPLACE Permissions (id, permission, value) SELECT m.perm_id, 'manage_spamfilter', 'false' FROM mail m, domains d, sa_list l 
			WHERE m.dom_id = d.id AND l.mailname = '' AND l.color = 'gray' AND LOWER(CONCAT(m.mail_name, '@', d.name)) LIKE BINARY(LOWER(REPLACE(REPLACE(l.pattern, '*', '%'), '?', '_')))"
	fi		
}

db_migrate_spamfilter_permissions_80()
{
        local perm_id
        local query

	query="SELECT perm_id FROM clients WHERE perm_id IS NOT NULL"
	db_select "$query"
	for perm_id in $db_select_output; do
            db_do_if_not "SELECT * from Permissions WHERE id = $perm_id AND permission = 'manage_spamfilter'" 1 \
			"INSERT Permissions (id, permission, value) VALUES ($perm_id, 'manage_spamfilter', 'true')"
        done

        query="SELECT perm_id FROM dom_level_usrs WHERE perm_id IS NOT NULL"
        db_select "$query"
        for perm_id in $db_select_output; do
            db_do_if_not "SELECT * from Permissions WHERE id = $perm_id AND permission = 'manage_spamfilter'" 1 \
                        "INSERT Permissions (id, permission, value) VALUES ($perm_id, 'manage_spamfilter', 'true')"
        done

        query="SELECT perm_id FROM mail WHERE perm_id IS NOT NULL"
        db_select "$query"
        for perm_id in $db_select_output; do
            db_do_if_not "SELECT * from Permissions WHERE id = $perm_id AND permission = 'manage_spamfilter'" 1 \
                        "INSERT Permissions (id, permission, value) VALUES ($perm_id, 'manage_spamfilter', 'true')"
        done

        if db_test_table sa_list; then
		db_do "REPLACE Permissions (id, permission, value) SELECT m.perm_id, 'manage_spamfilter', 'false' FROM mail m, domains d, sa_list l
			WHERE m.dom_id = d.id AND l.mailname = '' AND l.color = 'gray' 
			AND LOWER(CONCAT(m.mail_name, '@', d.name)) LIKE BINARY(LOWER(REPLACE(REPLACE(l.pattern, '*', '%'), '?', '_')))"
	fi

}

upgrade_db_80()
{
	add_db_changes 800
        db_fastcgi_support_80
	db_fix_add_column domainaliases tomcat "ENUM('false', 'true') NOT NULL DEFAULT 'false'"
        db_fix_add_column mail spamfilter "ENUM('false','true') NOT NULL DEFAULT 'false' AFTER autoresponder"
	
	db_migrate_spamfilter_configuration_80
	db_migrate_spamfilter_permissions_80

	db_max_dom_alias_init_80

	db_cleanup_zombie_domain_templates_80
	db_enable_spamfilter_on_mailnames_80
	db_drop_obsolete_spamfilter_tables_80
	db_set_drweb_management_permissions_80
	db_replace_make_dumps_permission_80
}


db_fix_add_miva_support_81()
{
    db_fix_add_column hosting miva \
                "ENUM('false','true') NOT NULL DEFAULT 'false' AFTER fastcgi"

    db_fix_add_column subdomains miva \
                "ENUM('false','true') NOT NULL DEFAULT 'false'"
}

db_fix_change_antivirus_structure_81()
{
    #Add virusfilter column to mail table
    db_fix_add_column mail virusfilter  \
                "ENUM('none','incoming', 'outgoing', 'any') NOT NULL DEFAULT 'none' AFTER spamfilter"
		
    #rename DrWeb permission		
    db_do "UPDATE Permissions SET permission='manage_virusfilter'
	    WHERE permission='manage_drweb'"
	    
    #Migrate DrWeb direction param to mail.virusfilter
    db_fix_migrate_drweb_direction_81
    
    #set DrWeb as active virusfilter on server
     db_do_if_not \
	 "SELECT * FROM misc WHERE param = 'virusfilter'" 1 \
	 "INSERT INTO misc(param, val) VALUES('virusfilter', 'drweb')"
    	    
}

db_fix_migrate_drweb_direction_81()
{
    
        local mn_id
        local query

    # from -> outgoing
        query="SELECT mn_id FROM mn_param WHERE param='drweb_direction' AND val='from'"
	db_select "$query"
        for mn_id in $db_select_output; do
            db_do "UPDATE mail SET virusfilter = 'outgoing' WHERE id = $mn_id"
        done
    # to -> incoming
        query="SELECT mn_id FROM mn_param WHERE param='drweb_direction' AND val='to'"
	db_select "$query"
        for mn_id in $db_select_output; do
            db_do "UPDATE mail SET virusfilter = 'incoming' WHERE id = $mn_id"
        done
	
    # any -> any
        query="SELECT mn_id FROM mn_param WHERE param='drweb_direction' AND val='any'"
	db_select "$query"
        for mn_id in $db_select_output; do
            db_do "UPDATE mail SET virusfilter = 'any' WHERE id = $mn_id"
        done		
	
	db_do "DELETE FROM mn_param WHERE param='drweb_direction'"

}

db_fix_set_webstat_management_permissions_81()
{
	local perm_id
	local query

	for query in \
		"SELECT c.perm_id FROM clients c LEFT JOIN Permissions p ON c.perm_id = p.id AND p.permission = 'manage_webstat' WHERE p.id IS NULL" \
		"SELECT d.perm_id FROM dom_level_usrs d LEFT JOIN Permissions p ON d.perm_id = p.id AND p.permission = 'manage_webstat' WHERE p.id IS NULL"
	do
		db_select "$query"
		for perm_id in $db_select_output; do
			db_do "REPLACE INTO Permissions (id, permission, value) VALUES ($perm_id, 'manage_webstat', 'true')"
		done
	done
}

db_fix_add_dalias_dns_column_81()
{
    #add 'dns' column and set it to true if does not exists
    if ! db_test_column domainaliases dns; then
	db_fix_add_column domainaliases dns \
            "ENUM('false','true') NOT NULL DEFAULT 'false' AFTER displayName"
	    
	db_do "UPDATE domainaliases SET dns='true'"    
    fi
}

db_fix_remove_make_dumps_permission_81()
{
    db_do "DELETE FROM Permissions WHERE permission = 'make_dumps'"
}

db_fix_update_hosting_services_81()
{
    local column
    for column in \
            fp fp_ssl fp_enable \
            ssi php php_safe_mode \
            cgi perl python fastcgi \
            miva coldfusion \
            asp asp_dot_net \
            ssl at_domains same_ssl
    do
        db_test_column hosting "$column" && \
            db_do "UPDATE hosting SET \`$column\` = 'false' WHERE \`$column\` = ''"
    done
}

db_fix_81()
{
    add_db_changes --fix 810
    db_fix_change_antivirus_structure_81
    db_fix_add_miva_support_81
    db_fix_set_webstat_management_permissions_81
    db_fix_add_dalias_dns_column_81
    db_fix_remove_make_dumps_permission_81
	db_fix_update_hosting_services_81
}

db_fix_remove_unique_index_81()
{
# Bug 113259, unique index on CHARACTER SET utf8 COLLATE utf8_general_ci

    db_do_if "SHOW INDEX FROM clients" "\$2 == \"0\" && \$3 == \"pname\"" "ALTER TABLE clients 
	    DROP INDEX \`pname\`; 
	    ALTER TABLE clients ADD INDEX (\`pname\`)"
	    
    db_do_if "SHOW INDEX FROM domains" "\$2 == \"0\" && \$3 == \"displayName\"" "ALTER TABLE domains 
	    DROP INDEX \`displayName\`; 
	    ALTER TABLE domains ADD INDEX (\`displayName\`)"	    
    
    db_do_if "SHOW INDEX FROM subdomains" "\$2 == \"0\" && \$3 == \"dom_id_2\"" "ALTER TABLE subdomains 
	    DROP INDEX \`dom_id_2\`; 
	    ALTER TABLE subdomains ADD INDEX \`dom_id_displayName\` (\`dom_id\`, \`displayName\`)"
	    
    db_do_if "SHOW INDEX FROM mass_mail" "\$2 == \"0\" && \$3 == \"name\"" "ALTER TABLE mass_mail 
	    DROP INDEX \`name\`; 
	    ALTER TABLE mass_mail ADD INDEX (\`name\`)"	    
	    
    db_do_if "SHOW INDEX FROM mail_resp" "\$2 == \"0\" && \$3 == \"mn_id\"" "ALTER TABLE mail_resp 
	    DROP INDEX \`mn_id\`; 
	    ALTER TABLE mail_resp ADD INDEX \`mn_id_resp_name\` (\`mn_id\`, \`resp_name\`)"	    
	    
    db_do_if "SHOW INDEX FROM badmailfrom" "\$2 == \"0\" && \$3 == \"domain\"" "ALTER TABLE badmailfrom 
	    DROP INDEX \`domain\`; 
	    ALTER TABLE badmailfrom ADD INDEX (\`domain\`)"	    
	    
    db_do_if "SHOW INDEX FROM DatabaseServers" "\$2 == \"0\" && \$3 == \"host\"" "ALTER TABLE DatabaseServers 
	    DROP INDEX \`host\`; 
	    ALTER TABLE DatabaseServers ADD INDEX \`host_port\` (\`host\`, \`port\`)"	    
	    
    db_do_if "SHOW INDEX FROM Skins" "\$2 == \"0\" && \$3 == \"name\"" "ALTER TABLE Skins 
	    DROP INDEX \`name\`; 
	    ALTER TABLE Skins ADD INDEX (\`name\`)"	    
	    
   db_do_if "SHOW INDEX FROM spamfilter_preferences" "\$2 == \"0\" && \$3 == \"spamfilter_id\"" "ALTER TABLE spamfilter_preferences 
	    DROP INDEX \`spamfilter_id\`; 
	    ALTER TABLE spamfilter_preferences ADD INDEX \`spamfilter_id\` (\`spamfilter_id\`, \`preference\`, \`value\`)"
	    
    db_do_if "SHOW INDEX FROM DashboardPreset" "\$2 == \"0\" && \$3 == \"name_type\"" "ALTER TABLE DashboardPreset 
	    DROP INDEX \`name_type\`; 
	    ALTER TABLE DashboardPreset ADD INDEX \`name_type\` (\`name\`, \`type\`)"	    
    
}

db_fix_new_siteapps_format_81()
{
    db_fix_add_column SiteAppPackages package_type "INT UNSIGNED NOT NULL DEFAULT 0"
    db_fix_add_column SiteAppPackages params_id "INT UNSIGNED"
    db_fix_add_key SiteAppPackages params_id
    
    db_fix_add_column SiteAppResources res_param_1 "VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin DEFAULT ''"
    db_fix_add_column DatabaseServers server_version "VARCHAR(255) CHARACTER SET BINARY NOT NULL"
    db_do "REPLACE INTO actions (name, descr, enabled) VALUES('siteapp_upgrade', 'Upgrade site application', 'true')"
}

db_fix_sso_81()
{
    db_fix_add_column clients uid "VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin AFTER sapp_pool_id"
    db_fix_add_column clients ownership "ENUM('true', 'false') NOT NULL DEFAULT 'true' AFTER uid"
    db_fix_add_column dom_level_usrs uid "VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin AFTER perm_id"
    db_fix_add_column dom_level_usrs ownership "ENUM('true', 'false') NOT NULL DEFAULT 'true' AFTER uid"
}

upgrade_db_81()
{
    db_fix_remove_unique_index_81
    db_fix_new_siteapps_format_81
    db_fix_sso_81
	db_do_if_not \
		"SELECT * FROM NewsArticles WHERE class = 'WhatsNew8_2'" 1 \
		"INSERT INTO NewsArticles(class) VALUES ('WhatsNew8_2')"

}

db_add_guid_actions_82()
{
  db_do_if_not \
  "SELECT * FROM actions WHERE name= 'client_guid_update'" 1 \
  "INSERT INTO actions(name, descr, enabled) VALUES('client_guid_update','Change Client GUID','true')"

   db_do_if_not \
   "SELECT * FROM actions WHERE name= 'domain_guid_update'" 1 \
   "INSERT INTO actions(name, descr, enabled) VALUES('domain_guid_update','Change Domain GUID','true')"
}

db_generate_guids_82()
{
  make_guids_script="$PRODUCT_ROOT_D/admin/plib/make_guids.php"
  if [ -f "$make_guids_script" ]; then
    sw_engine_pleskrun "$make_guids_script" >> "$product_log" 2>&1
  fi
}

db_add_guid_columns_82()
{
  db_fix_add_column clients guid \
    "VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'"

  db_fix_add_column domains guid \
    "VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'"
}

db_fix_82()
{
	add_db_changes --fix 820
}

db_add_mod_bw_columns_82()
{
    db_fix_add_column hosting traffic_bandwidth "INT DEFAULT -1"
    db_fix_add_column hosting max_connection "INT DEFAULT -1"
}

db_aps_upgrade_82()
{
    aps_upgrade_script="$PRODUCT_BOOTSTRAPPER_DIR/db/aps-psa830-db-upgrade"
    if [ -f "$aps_upgrade_script" ]; then
	$PRODUCT_ROOT_D/admin/bin/php "$aps_upgrade_script" >> "$product_log" 2>&1
    fi    

}

upgrade_db_82()
{
	#GUIDs
	db_add_guid_actions_82
	db_add_guid_columns_82
#	This cannot work on 9.x. Will be called later
#	db_generate_guids_82
	
	db_add_mod_bw_columns_82
	db_fix_del_column hosting at_domains
	db_fix_change_column dns_recs type type "ENUM('NS','A','CNAME','MX','PTR','TXT', 'SRV', 'master', 'none') NOT NULL DEFAULT 'A'"
	db_fix_change_column dns_recs_t type type "ENUM('NS','A','CNAME','MX','PTR','TXT', 'SRV') NOT NULL DEFAULT 'A'"

	db_aps_upgrade_82
	
	add_db_changes 821
}

db_del_obsoleted_sso_1_0_columns_83()
{
	db_do "DELETE FROM misc WHERE param IN ('admin_sso_uid', 'admin_ownership')"
	db_fix_del_column clients uid
	db_fix_del_column clients ownership
	db_fix_del_column dom_level_usrs uid
	db_fix_del_column dom_level_usrs ownership
}

db_fix_83()
{
	db_del_obsoleted_sso_1_0_columns_83
    add_db_changes 830
}

db_fix_countries_84()
{
	db_do "UPDATE Cards SET country = 'RS' WHERE country='CS'"
	db_do "UPDATE clients SET country = 'RS' WHERE country='CS'"
	db_do "UPDATE misc SET val='RS' WHERE param='admin_country' AND val='CS'"
}


db_fix_soa_serial_84()
{
	db_do_if_not \
		"SELECT * from misc WHERE param = 'soa_serial_format'" 1 \
		"INSERT INTO misc (param, val) VALUES ('soa_serial_format', 'UNIXTIMESTAMP')"

	db_fix_add_column dns_zone serial_format "enum('UNIXTIMESTAMP','YYYYMMDDNN') NOT NULL default 'UNIXTIMESTAMP'"

	db_fix_add_column dns_zone serial "VARCHAR(12) CHARACTER SET ascii COLLATE ascii_bin NOT NULL default '0'"

	# TP 38826 Resurrect serial number by dns_recs.time_stamp
	db_do "UPDATE dns_zone SET serial=UNIX_TIMESTAMP( (SELECT time_stamp FROM dns_recs WHERE dns_zone_id=dns_zone.id LIMIT 1) )"
}

db_fix_84()
{
	db_fix_countries_84
	db_fix_soa_serial_84
	add_db_changes 841
}

upgrade_plesk_in_watchdog_86()
{
	db_do_if "SHOW TABLES LIKE 'module_watchdog_service'" 1 \
		"UPDATE module_watchdog_service
			 SET start_cmd = '$PRODUCT_RC_D/sw-cp-server start'
			 , stop_cmd = '$PRODUCT_RC_D/sw-cp-server stop'
			 WHERE name = 'plesk_apache' "
}

upgrade_plesk_in_apspool_86()
{

	if db_test_column APSApplicationItems shared && ! db_test_column APSClientApplicationItems broadcast; then
		db_select "SELECT id FROM clients WHERE type = 'admin'"
		local adminId="$db_select_output"

		db_fix_add_column APSClientApplicationItems broadcast "ENUM ('false', 'true') NOT NULL DEFAULT 'false'"

# insert app to admin pool
		db_select "SELECT id from APSApplicationItems"
		local id
		for id in $db_select_output; do
			db_do "INSERT INTO APSClientApplicationItems (client_id, app_item_id, instances_limit, broadcast) VALUES ('$adminId', '$id', '-1' ,'true')"
		done

# update broadcast attribute
		db_select "SELECT id FROM APSApplicationItems WHERE shared = 'false'"
		for id in $db_select_output; do
			db_do "UPDATE APSClientApplicationItems SET broadcast = 'false' WHERE app_item_id = '$id' AND client_id = '$adminId'"
		done

# delete shared column
		db_fix_del_column APSApplicationItems shared
	fi
}

upgrade_plesk_in_domains_86()
{
	db_fix_add_column domains overuse "ENUM ('false', 'true') NOT NULL DEFAULT 'false'"
}

upgrade_plesk_in_clients_86()
{
	db_fix_add_column clients overuse "ENUM ('false', 'true') NOT NULL DEFAULT 'false'"
}

clean_dashboard_86()
{
# Clean clients
	db_do "delete from cl_param where param='preset_id'"
# Clean dom level users
	db_do "delete from dom_param where param='preset_id'"
# Clean DashboardPresetConfig, except custom (mysql 4.0 compatible)
#	db_do "delete from DashboardPresetConfig where preset_id in (select id from DashboardPreset where type <> 'custom')"
	db_select "select id from DashboardPreset where type <> 'custom'"
	for preset_id in $db_select_output; do
		db_do "delete from DashboardPresetConfig where preset_id='$preset_id'"
	done
# Cleean DashboardPreset, except custom
	db_do "delete from DashboardPreset where type <> 'custom'"
}

add_vista_skin()
{
	db_do_if_not "select * from Skins where place='vista'" 1 \
		"replace into Skins (name, place) values ('Vista', 'vista')"
	db_select "SELECT id FROM Skins WHERE place='vista'"
	local vistaID="$db_select_output"
	[ -n "$vistaID" ] || die "cannot find vista skin id"

	db_select "SELECT id FROM Skins WHERE place IN ('aqua', 'longhorn.aero', 'longhorn.black', 'plesk8.new', 'winxp.new', 'winxp.olivegreen', 'winxp.silver', 'vista')"
	local good_ids=`echo -n $db_select_output | tr '\n' ' ' | tr ' ' ','`

# clients
	db_do "UPDATE cl_param SET val='$vistaID' WHERE param='skin_id' AND val NOT IN ($good_ids)"
# domain level
	db_do "UPDATE dom_param SET val='$vistaID' WHERE param='skin_id' AND val NOT IN ($good_ids)"
# mailusers
	db_do "UPDATE mn_param SET val='$vistaID' WHERE param='skin_id' AND val NOT IN ($good_ids)"
# Update admin/default skins
# admin
	db_do "UPDATE misc SET val='$vistaID' WHERE param='admin_skin_id' AND val NOT IN ($good_ids)"
# default
	db_do "UPDATE misc SET val='$vistaID' WHERE param='def_skin_id' AND val NOT IN ($good_ids)"

# Clean up old skins
	db_do "DELETE from Skins WHERE id NOT IN ($good_ids)"
}

move_admin_into_clients_86()
{
	echo_try "migrate admin params to clients table"
	local ex="$PRODUCT_BOOTSTRAPPER_DIR/db/move_admin_into_clients_86.php"
	sw-engine $ex 1>>"$product_log" 2>&1
	[ "$?" -eq 0 ] || \
		warn "cannot migrate admin info. Please rerun '$ex' manually"

}

db_create_default_server_backup()
{
# Creation of default server backup task was removed, because simultaneous
# backups overload hardware node
	:
}

db_create_admin_in_clients_86()
{
	if ! db_test_column clients parent_id; then
		db_fix_add_column clients parent_id "INT UNSIGNED DEFAULT NULL"
		db_fix_add_column clients type "ENUM('client', 'reseller', 'admin') NOT NULL DEFAULT 'client'"
		db_do "REPLACE INTO clients (type, login, cr_date) VALUES ('admin', 'admin', now()); SET @id = LAST_INSERT_ID();UPDATE clients SET parent_id = @id WHERE parent_id IS NULL AND type <> 'admin';"
	fi
}

db_structure_upgrade_86()
{
	db_fix_add_column clients parent_id "INT UNSIGNED DEFAULT NULL"
    db_fix_add_column clients type "ENUM('client', 'reseller', 'admin') NOT NULL DEFAULT 'client'"
    db_fix_add_column IP_Addresses ftps "enum('false','true') NOT NULL DEFAULT 'false'"
    db_fix_add_column mass_mail to_resellers "ENUM('false', 'true') NOT NULL DEFAULT 'false'"
    db_fix_add_column mass_mail to_resellers_mode "ENUM('all', 'select', 'except') NOT NULL DEFAULT 'all'"
    db_fix_add_column Notifications send2reseller "VARCHAR(1) CHARACTER SET ascii COLLATE ascii_bin NOT NULL"

    db_fix_add_column hosting php_handler_type "ENUM('cgi', 'fastcgi', 'module') NOT NULL DEFAULT 'module'"
    db_fix_add_column subdomains php_handler_type "ENUM('cgi', 'fastcgi', 'module') NOT NULL DEFAULT 'module';"
}

db_upgrade_ip_pool_86()
{
if db_test_column IP_Addresses type; then
	db_do "DELETE FROM ip_pool"
	db_do "INSERT INTO ip_pool (id, ip_address_id, type) SELECT c.pool_id, ip.id, ip.type FROM clients c INNER JOIN Repository r ON c.pool_id = r.rep_id INNER JOIN IP_Addresses ip ON r.component_id = ip.id WHERE c.type <> 'admin';"
	db_do "INSERT INTO ip_pool (ip_address_id, type) SELECT id, type FROM IP_Addresses LIMIT 1; SET @pool_id = LAST_INSERT_ID();REPLACE INTO ip_pool (id, ip_address_id, type) SELECT @pool_id, id, type FROM IP_Addresses; UPDATE clients SET pool_id = @pool_id WHERE type='admin';"
	db_fix_del_column "IP_Addresses" "type"
fi
}

db_fix_86()
{
	upgrade_plesk_in_watchdog_86
	db_create_admin_in_clients_86
	db_structure_upgrade_86
    add_db_changes 860
	db_upgrade_ip_pool_86
	move_admin_into_clients_86
	upgrade_plesk_in_apspool_86
	upgrade_plesk_in_domains_86
	upgrade_plesk_in_clients_86
	add_vista_skin
	db_create_default_server_backup
}


db_pmm_dashboard_90()
{
	db_do "UPDATE DashboardPresetConfig SET uri='/plesk/server/migration/' WHERE uri='/plesk/server/pmm/'"
}

db_fix_90()
{
	clean_dashboard_86
    add_db_changes 900
	db_add_gl_filter
	db_install_dashboard_presets
	db_add_spf_to_dns_template
}

db_add_gl_filter()
{
	db_fix_add_column domains gl_filter "ENUM('on', 'off') NOT NULL DEFAULT 'on'"
}
db_add_spf_to_dns_template()
{
	db_do_if_not \
		"SELECT id FROM dns_recs_t WHERE val='v=spf1 +a +mx -all'" 1 \
		"REPLACE INTO dns_recs_t(displayHost, host, type, displayVal, val, time_stamp) VALUES('<domain>.', '<domain>.', 'TXT', 'v=spf1 +a +mx -all', 'v=spf1 +a +mx -all', NOW()+8);"
}
db_update_dashboard_951()
{
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/update_dashboard_presets_9_5_1.php 2>>"$product_log"
	[ "$?" -eq 0 ] || \
	    warn "Unable to update home page presets, see log for details. Please rerun $PRODUCT_ROOT_D/admin/plib/scripts/update_dashboard_presets_9_5_1.php manually"
}

db_update_exp_event()
{
	db_test_table "exp_event" || return
    
	local query

	query="DELETE FROM exp_event WHERE NOT (event_type='started' OR event_type='stopped'
		OR event_type='created' OR event_type='updated' OR event_type='deleted'
		OR event_type='status_changed' OR event_type='terminated' OR event_type='flushed'
		OR event_type='installed' OR event_type='uninstalled' OR event_type='siteapp_added'
		OR event_type='siteapp_removed' OR event_type='expired' OR event_type='exceeded'
		OR event_type='guid_changed')"

	db_do "$query"

	query="DELETE FROM exp_event WHERE NOT (obj_class='license' OR obj_class='service' 
		OR obj_class='ip_address' OR obj_class='admin_info' OR obj_class='siteapp'
		OR obj_class='session_preferences' OR obj_class='plesk_component' OR obj_class='client'
		OR obj_class='client_limits' OR obj_class='client_status' OR obj_class='client_prefs'
		OR obj_class='client_perms' OR obj_class='client_ip_pool' OR obj_class='client_limit_traffic'
		OR obj_class='client_limit_size' OR obj_class='domain' OR obj_class='domain_limits'
		OR obj_class='domain_user' OR obj_class='domain_alias' OR obj_class='domain_status'
		OR obj_class='phosting' OR obj_class='fhosting' OR obj_class='domain_limit_traffic'
		OR obj_class='domain_limit_size' OR obj_class='db_server' OR obj_class='subdomain'
		OR obj_class='mailname' OR obj_class='webuser' OR obj_class='maillist' 
		OR obj_class='dns_zone' OR obj_class='mailname_antivirus' OR obj_class='mailname_spamfilter'
		OR obj_class='mailname_mailgroup' OR obj_class='mailname_autoresponder' 
		OR obj_class='mailname_attachment' OR obj_class='remote_dns' OR obj_class='dashboard_preset' 
		OR obj_class='dashboard_preset_type' OR obj_class='dashboard_preset_name'
		OR obj_class='domain_perfomance' OR obj_class='template_domain' OR obj_class='template_client'
		OR obj_class='template_admin' OR obj_class='log_rotation' OR obj_class='server_ip'
		OR obj_class='db' OR obj_class='db_user' OR obj_class='reseller' OR obj_class='reseller_limits'
		OR obj_class='reseller_status' OR obj_class='reseller_prefs' OR obj_class='reseller_perms'
		OR obj_class='reseller_ip_pool' OR obj_class='reseller_limit_traffic'
		OR obj_class='reseller_limit_size')"

	db_do "$query"
}

db_upgrade_parent_domain_id_1012()
{
    db_fix_add_column domains parentDomainId "INT UNSIGNED NOT NULL DEFAULT 0"
}

db_upgrade_subdomains_1012()
{
    sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_subdomains_1011.php && suc || warn "fail\nupgrade subdomains"
}

db_upgrade_service_nodes_1012()
{
    db_fix_add_column IP_Addresses serviceNodeId "INT UNSIGNED NOT NULL DEFAULT 1"
    db_fix_add_column Configurations serviceNodeId "INT UNSIGNED NOT NULL DEFAULT 1"
    db_fix_add_column sys_users serviceNodeId "INT UNSIGNED NOT NULL DEFAULT 0"
    db_do_if "SHOW INDEX FROM sys_users" "\$2 == \"0\" && \$3 == \"login\"" "
        ALTER TABLE sys_users DROP INDEX \`login\`;
        ALTER TABLE sys_users ADD UNIQUE (\`serviceNodeId\`, \`login\`);
        UPDATE \`sys_users\` set \`serviceNodeId\` = 1 WHERE 0 = \`serviceNodeId\`;
    "
}

db_upgrade_dns_schema_1012()
{
    db_fix_add_column dns_zone syncSoa "enum('true','false','skip') NOT NULL default 'skip'"
    db_fix_add_column dns_zone syncRecords "enum('true','false','skip') NOT NULL default 'skip'"
    db_fix_add_column dns_recs_t uid "VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL"
    db_do "update dns_zone set syncSoa='true', syncRecords='true' where id not in (select val from misc where param='default_dns_zone_id')"
}

db_upgrade_dns_data_1012()
{
    sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_dns_1011.php && suc || warn "fail\nupgrade dns"
}
set_drweb_params()
{
	drweb_user="drweb"
	drweb_group="drweb"

	drweb_var_dir="/var/drweb"
	drweb_service="drwebd"
}

#proftpd

set_ftpd_params()
{
	anonftp_user="${product}ftp"
	anonftp_group="${product}ftp"

	PROFTPD_ROOT="$PRODUCT_ROOT_D/ftpd"
	PROFTPD_ETC_D="$PROFTPD_ROOT/etc"
}

set_ftpd_accounts()
{
	p_echo " Checking for the system groups and users necessary for ftp server..."
        group_op "$anonftp_group" "search" false
        user_op "$anonftp_user" "search" "$anonftp_group" "anonftp ${product} user" "$dummy_home" "$dummy_shell" false
}

set_ftpd_perms()
{

	set_ac root 0 555 "$PROFTPD_ROOT/*"
	set_ac root 0 755 "$PROFTPD_ROOT/var"

	set_ac root 0 555 "$PROFTPD_ROOT/bin/*"
	set_ac root 0 444 "$PROFTPD_ROOT/etc/*"
	set_ac root 0 555 "$PROFTPD_ROOT/sbin/*"


	chown -R 0:0 $PROFTPD_ROOT || die "chown -R 0:0 $PROFTPD_ROOT"
	chmod -R 555 $PROFTPD_ROOT/bin || die "chmod -R 555 $PROFTPD_ROOT/bin"
	chmod -R 555 $PROFTPD_ROOT/sbin || die "chmod -R 555 $PROFTPD_ROOT/sbin"
	chmod -R 755 $PROFTPD_ROOT/var || die "chmod -R 555 $PROFTPD_ROOT/var"
	chmod 755 $PROFTPD_ETC_D || die "chmod 755 $PROFTPD_ETC_D"
	chmod 644 $PROFTPD_ETC_D/proftpd.conf || die "chmod 644 $PROFTPD_ETC_D/proftpd.conf"
	echo "" >> $PROFTPD_ETC_D/proftpd.include || die "unable to create $PROFTPD_ETC_D/proftpd.include"
	chmod 644 $PROFTPD_ETC_D/proftpd.include || die "chmod 644 $PROFTPD_ETC_D/proftpd.include"

}

proftpd_super_server_config()
{
	local action="$1"

	case "$superserver" in
	    inetd)
		    ftp_rec="ftp stream tcp nowait root $PROFTPD_ROOT/sbin/proftpd proftpd -c $PROFTPD_ETC_D/proftpd.conf"
		    ;;
	    xinetd)
		    ftp_rec="service ftp
{
	socket_type		= stream
	protocol		= tcp
	wait			= no
	disable			= no
	user			= root
	instances		= UNLIMITED
	server			= $PROFTPD_ROOT/sbin/proftpd
	server_args		= -c $PROFTPD_ETC_D/proftpd.conf
}"
		    ;;
	    *)
		    die "Super server name unknown"
		    ;;
	esac

	super_server_action "$action" ftp "$ftp_rec"
}

setup_ftpd()
{
	add_login_shell "$false_shell"

	label_file_once "@@SYSCONFDIR/xinetd.d/ftp_psa" "${AUTOGENERATED_CONFIGS_UPGRADE}"

	p_echo " Checking for ftp home directory for 'clients' group..."

	if [ -f /etc/ftpchroot ]; then
		egrep "^@${clients_group}" /etc/ftpchroot >> $product_log 2>&1
		res=$?
	fi
	
	case "$res" in
		0)	p_echo " '@${clients_group}' is already in the /etc/ftpchroot"
			;;
		*)	inten="add '@${clients_group}' to /etc/ftpchroot"
			echo_try $inten
			echo "@${clients_group}" >> /etc/ftpchroot && suc || die $inten
			;;
	esac
	p_echo
}

install_ftpd()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		return 0;
	fi

	p_echo
	p_echo
	p_echo "===> Installing ftp server (proftpd)..."
	cd "$PRODUCT_ROOT_D" || die "cd $PRODUCT_ROOT_D"

	set_ftpd_params
	setup_ftpd
	set_ftpd_perms

	case "$machine" in
		linux)
			if [ -d "/etc/pam.d" ]; then
				if [ ! -f "/etc/pam.d/ftp" ]; then
					cp -fp $PRODUCT_ROOT_D/tmp/ftp.pamd /etc/pam.d/ftp
					chown root:0 /etc/pam.d/ftp
					chmod 644 /etc/pam.d/ftp
				fi
			fi
			;;
	    *)
			;;
	esac

	if [ ! -f /etc/ftpusers ]; then
		touch /etc/ftpusers || die "Error creating /etc/ftpusers file"
		IFS_OLD="$IFS"
		IFS=":"
		while { read username nu nu gid nu; }; do
			if [ $gid -le 100 -a "$username" != "ftp" ]; then
				echo $username
			fi
		done < /etc/passwd > /etc/ftpusers
		IFS="$IFS_OLD"
	fi

	rm -f $PRODUCT_ROOT_D/tmp/ftp.pamd
}

upgrade_proftpd_107()
{
	echo_try "upgrade anon_ftp quota to new format"
	local domain;
	for domain in $HTTPD_VHOSTS_D/*; do
		[ -e $domain/anon_ftp/incoming/quotadir ] || continue
		rm -f $domain/anon_ftp/incoming/quotadir/.undeletable \
			$domain/anon_ftp/incoming/quotadir/.quota >> $product_log 2>&1
		rmdir $domain/anon_ftp/incoming/quotadir >> $product_log 2>&1
	done
	sw_engine_pleskrun $PRODUCT_ROOT_D/admin/plib/scripts/upgrade_proftpd_107.php && suc || warn "fail\nupgrade anon_ftp quota to new format"
}
upgrade_proftpd_754()
{
	case "$machine" in
		BSD*)
			inten="reconfigure ftp superserver record"
			echo_try $inten
			set_ftpd_params
			proftpd_super_server_config remove 
			proftpd_super_server_config register 
			suc
			;;
		*)
			;;
	esac
}
upgrade_proftpd_820()
{
	if [ "X$linux_distr" = "Xdebian" -o "X$linux_distr" = "Xubuntu" ]; then
		if [ -f "${FTPD_CONF}" ]; then
			awk '{ if ($1 == "ScoreboardFile") {print "ScoreboardFile /var/run/proftpd_scoreboard"} else {print} }' \
				${FTPD_CONF} > ${FTPD_CONF}.tmp \
				&& mv -f ${FTPD_CONF}.tmp ${FTPD_CONF} \
		        && chmod 644 ${FTPD_CONF}
		fi
	fi
}
#!/bin/bash

set_tomcat_params()
{
	# # set_common_params
	tomcat_distrib="$PRODUCT_ROOT_D/tmp/jakarta-tomcat.tar"
	tomcat_version="7"
	CATALINA_HOME="/usr/share/tomcat"
	tomcat_user="tomcat"
	tomcat_group="tomcat"

	#basename directory. May be different. 
	dist_name="tomcat7"

	tomcat_conf="$CATALINA_HOME/conf/$dist_name.conf"
	### This is for linux - on standard builds we don't have 
	###	tomcat uncompressed in this stage
	[ -f $tomcat_conf ] || tomcat_conf="/etc/sysconfig/j2ee"
}

set_tomcat_perms()
{

	inten="set up Tomcat permissions"
	echo_try $inten

	chown -RL 0:$tomcat_group "$CATALINA_HOME" > /dev/null 2>&1 || chown -R 0:$tomcat_group "$CATALINA_HOME"
	chown -RL $tomcat_user:$tomcat_group "$CATALINA_HOME/logs" > /dev/null 2>&1 || 		chown -R $tomcat_user:$tomcat_group "$CATALINA_HOME/logs"
	chown -RL $tomcat_user:$tomcat_group "$CATALINA_HOME/work" > /dev/null 2>&1 || 		chown -R $tomcat_user:$tomcat_group "$CATALINA_HOME/work"
	chmod 775 "$CATALINA_HOME/logs" || die "chmod $dist_name directory logs"
	chmod 775 "$CATALINA_HOME/work" || die "chmod $dist_name directory work"
	chmod 775 "$CATALINA_HOME/conf" || die "chmod $dist_name directory conf"
	[ -e "$CATALINA_HOME/temp" ] && 		(chmod 777 "$CATALINA_HOME/temp" || die "chmod $dist_name directory temp")
	[ -e "$CATALINA_HOME/conf/jk2.properties" ] && 		(chmod 664 "$CATALINA_HOME/conf/jk2.properties" || die "chmod $dist_name file jk2.properties")
	[ -e "$CATALINA_HOME/conf/tomcat-users.xml" ] && 		(chmod 664 "$CATALINA_HOME/conf/tomcat-users.xml" || die "chmod $dist_name file tomcat-users.xml")

	suc

	return 0
}

set_tomcat_accounts()
{
	# for tomcat
	p_echo " Checking for the system groups and users necessary for Tomcat..."

	group_op "$tomcat_group" "search" false
	user_op "$tomcat_user" "search" "$tomcat_group" "Tomcat" "$CATALINA_HOME" "$bash_shell" false
}

set_java_home()
{
	tomcat_conf="$1"
	force="$2"

	[ -f $tomcat_conf ] || return

	echo_try "find JAVA_HOME variable in the $tomcat_conf"

	tomcat_JAVA_HOME=`sed -n -e "/^JAVA_HOME=\([\"']\)\(.*\)\1$/s//\2/p" $tomcat_conf | sed -n -e '$p'`

	java_home_dirs_list="/usr/java/j2sdk* /usr/java/jdk* ${PRODUCT_ROOT_D}/j2sdk* /usr/lib/j2sdk*                              /usr/lib*/jvm/java /Library/Java/Home /usr/local/diablo-jdk1.5.0 /usr/lib*/jvm/java*sun*"

	if [ -z $tomcat_JAVA_HOME ]; then

		p_echo
		p_echo " JAVA_HOME variable is not in the ${tomcat_conf}"

		echo_try "find Java home directory in ${java_home_dirs_list}"
		for java_home in $java_home_dirs_list; do
			if [ -d $java_home ] && [ -f "${java_home}/bin/java" -a -f "${java_home}/bin/javac" ]; then
				JAVA_HOME=$java_home
				break
			fi
		done
		[ ! -z $JAVA_HOME ] || die

		p_echo
		echo_try "add JAVA_HOME=\"${JAVA_HOME}\" in the ${tomcat_conf}"
		echo >> $tomcat_conf || die
		echo "JAVA_HOME=\"${JAVA_HOME}\"" >> $tomcat_conf && suc || die

	elif [ ! -f "${tomcat_JAVA_HOME}/bin/java" -o ! -f "${tomcat_JAVA_HOME}/bin/javac" -o "X$force" = "Xtrue" ]; then

		p_echo
		p_echo " Incorrect JAVA_HOME variable value (${tomcat_JAVA_HOME}) in the ${tomcat_conf}"

		echo_try "find Java home directory in ${java_home_dirs_list}"
		for java_home in $java_home_dirs_list; do
			if [ -d $java_home ] && [ -f "${java_home}/bin/java" -a -f "${java_home}/bin/javac" ]; then
				JAVA_HOME=$java_home
				break
			fi
		done
		[ ! -z $JAVA_HOME ] || die

		p_echo
		echo_try "add JAVA_HOME=\"${JAVA_HOME}\" in the ${tomcat_conf}"
		esc_JAVA_HOME=`echo "${JAVA_HOME}" | sed -n -e 's/\//\\\\\//gp'`
		tomcat_conf_old="${tomcat_conf}-old"
		cp -f $tomcat_conf $tomcat_conf_old || die
		sed -e "s/^JAVA_HOME=\([\"']\).*\1$/JAVA_HOME=\"${esc_JAVA_HOME}\"/" $tomcat_conf_old > $tomcat_conf && suc 		|| (mv -f $tomcat_conf_old $tomcat_conf && die)
		rm -f $tomcat_conf_old
	else
		p_echo
		p_echo " JAVA_HOME variable is already in the $tomcat_conf and has correct value (${tomcat_JAVA_HOME})"
	fi
}

set_tomcat_user()
{
	[ -f $tomcat_conf ] || return

	echo_try "replace TOMCAT_USER variable in the $tomcat_conf"

	sed -e "s|^TOMCAT_USER=.*|TOMCAT_USER=\"$tomcat_user\"|g" < $tomcat_conf > $tomcat_conf.tmp		&& mv -f $tomcat_conf.tmp $tomcat_conf 	&& chmod 644 $tomcat_conf && suc

}

tomcat_conf_add_value()
{
	#variable	"$1"
	#value		"$2"
	#tomcat_conf	"$3"

	test -f "$3" || return

	if ! egrep -q "^$1=" "$3"; then
		echo >> "$3" || die
		echo "$1=$2" >> "$3" || die
	fi
}

tomcat_create_server_link()
{
	if [ -e /usr/share/$dist_name/server ]; then
		if [ ! -e $CATALINA_HOME/server ]; then
			ln -s /usr/share/$dist_name/server $CATALINA_HOME/server
		fi
	fi
	for i in psa-users psa-wars psa-webapps; do
		[ ! -e $CATALINA_HOME/$i ] && mkdir -p $CATALINA_HOME/$i
		[ -e $CATALINA_HOME/$i ] && chown -R $tomcat_user:$tomcat_group $CATALINA_HOME/$i
		[ ! -e /usr/share/$dist_name/$i ] && ln -sf $CATALINA_HOME/$i  /usr/share/$dist_name/$i
	done
}

tomcat_change_sysconfig()
{
	[ -f "/etc/sysconfig/j2ee" ] && sysconfig_conf="/etc/sysconfig/j2ee" || sysconfig_conf="/etc/sysconfig/$dist_name"
	[ -f $sysconfig_conf ] || return

	echo_try "comment CATALINA_BASE variable in the $sysconfig_conf"

	sed -e "s|^\(CATALINA_BASE=.*\)|#\1|g" < $sysconfig_conf > $sysconfig_conf.tmp		&& mv -f $sysconfig_conf.tmp $sysconfig_conf 	&& chmod 644 $sysconfig_conf && suc

	# needed minimum on suse93x64
	if ! egrep -q "export.*JAVA_HOME" "$sysconfig_conf"; then
		echo >> "$sysconfig_conf" || die
		echo "export JAVA_HOME" >> "$sysconfig_conf" || die
	fi
}

tomcat_create_manager_links()
{
	for i in manager host-manager; do 
		if [ -e "/usr/share/tomcat6-admin/$i" -a -e "$CATALINA_HOME/webapps" -a ! -e "$CATALINA_HOME/webapps/$i" ]; then
			ln -sf /usr/share/tomcat6-admin/$i $CATALINA_HOME/webapps/$i
		fi
	done
}

install_tomcat_linux()
{
	local conf_tmp="/etc/$dist_name/conf/$dist_name.conf"
	if [ -r "$conf_tmp" ]; then
		catalinahome=`egrep "^CATALINA_HOME=" $conf_tmp 2>/dev/null | sed -e "s/CATALINA_HOME=\"\(.*\)\"/\1/"`
		if [ -n $catalinahome ]; then
			CATALINA_HOME=$catalinahome
		fi
	fi

	tomcat_conf_add_value SHUTDOWN_WAIT 30 "$tomcat_conf"

	tomcat_create_server_link

	tomcat_change_sysconfig



}

comment_native_mod_jk_props()
{
	perl -pi -e 's/^\s*JkWorkersFile.*$/#$_/g' /etc/apache2/mods-available/jk.conf
}

install_tomcat()
{
	set_tomcat_params 

	conf_setval "${prod_conf_t}" CATALINA_HOME "${CATALINA_HOME}"
	set_tomcat_accounts

	install_tomcat_linux

	set_java_home $tomcat_conf false
	set_tomcat_user

	p_echo " Making chown and chmod under JDK stuff"
	set_tomcat_perms
}

tomcat_reconfigure_server_safe()
{
	echo_try "reconfigure Tomcat services"
	local ports=

	# needed for proper work tomcatmng
	conf_setval "${prod_conf_t}" CATALINA_HOME "${CATALINA_HOME}"

	for name in warp coyote; do
		db_select "SELECT val FROM misc WHERE val = '${name}_connector_port'" 			|| {
				p_echo "Failed to get Tomcat parameter '${name}_connector_port' from the database"
				return 1
			}
		if [ -n "$db_select_output" ]; then
			ports="--${name}-connector-port $db_select_output"
		fi
	done

	"$UTILS_DIR/tomcatmng" --install-psa --replace-if-exists $ports 		|| {
			p_echo "Failed to configure Tomcat PSA service"
			return 1
		}

	db_select "SELECT d.name
				FROM domains d, DomainServices ds
				WHERE d.id = ds.dom_id
					AND type='tomcat'
					AND ds.status = 0" 		|| {
			p_echo "Failed to get active Tomcat domains"
			return 1
		}
	local domains="`echo $db_select_output | tr ' ' ','`"

	if [ -n "$domains" ]; then
		"$PLESK_LIBEXEC_DIR/tomcat_upgrade_helper" --reconfigure-domains "$domains" 			|| {
				p_echo "Failed to reconfigure Tomcat settings for active domains"
				return 1
			}
	fi

	suc
	return 0
}

tomcat_reconfigure_server()
{
	tomcat_reconfigure_server_safe || warn "Tomcat server reconfiguration"
}
upgrade_cf_83()
{
	db_select "select val from misc where param='cf_instance_path'"
	[ -n "$db_select_output" -a -d "$db_select_output" ] || return 0

	[ ! -f "$HTTPD_INCLUDE_D/jrun.conf" ] || return 0
	$UTILS_DIR/cfmng --write-jrun-conf
	true
}

keyupdate_main_710_std()
{
	autoinstaller_upgrade_710_std

	output=`$PRODUCT_ROOT_D/admin/sbin/keyupdate  --update-main --product-version $product_version`
	status="$?"
	if test "$status" -ne 0; then
		if
			test -n "$PLESK_AUTOINSTALLER"
		then
			p_echo
			p_echo '*****************************************************'
			p_echo
			p_echo " The upgrade of your Plesk server was unable to be completed due to a failure to upgrade your product license."
			p_echo
			p_echo " Failure reason:"
			p_echo " $output"
			p_echo
			p_echo " If you have acquired your new product license already, please attempt the upgrade again. You will given an option to continue without automatic license updating."
			p_echo " If you have not acquired your new product license, you can do so either through our online license updater at https://register.parallels.com/key_upgrade/ or by contacting your account administrator. For customers of Parallels Partners, please contact your provider for assistance with acquiring an upgrade to your license."
			p_echo " For additional assistance contact us at customerservice@parallels.com."
			p_echo
			p_echo '*****************************************************'
			p_echo
			exit 1
		else
			p_echo
			p_echo '*****************************************************'
			p_echo
			p_echo " Plesk is unable to update your product license."
			p_echo
			p_echo " Failure reason:"
			p_echo " $output"
			p_echo
			p_echo " Continuing with the upgrade without having an appropriate product"
			p_echo " license will result in the installation of a default license with"
			p_echo " limited functionality. Administrators are advised to first acquire the"
			p_echo " appropriate license before continuing with the product upgrade."
			p_echo
			p_echo '*****************************************************'
			while true; do
				pnnl_echo "     Do you wish to continue (yes/[no])?"
				read answer
				if [ "$answer" = "yes" ]; then
					touch "$prodkey.new"
					break
				elif [ -z "$answer" -o "$answer" = "no" ]; then
					p_echo
					p_echo " Updgrade canceled."
					p_echo
					exit 0
				fi
			done
		fi
	else
		p_echo " No errors on key upgrade"
		p_echo " $output"
	fi
}

autoinstaller_upgrade_710_std()
{
	autoinstaller_upgrade_710_std_extract

	(
		cd "$PRODUCT_ROOT_D/admin/sbin"
		cp -p -f autoinstaller autoinstaller.orig
		cp -p -f "$PRODUCT_ROOT_D/tmp/psa-pre-$product_version/autoinstaller" autoinstaller.new
		mv -f autoinstaller.new autoinstaller
		cp -R -p -f "$PRODUCT_ROOT_D/tmp/psa-pre-$product_version/php/"*  "$PRODUCT_ROOT_D/admin"
	) >>"$product_log" 2>&1
}

autoinstaller_upgrade_710_std_extract()
{
	(
		uudecode -o /dev/stdout <<'EOF' | tar xpzf - -C "$PRODUCT_ROOT_D"
KEYUPDATE_ARCHIVE_PLACEHOLDER
EOF
	) >>"$product_log" 2>&1

	local SRC_DIR="$PRODUCT_ROOT_D/tmp/psa-pre-$product_version"

	if [ ! -d $SRC_DIR ]; then
		die "psa-pre scripts installing: $SRC_DIR does not exist"
	fi
	chown -Rh 0:0 $SRC_DIR

	for util in keyupdate autoinstaller; do
		cp -f "$SRC_DIR/$util" "$PRODUCT_ROOT_D/admin/sbin/" \
		|| die "installing $util util: an error occured during copying the file"

		if [ ! -L "$PRODUCT_ROOT_D/admin/bin/$util" ]; then
			unlink "$PRODUCT_ROOT_D/admin/bin/$util" > /dev/null 2>&1
			cd "$PRODUCT_ROOT_D/admin/bin" \
			&& ln -s ../sbin/wrapper ./$util \
			|| warn "installing $util util: an error occured during linking to wrapper"
		fi
		chown -h 0:0 \
			"$PRODUCT_ROOT_D/admin/bin/keyupdate" \
			"$PRODUCT_ROOT_D/admin/sbin/keyupdate" \
		&& chmod 755 "$PRODUCT_ROOT_D/admin/sbin/keyupdate" \
		|| warn "permissions setting for $util util"
	done

	chmod -R 755 $SRC_DIR/php/ \
	&& find $SRC_DIR/php/ -type f -exec chmod 644 {} \; \
	|| warn "permissions setting for psa-pre php scripts"

	cp -Rfp $SRC_DIR/php/* "$PRODUCT_ROOT_D/admin/" \
	|| die "installing of psa-pre php scripts"
}
# vim:syntax=sh

set_swkey_params()
{
	SWKEY_REPOSITORY="/etc/sw/keys"
	KEYUPGRADE_PATH="/usr/lib64/plesk-9.0/key-upgrade"
	KEYUPGRADE8_PATH="/usr/lib64/plesk-9.0/key-upgrade8"
}

key_upgrade8_cmd()
{
	# update key from 8.x to 9+
	p_echo "Update license key to OF format"
	nohup /bin/sh -c "$KEYUPGRADE8_PATH 11.0.9" > /dev/null 2>&1 &
}

key_upgrade_cmd()
{
	# set to run key upgrade script
	p_echo "Starting Plesk Key upgrade task"
	nohup /bin/sh -c "$KEYUPGRADE_PATH 11.0.9 2>&1 | logger -p daemon.err -t plesk-key-upgrader" 		>/dev/null 2>&1 &
}


pre_keyupdate()
{
	set_mysql_server_params

	getppid2()
	{
		cat /proc/$1/stat | cut -f 4 -d ' '
	}
	if
		test -f /usr/local/psa/version 		&& grep -q "^7\.1\." /usr/local/psa/version 		&& test ! -e /etc/psa/key.new-11.0.9 		&& test ! -e /etc/psa/key.new
	then
		if ! pleskrc mysql status; then
			mysql_stopped=yes
			pleskrc mysql start
		fi
		output=`/usr/local/psa/admin/sbin/keyupdate --update-main --product-version 11.0.9`
		status="$?"
		test $status -ne 0 && echo "keyupdate fails"
		if test "_$mysql_stopped" = _yes; then
		    pleskrc mysql stop
		fi
		if
			test "$status" -ne 0
		then
			PPID_STORED=$PPID
			GPPID_STORED=$(getppid2 $PPID_STORED)
			if
				test -n "$PLESK_AUTOINSTALLER" 				|| grep -q autoinstaller "/proc/$GPPID_STORED/cmdline"
			then
				echo
				echo '*****************************************************'
				echo
				echo " The upgrade of your Plesk server was unable to be completed due to a failure to upgrade your product license."
				echo
				echo " Failure reason:"
				echo " $output"
				echo
				echo " If you have acquired your new product license already, please attempt the upgrade again. You will given an option to continue without automatic license updating."
				echo " If you have not acquired your new product license, you can do so either through our online license updater at https://register.parallels.com/key_upgrade/ or by contacting your account administrator. For customers of Parallels Partners, please contact your provider for assistance with acquiring an upgrade to your license."
				echo " For additional assistance contact us at customerservice@parallels.com."
				echo
				echo '*****************************************************'
				echo
				kill $PPID
				exit 1
			else
				echo " Error on key upgrade:"
				echo " $output"
			fi
		else
			echo " No errors on key upgrade"
			echo " $output"
		fi
	fi
}

key_upgrade_86_install_additional_key()
{
	key_path="$1"
	echo_try "install key $key_path"

	sw_engine_pleskrun -r \
	 'try { of_install_key(file_get_contents("'"$key_path"'")); }
	  catch (Exception $e) { error_log($e->getMessage()); exit(1); }' >>"$product_log" 2>&1 \
	|| report_problem "install key $key_path" \
	&& suc
}

key_upgrade_86_install_additional_keys()
{
	p_echo "installing additional keys"
	for key in `/bin/ls -rt /etc/psa/key.d`; do
		key_upgrade_86_install_additional_key "/etc/psa/key.d/$key"
	done
}

key_upgrade_86()
{

# FIXME: probably this should be moved to key-upgrade8
	p_echo "preparing to upgrade Plesk keys"
	set_swkey_params

	#install fake main key
	db_select "SELECT plesk_key_id FROM key_history WHERE filename = '/etc/psa/psa.key' ORDER BY id DESC LIMIT 1"
	key_number="$db_select_output"
	db_select "SELECT options FROM key_history WHERE filename = '/etc/psa/psa.key' ORDER BY id DESC LIMIT 1"
	key_cookie="$db_select_output"


	# install stub only if there is nondefault key
	if [ -n "$key_number" ] && [ "$key_number" != "plsk000000000000" ]; then
		cat >"$SWKEY_REPOSITORY/registry.xml" <<EOF
<value><struct>
<member><name>history</name>
<value><array><data>
</data></array></value></member>
<member><name>active</name>
 <value><struct>
 <member><name>$key_number</name>
  <value><struct>
   <member><name>key_product_name</name>
    <value><string>plesk-unix</string></value>
   </member>
   <member><name>key_update_cookie</name>
    <value><string>$key_cookie</string></value>
   </member>
   <member><name>update_time</name>
    <value><string>instant</string></value>
   </member>
  </struct></value>
 </member>
 </struct></value>
</member>
</struct></value>
EOF

	key_upgrade8_cmd
	fi

	key_upgrade_86_install_additional_keys

	p_echo "Plesk Key upgrade is prepared"
}
# 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"

	local scr_path=${SYSTEM_RC_D}/${service}
	if [ -x ${scr_path} ]; then
        service_script=${scr_path}
    fi

	if [ "$action" = "exists" ]; then 
		[ -n "$service_script" ] && return 0 || return 1
	else
		if [ -z "$service_script" ]; then
            warn "Unable to ${inten} - control script is not exist or not executable"
            return 1
        fi
	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 $@ >>$product_log 2>&1
			;;
		stop)
			if pleskrc $service_name status; then
				$action_cmd $action $@
			else
				true
			fi
		    ;;
		restart)
			if pleskrc $service_name status; then 
				$action_cmd "restart" $@
			else 
				$action_cmd "start" $@
			fi
		    ;;
		reload)
		    if pleskrc $service_name status; then
				$action_cmd "reload" $@
			else
				true
			fi
		    ;;
		status)
		    $action_cmd "status"
		    ;;
	    *)
		    $action_cmd $action $@ 
		    ;;
	esac >> $product_log 2>&1

	ret="$?"
	if [ "$action" != "status" ]; then
		[ "$ret" -eq 0 ] && suc || warn $inten
	fi

	return $ret
}

is_function()
{
	local type_output="`type -t \"$1\" 2>/dev/null`"
	case "$type_output" in
		*function)
			return 0
		;;
		*)
			return 1
		;;
	esac
}
form_undotted_version()
{
# Backward compatible with versions < 11.0.0
	echo $1 | awk -F. '{ if ($1 < 11) { print  $1  $2 } else { print $1*100+$2 } }'
}

get_prev_version()
{
	# Debian package system reports previous version as script argument
	if [ "X${prev_version}" = "X" ]; then

		if [ -f "$1/core.version" ]; then
		# Check version from core
			prev_version=`cat $1/core.version | awk '{ print $1 }'`
            prev_build=`cat $1/core.version | awk '{ print $4 }'`
		elif [ -f $1/version ]; then
		# version file must exists in product directory
		    prev_version=`cat $1/version | awk '{ print $1 }'`
		    prev_build=`cat $1/version | awk '{ print $4 }'`
		else
		    p_echo "    Unable to find version file $1. "
		    p_echo "    Please, restore version file or remove old ${PRODUCT_NAME}, if unnecessary."
		    exit 1
		fi

		# check, that it is not empty
		if [ "X${prev_version}" = "X" -o "X${prev_build}" = "X" ]; then
			p_echo "    Unable to determine version or build number of ${PRODUCT_NAME} installed. It is impossible"
			p_echo "    to upgrade ${PRODUCT_NAME} to version $product_version."
			p_echo "    To install new version without data saving remove '$1' directory"
			p_echo "    manually. Please backup all data before removing if it need."
			exit 1
		fi
	fi

	# chat, that it is known version of product
	prev_short_version=`form_undotted_version ${prev_version}`

	for i in ${known_product_versions}; do
	    if [ "X${prev_short_version}" = "X${i}" ]; then
			return 0
	    fi
	done

	# version is unknown for upgrader. let the user to know the propblem
	p_echo "    Unable to upgrade. You have  $prev_version version installed,"
	p_echo "    but upgrader is incompatible with this version."
	p_echo "    To install new ${PRODUCT_NAME} copy, please move '$1'"
	p_echo "    to another place manually."
	exit 1
}

check_product_root()
{
	# check product root
	p_echo
	pnnl_echo "===> Checking for previous installation ... "

	do_upgrade=0

	if [ ! -s "$PRODUCT_ROOT_D/version" ]; then
		p_echo "not found."
	else
		p_echo "found."
		get_prev_version ${PRODUCT_ROOT_D}
		do_upgrade=1
	fi
}

confirm_upgrade()
{
	# Standard packaging does not allow self-upgades
	if [ "X${prev_version}" = "X${product_version}" ]; then
		echo "$prev_build $product_build" | awk '{ exit (($1 >= $2) ? 0 : 1);}' >/dev/null
		if [ 0$? -eq 0 ]; then
		    p_echo "    Unable to upgrade. You already have ${prev_version} version installed"
		    p_echo "    To install new ${PRODUCT_NAME} copy, please move '${PRODUCT_ROOT_D}'"
	    	p_echo "    to another place manually."
		    exit 1
		fi
	fi

	p_echo
	p_echo
	p_echo "    You have version $prev_version installed."
	p_echo
	p_echo "    It is possible to upgrade it to ${PRODUCT_FULL_NAME} ${product_version}."
	p_echo
	p_echo "    In case you haven't made proper backup $PRODUCT_NAME is not"
	p_echo "    responsible for any consequences."
	p_echo
	p_echo "    Plesk is ready for upgrade.  Please note that ${PRODUCT_NAME} utilizes"
	p_echo "    your version file to verify that you are performing a correct software"
	p_echo "    upgrade. If your version file has been changed manually and does not"
	p_echo "    reflect accurate information, then the upgrade may crash causing you"
	p_echo "    to lose your data."
	p_echo
	p_echo " *****************************************************************************"
	p_echo " *                                                                           *"
	p_echo " *        NOTE:   After upgrade you'll have installed default key file for   *"
	p_echo " *                Plesk with limited functionality; you can create only one  *"
	p_echo " *                client and one domain with it. If you have more domains    *"
	p_echo " *                and clients then Control panel will not work and you       *"
	p_echo " *                will need to get a key with additional features from       *"
	p_echo " *                the $PRODUCT_NAME team: ${sales_email}                            *"
	p_echo " *                                                                           *"
	p_echo " *****************************************************************************"
	p_echo

	pnnl_echo "    Do you really want to proceed? [N]"

	if [ "x$PLESK_AUTOINSTALLER" != "x" ]; then
		answer=y;
	else
		read answer
	fi

	case "$answer" in

   		y*|Y*)
			do_upgrade=1
			;;
   		*)
			p_echo
			p_echo "Thank you for choosing our products!"
			p_echo
			exit 0
			;;
	esac
}

check_localtime_file()
{
	[ -f /etc/localtime ] && return 0
	report_problem \
		"There is no /etc/localtime file in system." \
		"Run tzsetup as root to set up your timezone"
	return 1
}

check_tmp_permissions()
{
	local tmp_perm_mask=777
	[ $((0`stat -c %a /tmp` & 0$tmp_perm_mask)) -eq $((0$tmp_perm_mask)) ] && return 0

	if [ -f /tmp/pp-bootstrapper-ez-templates-prep-install.flag ]; then
		chmod 1777 /tmp
		p_echo " /tmp file access permissions were adjusted to 1777."
		p_echo
		return 0
	else
		report_problem \
			"/tmp should have at least $tmp_perm_mask file access permissions." \
			"Run 'chmod 1777 /tmp' as root to set up proper file access permissions."
		return 1
	fi
}


check_mysql_password()
{
	if [ "X${minimal_changes}" = "X1" ]; then
		# try to connect to mysql database with empty password

		echo "" | $mysql_client -u root mysql >> "$product_log" 2>&1
		myOK=$?
		[ $myOK -eq 0 ] || return 0

		echo "mysql database with empty root user password is found."
		echo "For security purposes breaks its installation until a password"
		echo "is assigned to administrator. Please, assign a password to mysql"
		echo "database administrator and try to install again."
		return 1
	fi
	return 0
}

preinstall_checks()
{
	check_localtime_file || exit 1
	check_tmp_permissions || exit 1
}

check_versions_match()
{
	if [ "X${prev_version}" = "X" ]; then
		prev_version=`cat "${PRODUCT_ROOT_D}/version" | awk '{ print $1 }'`
	fi

	# check, that it is not empty
	if [ "X${prev_version}" = "X" ]; then
		p_echo "    Unable to define version of ${PRODUCT_NAME} installed. It is impossible"
		p_echo "    to upgrade ${PRODUCT_NAME} to version $product_version."
		p_echo "    To install new version without data saving remove ${PRODUCT_ROOT_D} directory"
		p_echo "    manually. Please backup all data before removing if it need."
		exit 1
	fi

	file_version=`echo ${prev_version} | awk '{printf "%02s%1s\n",$1,$2}' FS='.'`

	for kv in $known_product_versions error; do
		if test $kv = error; then
			p_echo "    Unable to upgrade $PRODUCT_NAME. You have  $prev_version version"
			p_echo "    installed, but upgrader is incompatible with this version."
			p_echo "    To install new ${PRODUCT_NAME} copy, please move '$PRODUCT_ROOT_D'"
			p_echo "    to another place manually."
			die " check version"
		fi
		if test "$file_version" = "0$kv"; then
			break
		fi
	done

}

check_securelevel()
{
   local inten="$1"
   local secure_level
   local config1="/boot/loader.conf"
   local config2="/etc/rc.conf"

   #check secure level in sysctl

   secure_level=`sysctl kern.securelevel | awk -F ':' '{print $2}'`
   if [ "X$secure_level" != "X -1" ]; then
       p_echo "Your OS is in secure_level $secure_level!" 
       p_echo

      for i in "$config1 $config2"; do
         sed -e 's|\(.*securelevel.*\)|\#\1|g' "$i" "$i.saved";
      done

      p_echo "Secure level was changed from $secure_level to -1. Please reboot your system" 
      p_echo "start installation again"
      die "$inten" 
   fi

  return 0
}

print_congratulations()
{

printf "\a\a\a"
p_echo
p_echo
p_echo
p_echo

local passwd upgrade

if [ "X$admin_passwd" = "Xsetup" ]; then
	passwd="setup"
else
	passwd="<YOUR ADMIN PASSWORD>"
fi

local print_address=`echo $ipaddress| awk '{print $1}'`

if [ "X$do_upgrade" = "X1" -o "X$rpm_upgrade" = "X1" ]; then

	pp_echo
	if [ "X${minor_problem}" != "X1" ]; then
		pp_echo "                             Congratulations!"
	else
		pp_echo
	fi
	pp_echo "        All stages of the upgrade were successful."
	pp_echo "        ${PRODUCT_NAME} is now running on your system."
	pp_echo "        To complete the system configuration process, please proceed to URL:"
	pp_echo "        https://${fullhost}:8443/ or"
	pp_echo "        https://${print_address}:8443/"
	pp_echo "        Use 'admin' and '$passwd' as login name and password."
	pp_echo
	pp_echo "        Further, use the following commands to start and stop the system:"
	pp_echo "        $START_SH start and"
	pp_echo "        $START_SH stop respectively."
	pp_echo

	if [ "X${minor_problem}" = "X1" ]; then
		pp_echo " *****************************************************************************"
		pp_echo " *                                                                           *"
		pp_echo " *   WARNING:    Some problems occured during upgrade. You need to           *"
		pp_echo " *            check log file                                                 *"
		pp_echo " *            ${product_log}       *"
		pp_echo " *            to fix these problems.                                         *"
		pp_echo " *                                                                           *"
		pp_echo " *****************************************************************************"
		pp_echo
	fi

	if test -n "$upgrade_default_key_installed"; then

		pp_echo "*****************************************************************************"
		pp_echo
		pp_echo " WARNING:    Automatic license upgrade was not performed during"
		pp_echo "             the upgrade process. The product is currently running"
		pp_echo "             on the default license with limited functionality"
		pp_echo "             until such time that an appropriate license is installed."
		pp_echo
		pp_echo "*****************************************************************************"

	fi
else

	pp_echo "                             Congratulations!"
	pp_echo "        Plesk has been successfully installed on your server."
	pp_echo "        To complete the system configuration, please proceed to URL:"
	pp_echo "        https://${fullhost}:8443/ or"
	pp_echo "        https://${print_address}:8443/"
	pp_echo "        Use the login name 'admin' and password '$passwd'."
	pp_echo "        Or use the login name 'root' and your superuser password."
	pp_echo
	pp_echo "        Further, use the following commands to start and stop Plesk:"
	pp_echo "        \"$START_SH start\" and"
	pp_echo "        \"$START_SH stop\" respectively."
	pp_echo
	pp_echo "        All Plesk control panel documentation is available at"
	pp_echo "        http://www.parallels.com/en/products/plesk/docs"
	pp_echo
	pp_echo "                    Thank you for choosing our products!"
fi
}

define_action()
{

action="$2"

case "$action" in

	"")
		case "$my_name_1" in

			deinstall.sh)
				exit 1
				;;

			*)
				;;
		esac
		;;

	deinstall)
		prep_deinstall
		unset PLESK_INSTALLER_NOUNDO
		smart_undo_install
		;;

	help|*)
		p_echo "usage: $1 <arg>"
		p_echo "where argument is one from the list:"
		p_echo
		p_echo "	deinstall    -- remove ${product} from you computer"
		p_echo "	help         -- this screen"
		p_echo

		exit 1
		;;

esac

}


# 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="$*"

	if [ "X$trigger_uninstall" != "X1" ]; then
		printf "\a\a"
		report_problem \
			"ERROR while trying to $*" \
			"Check the error reason(see log file: ${product_log}), fix and try again"
	fi

	smart_undo_install

	selinux_close

	exit 1
}

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

# This function needs for some print warning when some services cannot restart
# if called with arg, then we add arg to variable SR_WARNING and print warning
# message for arg, else print warning message for SR_WARNING
service_restart_warning()
{
	if [ "X$1" != "X" ]; then
		if [ "X${SR_WARNING}" = "X" ]; then
			SR_WARNING=$1
		else
			for i in ${SR_WARNING}; do
				if [ "$i" = "$1" ]; then
					break
				fi
			done
			if [ "$1" != "$i" ]; then
				SR_WARNING=$SR_WARNING" "$1
			fi
		fi
		p_echo "WARNING!"
		p_echo "Some problems occured when $1 restart, check it after installation/upgrade complete"
	        p_echo
	 	p_echo "Continue..."
		p_echo
	else
		if [ "X${SR_WARNING}" != "X" ]; then
			p_echo "WARNING!"
		        p_echo "Some problems occured when following services restart:"
			for i in ${SR_WARNING}; do
				p_echo $i
			done
			p_echo "Don't forget to check it after installation/upgrade complete"
        		p_echo
	       	        p_echo "More information can be found in log file: ${product_log}"
			p_echo
		fi
	fi
}

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 "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()
{
	p_echo
	if [ $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 "Problem: $@"

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

	problems_occured=1
}

comm_err()
{
  p_echo "       Unfortunately, this situation has not yet been"
  p_echo "       resolved."
  p_echo "       Please, visit $support_contact for assistance."
  p_echo
  p_echo "Exiting..."
  p_echo

  smart_undo_install
  exit 1
}

gid_err()
{
  gid="$1"

  p_echo
  p_echo "ERROR: It seems there is a group with GID=$gid"
  p_echo "       in this system, but $PRODUCT_NAME needs the same GID"
  p_echo "       for its operation."

  send_error_report "Error: group with GID=$gid already exists."
  comm_err
}

group_err()
{
  group="$1"
  gid="$2"

  p_echo
  p_echo "ERROR: It seems that there is group $group"
  p_echo "       in your system. $PRODUCT_NAME uses the same group"
  p_echo "       name but with another group ID ($gid)."

  send_error_report "Error: group $group exists, but it doesn't have GID=$gid."
  comm_err
}

uid_err()
{
  uid="$1"

  p_echo
  p_echo "ERROR: It seems there is a user with UID=$uid"
  p_echo "       in this system, but $PRODUCT_NAME needs the same UID"
  p_echo "       for its operation."

  send_error_report "Error: user with UID=$uid already exists."
  comm_err
}

logname_err()
{
  user="$1"
  uid="$2"

  p_echo
  p_echo "ERROR: It seems that there is a $user in your system"
  p_echo "       with a UID other than that used by $PRODUCT_NAME ($uid)"
  p_echo "       or the $user is in the primary group, but this"
  p_echo "       group is not the one that $PRODUCT_NAME uses."

  send_error_report "Error: user $user exists, but it doesn't have UID=$uid or it belongs to wrong primary group."
  comm_err
}

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

suc()
{
	p_echo "done"
}

send_error_report()
{
	{
		echo $@
		echo ""
		if [ -n "$error_report_context" ]; then
			echo "Context: $error_report_context"
			echo ""
		fi
		test -t 0 || cat -
	} | $PRODUCT_ROOT_D/admin/bin/send-error-report "install" >/dev/null 2>&1
}

set_error_report_context()
{
	error_report_context="$@"
}
extract_report()
{
	case "$1" in
		0) p_echo " Extraction successfully completed"
			p_echo
			;;
		*)

p_echo
p_echo "ERROR: something wrong with distribution archive file"
p_echo "Exiting..."
p_echo

			smart_undo_install
			exit 1
			;;
	esac
}

extract_mess()
{
p_echo
p_echo
p_echo "	So, it's time to unpack distribution files "
p_echo "	All files will be extracted into $PRODUCT_ROOT_D directory"
p_echo "	This operation takes some time,"
p_echo "	please, wait..."
p_echo

}

cleanup_old_files()
{
	local files
	local empty_dirs

	files="admin/plib/class.dlClient.php3 \
		   admin/lib/python/test_*.py \
		   admin/lib/python/tests.py \
		bin/skin_manage.sh"

	for f in $files; do
		rm -f "$PRODUCT_ROOT_D/$f"
	done

	cleanup_mailman_libs
}

product_extract()
{
	extract_mess
	if [ ! -d $PRODUCT_ROOT_D ]; then
	    mkdir -p $PRODUCT_ROOT_D;
	fi

	cd "/usr/local"

	p_echo "===> Checking integrity of package..."

	if [ -x /usr/bin/sum ] ; then

    	sum=`tail +${installer_length} "$my_name" | /usr/bin/sum`

		sum1=`echo ${sum} | awk '{ print $1}'`
		sum2=`echo ${sum} | awk '{ print $2}'`

    	if [ 0$sum1 -ne 0${package_sum1} -o 0$sum2 -ne 0${package_sum2} ]; then
			p_echo "	Package file appears to be corrupted.  Please download"
			p_echo "	original file from download page."
			p_echo "	Do not attempt to install this archive file."
			p_echo
			exit 1
    	fi
	else
    	p_echo "Can't find /usr/bin/sum to do checksum.  Continuing anyway."
	fi

	p_echo

	p_echo "===> Extracting distribution into $PRODUCT_ROOT_D directory..."

	exclude_files_list="/tmp/${PRODNAME}_${product_version}_upgrade_exclude_list"

	if [ "X$do_upgrade" != "X1" ]; then
		pnnl_echo >"$exclude_files_list"
	else
		cat > ${exclude_files_list} << EOF
./home/vhosts/default/htdocs/black_line.gif
./home/vhosts/default/htdocs/index.html
./home/vhosts/default/htdocs/logo.gif
./home/vhosts/default/httpsdocs/black_line.gif
./home/vhosts/default/httpsdocs/index.html
./home/vhosts/default/httpsdocs/logo.gif
./home/vhosts/.skel/error_docs/bad_request.html
./home/vhosts/.skel/error_docs/unauthorized.html
./home/vhosts/.skel/error_docs/forbidden.html
./home/vhosts/.skel/error_docs/internal_server_error.html
./home/vhosts/.skel/error_docs/not_found.html
./home/vhosts/.skel/httpdocs/index.html
./home/vhosts/.skel/httpsdocs/index.html
EOF
	fi

	if $tar xf /dev/null --no-overwrite-dir 2>/dev/null ; then
			tail "+$installer_length" "$my_name" \
			| $tar xpzf - --same-owner --exclude-from \
				"$exclude_files_list" >> "$product_log" 2>&1
	else
			tail "+$installer_length" "$my_name" \
			| $tar xpzf - --same-owner --overwrite-dir \
				--exclude-from "$exclude_files_list" \
			>> "$product_log" 2>&1
	fi
	extract_report "$?"

	rm -f "$exclude_files_list"
}

update_history()
{
	inten="insert upgrade info into history table"

	get_product_versions

	query="SELECT * FROM upgrade_history 
		WHERE version_info='${product_prev_version}' OR db_version='${product_prev_version}'
		LIMIT 1"
	if ! db_test "$query" '1'; then
		query="INSERT INTO upgrade_history (upgrade_date, version_info, 
		db_version) VALUES (now()-1,
			'${product_this_version}', '${product_prev_version}')"
		db_do --inten "$inten" "$query"
	fi

	query="INSERT INTO upgrade_history (upgrade_date, version_info, db_version) 
		VALUES (now(), '${product_this_version}', 
		'${product_this_version}${product_this_version_tag:+ (${product_this_version_tag})}')"
	db_do --inten "$inten" "$query"
}

get_ip_address_list()
{
	local ipaddress=''

	if test -x /sbin/ip ; then
		ipaddress=`/sbin/ip addr | grep -v 'inet6' | grep -v '127\.[0-9]*\.[0-9]*\.[0-9]*' | sed -n -e 's/^ *inet \([0-9\.]*\).*$/\1/ p'`
	else
		ipaddress=`$ifconfig |grep "$inet_str" | grep -v "inet6" | sed -e "s/$inet_str.\([0-9.]*\).*/\1/g"|awk '{print $1}' - | grep -v '^127\.[0-9]*\.[0-9]*\.[0-9]*$'`
	fi
	
	echo -n $ipaddress
}

get_domain()
{
	host="`${get_hostname}`"
	local try_dot=`echo "$host" | sed -e 's/^[^.]*\..*$/\./'`

	case "$try_dot" in
			.)	domain="`echo "$host" | sed -e 's/^[^.]*\.//'`"
				host="`echo $host | sed -e 's/\..*//'`"
				;;
			*)	domain="`$get_domainname`"
				;;
	 esac
	 domain=`echo "$domain" | sed 's/\.$//'`

	 if [ "X$host" = "X" -o "X${domain}" = "X" -o "$domain" = "(none)" ]; then
		p_echo "Warning!"
		p_echo "Unable to determine the host or domain name of your computer."
		p_echo "Setting it to localhost.localdomain"
		host="localhost"
		domain="localdomain"
	 fi

 	 fullhost="${host}.${domain}"
	 return 0;
}

get_config_parameters()
{
 admin_email=

#list of addresses
 local ipaddress_list="`get_ip_address_list`"

 get_domain

 if [ "X$PLESK_DISABLE_HOSTNAME_CHECKING" = "X" -a "X$PLESK_VZ" != "X1" ]; then
 	check_hostname "$fullhost" || die "check the hostname" 
 else
    ipaddress="`echo "$ipaddress_list" | head -1`"
 fi

 start_after_install=1;

 p_echo
}

# vim:syntax=sh

mk_backup()
{
	target="$1"
	dup="$2"
	opts="$3"

	if [ -L "$target" ]; then
		rm "$target"
	elif [ -$opts "$target" ]; then
		if [ ! -$opts "$target.$product_suffo" ]; then
			case "$dup" in
				mv)
					mv -f $target $target.$product_suffo || die "mv -f $target $target.$product_suff"
					;;
				cp)
					cp -fp $target $target.$product_suffo || die "cp -fp $target $target.$product_suff"
					;;
				*)
					p_echo " mk_backup: wrong option -- must be 'cp' or 'mv'"
					die "mk_backup"
					;;
			esac
		else
			case "$dup" in
				mv)
					mv -f $target $target.$product_suff || die "mv -f $target $target.$product_suff"
					;;
				cp)
					cp -fp $target $target.$product_suff || die "cp -fp $target $target.$product_suff"
					;;
				*)
					p_echo " mk_backup: wrong option -- must be 'cp' or 'mv'"
					die "mk_backup"
					;;
			esac
		fi
	else
		case "$opts" in
			f|d)
				;;
			*)
				p_echo " mk_backup: wrong option -- must be 'f' or 'd'"
				die "mk_backup"
				;;
		esac
	fi
}

vz_tune()
{
	#run this only inside vz environment
	if [ -z "$PLESK_VZ" -o "0$PLESK_VZ" -eq "0" ]; then 
		return
	fi
}

# accumulates chown and chmod
set_ac()
{
	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"
}

mkdir_ex()
{
	local owner group mode dir
	owner="$1"
	group="$2"
	mode="$3"
	dir="$4"

	if ! test -d "$dir"; then
		mkdir "$dir" || die "create directory $dir"
	fi
	set_ac "$owner" "$group" "$mode" "$dir"
}

set_ac_r()
{
	u_owner="$1"
	g_owner="$2"
	perms="$3"
	node="$4"

	chown -R $u_owner:$g_owner $node || die "chown $u_owner:$g_owner $node"
	chmod -R $perms $node || die "chmod $perms $node"
}

#get_ls (brief|full) directory
#eliminating error in command 'ls *' on empty dir
get_ls()
{
	opt="$1"
	ls_dir="$2"

	case "$opt" in
		brief)
			for base_name in `ls -A $ls_dir`; do
			    echo "$base_name"
			done
		;;
		full)
			for base_name in `ls -A $ls_dir`; do
			    echo "$ls_dir/$base_name"
			done
		;;
		*)
			p_echo "get_ls: wrong parameter"
			die "get_ls $opt $ls_dir"
		;;
	esac
}

empty_dir()
{
	check_dir="$1"

	files_num=`ls -al "$check_dir" | wc -l`
	if [ "$files_num" -gt 3 ]; then
	    return 1
	else
	    return 0
	fi
}

prep_deinstall()
{
	users_created=`cat $PRODUCT_ROOT_D/admin/conf/${product}.users`
	groups_created=`cat $PRODUCT_ROOT_D/admin/conf/${product}.groups`
}

save_users_groups()
{
	for i in $users_created; do
		echo $i >> "$PRODUCT_ROOT_D/admin/conf/${product}.users"
	done

	for i in $groups_created; do
		echo $i >> "$PRODUCT_ROOT_D/admin/conf/${product}.groups"
	done
}

start_product_now()
{
	define_start_script
	p_echo
	if [ "X$start_after_install" = "X1" ]; then
		inten="start ${PRODUCT_NAME}"
		echo_try $inten
		p_echo
		$START_SH stop
# On suse 12 systemd will refuse to stop services, which are already stopped
# (from it's point of view). So we stop all services right now before
# start. stopall command doesn't prcessed by systemd
		$START_SH stopall
		$START_SH start
	fi
}

start_product_now_final()
{
	unset PLESK_KEYUPDATE_DISABLED
	start_product_now
}

stop_product_now()
{
	define_start_script
	p_echo
	inten="stop $PRODUCT_NAME server"
	echo_try $inten
	p_echo
	$START_SH stop
}

add_manpath()
{
	local manpath manpath_config
	manpath="$1"

	if [ "X$manpath" = "X" ]; then
		warn "add_manpath: supply manpath parameter"
		return 1
	fi


	case "$machine" in

		BSD*)
			manpath_config="/etc/manpath.config"

			if [ ! -f "$manpath_config" ]; then
				touch "$manpath_config"
			fi

			grep_res=`egrep "$manpath" "$manpath_config"`

			if [ "X$grep_res" != "X" ]; then
					return
			fi

			echo "OPTIONAL_MANPATH	$manpath" >> "$manpath_config"
			;;

		*)
			;;
	esac

	return 0
}

find_file()
{
	local paths="$*"

	for file in $paths; do
		[ -f "$file" ] && echo $file && return 0
	done

	return 1
}

set_default_locale()
{
	p_echo 'Setting the default locale'
	default_locale_file="$PRODUCT_ROOT_D/admin/htdocs/locales/default"
	if [ -f $default_locale_file ]; then
		test -r "$default_locale_file" || die "set up default locale: cannot read '$default_locale_file'"
		default_locale="`cat $default_locale_file | sed 's/^\([^:]*\):.*/\1/'`"
		default_locale_name="`cat $default_locale_file | sed 's/^[^:]*:\([^:]*\):.*/\1/'`"
		default_locale_country="`cat $default_locale_file | sed 's/^[^:]*:[^:]*:[^:]*:\([^:]*\);.*/\1/'`"
	else
		default_locale="en-US"
		default_locale_name="ENGLISH"
		default_locale_country="UNITED STATES"
	fi
	p_echo "The default locale is set to $default_locale ($default_locale_name, $default_locale_country)"
}

set_services_info()
{
	if [ "1" = "${PLESK_VZ}" ]; then
		p_echo 'Setting the services information on VZ mode.'
		cp -f ${PRODUCT_ETC_D}/service/vzmode/*.xml ${PRODUCT_ETC_D}/service
	fi
}

vz_disable_updater()
{
	if [ "X${PLESK_VZ}" = "X1" ]; then
	#disable updater for Virtuozzo, see bug 45766
	`echo 'REPLACE misc SET param="disable_updater", val="true"' | $mysql` || die "Cannot deactivate Updater."
	fi
}

detect_vz()         
{                   
    local vzcheck_file
        
    PLESK_VZ=0
    vzcheck_file="/proc/self/status"
                    
    if [ ! -f ${vzcheck_file} ]; then
        return 1; 
    fi              
                    
    grep -q -E '^envID\:[[:space:]]*([[:digit:]]+)$' < ${vzcheck_file} >/dev/null 2>&1
                    
    if [ $? -eq 0 ]; then
        PLESK_VZ=1  
        return 0;
    fi      
    return 1;
}       

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
}

add_string()
{
	local pattern string config
	pattern="$1"
	string="$2"
	config="$3"

	if ! grep -q "^$pattern\$" "$config"; then
		echo "$string" >>"$config"
	fi
}

sh_get_args()
{
	echo 'while true; do case "$1" in '"$1"'*) break;; esac; shift; done'
}

get_phpini_var()
{
	[ -z "$1" ] && return
	cat $php_ini | perl -n -e 'next if(/^;/);  print $5 if(/^(\s*)'$1'(\s*)=(\s*)("*)(.*?)("|\s|;)/);'
}

set_phpini_var()
{
	local variable=$1
	local value=$2

	if [ -z "$variable" ]; then
		warn "set_phpini_var() error: variable name is empty."
		return
	fi

	last_entry_line=`grep -n "^[^a-zA-Z]*$variable" $php_ini | tail -n 1 | awk -F ':' '{print $1}'`;
	if [ -z "$last_entry_line" -o 0$last_entry_line -eq 0 ]; then
		echo "$1 = \"$2\"" >> $php_ini
		result=$?
	else
		tmp_file=`mktemp /tmp/php-iniXXXXXX`
		$cp_preserve $php_ini $tmp_file
		cat $php_ini | awk -v variable="$variable" -v value="$value" '
		{
			line+=1;
			if ($0 ~ /^[ \t]*'$variable'[ \t]*=/) {
				printf("%s = %s\n",variable,value);
				done=1;
			} else {
				print $0;
			}
			if (!done && (line>'$last_entry_line')) {
				printf("%s = %s\n",variable,value);
				done=1;
			}
		}' > $tmp_file && mv -f $tmp_file $php_ini >> $product_log 2>&1
		result=$?
	fi

	if [ 0$result -eq 0 ]; then
		echo "$variable=\"$value\" has been added to $php_ini" >> $product_log 2>&1
	else
		warn "set_phpini_var() error: can't add $variable=\"$value\" to $php_ini";
	fi
}

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

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

get_random_number()
{
	perl -e '
	 my $res = int(rand($ARGV[0]));
	 if (exists $ARGV[1]) {
	  $res = $res + $ARGV[1];
	 }
	 print $res;
	' "$@"
}

get_random_string()
{
	local str_length="$1"
	local str_symbols="$2"
	if [ -x "$PRODUCT_ROOT_D/admin/sbin/random_str" -a -z "$str_symbols" ]; then
		"$PRODUCT_ROOT_D/admin/sbin/random_str" "$str_length"
	else
		# random_str utility may be unavailable in pre phase
		if [ -z "$str_length" ]; then
			str_length="14"
		fi
		if [ -z "$str_symbols" ]; then
			str_symbols="A-Za-z0-9_"
		fi

		< /dev/urandom tr -dc "$str_symbols" 2>/dev/null | head -c "$str_length" 2>/dev/null
	fi
}

fix_etc_hosts()
{
	if ! grep -q -E '^127\..*[[:space:]]localhost([[:space:]]|$)' /etc/hosts; then
		awk '
			BEGIN{ set = 0; }
			/^127\.0\.0\.1[[:space:]]/{ print $0, " localhost"; set = 1; next; }
			{ print }
			END{ if (set == 0) { print "127.0.0.1 localhost"; } }
		' /etc/hosts >/etc/hosts.tmp 		&& mv /etc/hosts.tmp /etc/hosts 		|| report_problem "insert localhost entry in /etc/hosts"
	fi
}

sequence()
{
	if type seq >/dev/null 2>&1; then
		seq $*
	elif type jot >/dev/null 2>&1; then
		jot $*
	else
		die "Unable to find seq or jot command"
	fi
}

realpath()
{
	perl -e 'use Cwd abs_path; print abs_path("'$1'"), "\n";' 
}

get_ini_conf_var()
{
	local conf="$1"
	local section="$2"
	local param="$3"

	[ -n "$conf" -a -n "$param" ] || die "get_ini_conf_var(): required parameters missing"

	local section_empty=0
	[ -n "$section" ] || section_empty=1

	perl -n -e 'BEGIN { $insect='$section_empty' }
				next if (/^\s*;/);
				$insect=0 if (/^\s*\[.*\]/);
				$insect=1 if (/^\s*\['$section'\]/);
				$val = $2, $val =~ s/\s+$//, print $val . "\n" 
					if ($insect && /^\s*('$param')\s*=\s*([^;\n]*)(;.*)?$/);' $conf | head -n 1
}

set_ini_conf_var()
{
	local conf="$1"
	local section="$2"
	local param="$3"
	local value="$4"

	[ -n "$conf" -a -n "$param" ] || die "set_ini_conf_var(): required parameters missing"

	local section_empty=0
	[ -n "$section" ] || section_empty=1

	perl -n -e 'BEGIN { $insect='$section_empty' }
				if (not /^\s*;/) {
					$insect=0 if (/^\s*\[.*\]/);
					$insect=1 if (/^\s*\['$section'\]/);
					if ($insect && /^(\s*('$param')\s*=\s*)([^;\n]*)((;.*)?)$/) {
						$tail = $4; chomp($tail); $tail = "    " . $tail if ($tail);
						print $1 . "'$value'" . $tail . "\n";
						next;
					}
				}
				print $_;' $conf > $conf.tmp && 	cat $conf.tmp > $conf && rm -f $conf.tmp
}

sw_engine_pleskrun()
{
	if [ -x $PRODUCT_ROOT_D/bin/sw-engine-pleskrun ]; then
		$PRODUCT_ROOT_D/bin/sw-engine-pleskrun "$@"
	elif [ -x "/usr/bin/sw-engine" ]; then
		local args
		if [ -e "$PRODUCT_ROOT_D/admin/conf/php.ini" ]; then
			args="-c $PRODUCT_ROOT_D/admin/conf/php.ini"
		else
			args="-d psasem.semfile=\"$PRODUCT_ROOT_D/var/psasem.sem\""
		fi
		/usr/bin/sw-engine $args "$@"
	else
		echo "No Plesk PHP interpreter found"
		return 1
	fi
}

install_default_license_key()
{
	pnnl_echo "install default license key ..."

# key from 8.x?
	if 	db_test_table "key_history" && 		db_test "SELECT COUNT(*) FROM key_history WHERE filename = '/etc/psa/psa.key' LIMIT 1" '$1!="0"'; then
			p_echo "not needed, license from 8.x found"
			return;
	fi

# check OF-key
	if sw_engine_pleskrun -r 'exit(of_get_key_by_product("plesk-unix") === false ? 1 :0);'; then
			p_echo "not needed, license from 9.x found"
			return
	fi

	local dest_dir="/etc/sw/keys/keys"
	local key=plesk-default-key.xml

    [ ! -s "$dest_dir/$key" ] || return

    cp -f "${PRODUCT_ROOT_D}/tmp/$key" "$dest_dir/"
    chown root:swkey-data "$dest_dir/$key"
    chmod 0660 "$dest_dir/$key"
    suc
}
label_file_once()
{
	local _fname _mess _messLines _fileHead _tmpFile

	test $# -eq 2 || die 'label_file_once() not enough arguments'
	
	_fname="${1}"
	_mess="${2}"

	inten="add header to file ${_fname}"
	echo_try $inten

	test -f "${_fname}" || die "file ${_fname} does not exist"
    _messLines=`printf "${_mess}" | wc -l | awk '{print $NF}'`

	_tmpFile=`basename "${_fname}"`
	_tmpFile=`mktemp "/tmp/${_tmpFile}.XXXXXX"` || die "can not create temporary file"
	head -n ${_messLines} "${_fname}" > "${_tmpFile}"

	printf "${_mess}" | diff -q - "${_tmpFile}" 1>/dev/null
	if [ $? -eq 0 ]; then
		p_echo "file ${_fname} already contains required header"
		rm -f "${_tmpFile}"
		return
	fi
	rm -f "${_tmpFile}"

	# preserve permissions, not optimal, need to rework
	cp -p "${_fname}" "${_fname}.tmp"

	printf "${_mess}" | cat - "${_fname}" > "${_fname}.tmp"
	cp -f "${_fname}.tmp" "${_fname}"
	rm -f "${_fname}.tmp"
	p_echo "completed successfully"
}
get_ip_address_250()
{
	local dom_id query ip_address
	dom_id=$1
	
	query="select r.val from domains d, dns_recs r where d.id='$dom_id' and d.id=r.dom_id and r.type='A' and r.host=CONCAT(d.name, '.')"
	ip_address=`echo $query | $mysql`
	echo $ip_address
}

get_ip_address()
{
	local dom_id query ip_address
	dom_id=$1
	
	query="select h.ip_address from domains d, hosting h where d.id='$dom_id' and d.id=h.dom_id"
	ip_address=`echo $query | $mysql`
	echo $ip_address
}

get_param()
{
	local par_name query par_value
	par_name=$1
	
	query="select val from misc where param='$par_name'"
	par_value=`echo $query | $mysql`
	echo $param_value
}

get_dom_param()
{
	local par_name dom_id query par_value
	par_name=$1
	dom_id=$2
	
	query="select val from dom_param where dom_id='$dom_id' and param='$par_name'"
	par_value=`echo $query | $mysql`
	echo $param_value
}

get_dom_email_250()
{
	local dom_id query dom_email
	dom_id=$1

	query="select c.email from domains d, clients c where d.cl_id=c.id and d.id='$dom_id'"
	dom_email=`echo $query | $mysql`
	
	if [ "X$dom_email" = "X" ]; then
		dom_email=`get_param "admin_email"`
	fi
}

get_dom_ns_250()
{
	local dom_id query dom_ns
	dom_id=$1
	
	query="select r.val from domains d, dns_recs r \
		where d.dns_zone='true' and r.dom_id=d.id and d.id='$dom_id' and r.type='NS' \
		and (r.host=CONCAT(d.name, '.') or r.host='@') order by r.time_stamp"
	dom_ns=`echo $query | $mysql`

	if [ "X$dom_ns" = "X" ]; then
		query="select name from domains where id='$dom_id'"
		dom_ns="`echo $query | $mysql`."
	fi
}

get_dom_ns_reverse_250()
{
	local dom_ns

	dom_ns=`get_param "FullHostName"`

	if [ "X$dom_ns" = "X" ]; then
		dom_ns="localhost."
	fi
}


chk_mn()
{
	mail_name="$1"
	re_m="^[a-zA-Z0-9-]+((\.|_)[A-Za-z0-9-]+)*$"
	echo "$mail_name" | egrep $re_m >> $product_log 2>&1
	common_var=$?
}

chk_dom()
{
	dom_name="$1"
	re_d="^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*)+$"
	echo "$dom_name" | egrep $re_d >> $product_log 2>&1
	common_var=$?
}

chk_email()
{
	email="$1"
	re_m="[a-zA-Z0-9-]+((\.|_)[A-Za-z0-9-]+)*"
	re_d="[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*)+"
	re_e="^${re_m}\@${re_d}$";
	echo "$email" | egrep $re_e >> $product_log 2>&1
	common_var=$?
}

chk_ip()
{
	ip="$1"
	re="^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$"
	echo "$ip" | egrep "$re" >> $product_log 2>&1
	common_var=$?
}
set_super_server_params()
{
    case "${machine}_${linux_distr}" in
	linux_*)
	    superserver_mode=native
		superserver=xinetd
	    set_xinetd_params $superserver_mode
	;;
	BSD*)
	    superserver_mode=native
		superserver=inetd
	    set_inetd_params $superserver_mode
	;;
	*)
	    die "Unable to detect super server type"
	;;
    esac

    super_server_action configure
}



set_inetd_params()
{	
    superserver_conf="/etc/inetd.conf"

    if [ "$superserver_mode" = compat ]; then
	if [ -x "$PRODUCT_RC_D/xinetd" ]; then 
	    superserver_service="xinetd"
		superserver_binary="/usr/sbin/xinetd"
	elif [ -x "$PRODUCT_RC_D/inetd" ]; then 
	    superserver_service="inetd"
		superserver_binary="/usr/sbin/inetutils-inetd"
	elif [ -x "$PRODUCT_RC_D/openbsd-inetd" ]; then
	    superserver_service="openbsd-inetd"
		superserver_binary="/usr/sbin/inetd"
	else
	    die "Unable to find script for superserver"
	fi
    else
	superserver_service="inetd"
    fi

    superserver_dir="/etc"
}

set_xinetd_params()
{
    superserver_conf="/etc/xinetd.conf"
    superserver_service="xinetd"
    superserver_dir="/etc/xinetd.d"
}

superserver_reconfig()
{
    pleskrc superserver reload
}

configure_xinetd_compat()
{
	local inten="configure xinetd compatibility mode with $superserver"
	if [ "$linux_distr" = "debian" -o "$linux_distr" = "ubuntu" ]; then
		[ "$superserver_service" = "xinetd" ] || return 1
		[ -f "/etc/default/xinetd" ] || return 1
		grep -q 'XINETD_OPTS=.*-inetd_compat' /etc/default/xinetd && return 1
		echo_try $inten

		if ! grep -q '^\s*XINETD_OPTS' /etc/default/xinetd; then
			echo 'XINETD_OPTS="-inetd_compat"' >>/etc/default/xinetd
			suc
			return 0
		fi

		eval `grep '^\s*XINETD_OPTS' /etc/default/xinetd`
		XINETD_OPTS="$XINETD_OPTS -inetd_compat"
		local tmp_file=`mktemp /tmp/xinetdXXXXXX`
		sed -e "s/XINETD_OPTS.*/XINETD_OPTS=\"$XINETD_OPTS\"/g" /etc/default/xinetd > $tmp_file && mv -f $tmp_file /etc/default/xinetd
		suc
		return 0
	fi
	return 1
}


super_server_action()
{
    local in out
    local action="$1"
    local service="$2"
    local template="$3"

    inten="$action $service service record for $superserver_service daemon"

    case "$action" in
	remove) ;;
	register)
		[ -z "$template" ] && die "Template for super server $action was not defined"
		;;
	comment|disable)
		;; 
	configure)
		case "$superserver_mode" in
		    native)
			register_service $superserver_service defaults defaults
			;;
		    compat)
			configure_xinetd_compat && pleskrc superserver restart
			;;
		    *)
			die "Mode for $superserver_service was not defined"
			;;
		esac

		return 0
		;;
	*)
		die "Some arguments was not defined or defined incorrect for action with super server"
		;;
    esac 

    case "$superserver" in
	inetd)
		super_server_modify_inetd "$service" "$action" "$template"
		;;
	xinetd)
		super_server_modify_xinetd "$service" "$action" "$template"
		;;
	*)
		die "Unable to define super server type"
		;;	
    esac

    if [ $? -ne 0 ]; then
	die $inten 
    fi
}

super_server_modify_inetd()
{
	local service="$1"
	local action="$2"
	local template="$3"

	case "$action" in
		comment|disable)
			grep -q "^$service[[:space:]]" $superserver_conf || return 0
			sed -e "s|^$service|#$service|g" < "$superserver_conf" > "$superserver_conf.tmp" 			&& mv -f "$superserver_conf.tmp" "$superserver_conf" 			|| return 1
			;;
		remove)
			if [ -x /usr/sbin/update-inetd ]; then
				/usr/sbin/update-inetd --enable "$service"
				/usr/sbin/update-inetd --remove "$service"
			else
				grep -q "^$service[[:space:]]" $superserver_conf || return 0
				sed -e "s|^$service[[:space:]].*||g" < "$superserver_conf" > "$superserver_conf.tmp" 			    	&& mv -f "$superserver_conf.tmp" "$superserver_conf" 			    	|| return 1
			fi
			;;
		register)
			if [ -x /usr/sbin/update-inetd ]; then
				/usr/sbin/update-inetd --enable "$service"
				/usr/sbin/update-inetd --remove "$service"
				/usr/sbin/update-inetd --add "$template"
			else
				egrep -q "$template" $superserver_conf
				if [ "$?" -ne "0" ]; then 
					super_server_modify_inetd comment $service && 					echo "$template" >> $superserver_conf || return 1
				fi
			fi
			;;
	esac

	return 0
}

super_server_modify_xinetd()
{
	local file
	local service="$1"
	local action="$2"
	local template="$3"

	for file in $superserver_dir/*; do
		grep -q "$service" $file 1>>$product_log 2>&1 || continue

		case "$action" in
		    remove)
			    awk "/^[[:space:]]*(#|[[:space:]])*service[[:space:]]+$service($|[[:space:]]+)/,/.*}.*/ 				{next;} {print}
			    " <$file >$file.tmp 			    && mv -f $file.tmp $file || return 1
			    ;;
		    comment)
			    awk "/^[[:space:]]*service[[:space:]]+$service($|[[:space:]]+)/,/.*}.*/ 			       { print \"#\"\$0; next; }
			       {print}
			    " < $file > $file.tmp 			    && mv -f $file.tmp $file || return 1
			    ;;
		esac
	done

	case "$action" in
	    register)
		    echo "$template" > "$superserver_dir/${service}_psa" || return 1
		    label_file_once "$superserver_dir/${service}_psa" "${AUTOGENERATED_CONFIGS_UPGRADE}"
		    ;;
	    disable)
			[ -f "$superserver_dir/${service}_psa" ] && mv -f "$superserver_dir/${service}_psa" "$superserver_dir/${service}.psa"
		    ;;
	esac

	return 0
}


superserver_status_linux_debian()
{
    get_pid "/usr/sbin/xinetd" false
    local pid=$common_var
    if test "$pid" -ne 1; then
# running
        return 0
    fi
    return 1
}
lockfile()
{
	local tempfile="$1.$$"
	local lockfile="$1.lock"

	echo $$ > $tempfile 2>/dev/null || {
		p_echo "Unable to create lock file in `dirname $tempfile`"
		return 1
	}

	ln $tempfile $lockfile >/dev/null 2>&1 && {
		rm -f $tempfile
		return 0
	}

	kill -0 `cat $lockfile` >/dev/null 2>&1 && {
		rm -f $tempfile
		return 1
	}

	p_echo "Removing stale lock file $lockfile"
	rm -f $lockfile
	ln $tempfile $lockfile >/dev/null 2>&1 && {
		rm -f $tempfile
		return 0
	}

	rm -f $tempfile
	return 1
}

unlockfile()
{
	rm -f "$1.lock"
}
#-*- 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.0.9${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
}

set_log_name()
{
	CUSTOM_LOG_NAME="$1"
}

set_log_action_name()
{
	CUSTOM_LOG_ACTION_NAME="$1"
}

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

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
}

# here goes functions

package_script_begin_rpm()
{
	package_script_begin
}

package_script_end_rpm()
{
	package_script_end
}

package_script_begin_deb()
{
	package_script_begin
	echo "dpkg action: $PLESK_PACKAGE_DEB_ACTION" >>"$product_log"
}

package_script_end_deb()
{
	package_script_end
}

package_script_begin_pkg()
{
	package_script_begin
}

package_script_end_pkg()
{
	package_script_end
}

package_script_begin_std()
{
	package_script_begin
	local installer_flag=/tmp/psa-installer.run
	if ! touch "$installer_flag"  >>"$product_log" 2>&1; then
		package_script_begin_die "Cannot create $installer_flag"
	fi
}

package_script_begin_die()
{
	PACKAGE_SCRIPT_FAILED="$1"
	package_script_end
	exit 1
}

package_script_end_std()
{
	package_script_end
	rm -rf /tmp/psa-installer.run
}

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

# <fun> <package_function_name> <bootstrapper_function_name> NAME VERSION RELEASE [DEB_ACTION]
package_script_safe_run()
{
	PACKAGE_NAME="$3"
	PACKAGE_VERSION="$4"
	PACKAGE_RELEASE="$5"
	PACKAGE_DEB_ACTION="$6"
	# Run functions in subshell because package scriptlet must exit with status code indicating success.
	# Postpone package problem report till post-install package scriptlet (package_script_safe_run_with_report)
	package_script_begin
	(
		transaction_begin
		transaction_add_rollback_action "package_script_end"
		transaction_add_rollback_action "set_upgrade_failure_flag"

		# run package specific script before bootstrapper
		call_optional_function "$1"

		# perform bootstrapper prep-install actions if required
		if is_function "$2"; then
			# NOTE: flag indicates that prep-install not performed yet
			if [ -f /tmp/pp-bootstrapper-ez-templates-prep-install.flag ]; then
				# FIXME: temporary w/a for EZ templates
				# Some  components (at least, sitebuilder) don't use bootstrapper 
				# but require prep-install performed before package installation.
				# Run bootstrapper prep-install actions once during package installation.
				if [ -f $PRODUCT_BOOTSTRAPPER_DIR/bootstrapper.sh ]; then
					env MAINTAINER_SCRIPT_CONTEXT=1 $PRODUCT_BOOTSTRAPPER_DIR/bootstrapper.sh prep-install
					# Save bootstrapper command to perform after package installation
					echo "$PRODUCT_BOOTSTRAPPER_DIR/bootstrapper.sh post-install" >/tmp/pp-bootstrapper-ez-templates-post-install.sh
					rm -f /tmp/pp-bootstrapper-ez-templates-prep-install.flag
				fi
			fi
			# run bootstrapper script only if bootstrapper mode is disabled (no AI, no EZ)
			if [ ! -f /tmp/pp-bootstrapper-mode.flag ]; then
				"$2"
			fi
		fi

		transaction_add_commit_action "package_script_end"
		transaction_commit
	)
}

# <fun> <package_function_name> <bootstrapper_function_name> NAME VERSION RELEASE [DEB_ACTION]
package_script_safe_run_with_report()
{
	package_script_safe_run "$@"
	local ret=$?
	# package problem report was shown if necessary in log_stop()
	if [ $ret -ne 0 ]; then
		# fatal error
		# show re-start recommendation only if bootstrapper mode is disabled (no AI, no EZ)
		if [ ! -f /tmp/pp-bootstrapper-mode.flag ]; then
			p_echo "To complete product installation one should run bootstrapper script:"
			p_echo "      $PRODUCT_BOOTSTRAPPER_DIR/bootstrapper.sh post-install"
			p_echo
		fi
	fi
}

# <fun> <function name(s)> NAME VERSION RELEASE [DEB_ACTION]
package_script_call_main_function()
{
	package_script_call_main_function_begin "$@"

	for package_func in $1; do
		if ! call_optional_function "$package_func"; then
			break
		fi
	done

	package_script_end_handler ok
}

package_script_call_main_function_begin()
{
	PACKAGE_NAME="$2"
	PACKAGE_VERSION="$3"
	PACKAGE_RELEASE="$4"
	PACKAGE_DEB_ACTION="$5"
	package_script_begin_this_system

	trap "package_script_end_handler error" HUP PIPE INT QUIT TERM EXIT
}

package_script_end_handler()
{
	case "$1" in
	error)
		if [ -z "$PACKAGE_SCRIPT_FAILED" ]; then
			PACKAGE_SCRIPT_FAILED="Package script failed"
		fi
		report_problem "$PACKAGE_SCRIPT_FAILED"
		;;
	ok) PACKAGE_SCRIPT_FAILED=
		;;
	esac

	trap - EXIT

	package_script_end_this_system
}

set_maintenance_mode_flag()
{
	touch /var/lock/parallels-panel-maintenance-mode.flag
}

set_upgrade_failure_flag()
{
	touch /var/lock/parallels-panel-upgrade-failure.flag
}

reset_upgrade_failure_flag()
{
	rm -f /var/lock/parallels-panel-maintenance-mode.flag
	rm -f /var/lock/parallels-panel-upgrade-failure.flag
}

reset_maintenance_mode_flag()
{
	rm -f /var/lock/parallels-panel-maintenance-mode.flag
}

package_script_begin_this_system()
{
    package_script_begin_rpm
}

package_script_end_this_system()
{
    package_script_end_rpm
}

package_script_call_main_function_begin_std()
{
    package_script_call_main_function_begin psa 11.0.9 110130220.09
}


generate_password_file()
{
	local passwd_file="$1"
	local title="$2"
	local user="$3"
	local group="$4"
	local mode="$5"

	if [ "$#" -ne 5 ]; then 
		die "Some arguments was not defined for this function"
	fi

	local passwd
	local inten="generate random password for $title"

	echo_try $inten

	if [ ! -s "$passwd_file" ]; then 
		passwd=`get_random_string` || die $inten
		echo "$passwd" > "$passwd_file" || die $inten
		set_ac $user $group $mode $passwd_file || die $inten
	else
		set_ac $user $group $mode $passwd_file || die $inten
	fi
}

get_pid()
{
	local i

	local ex_f="$1"
	local opt="$2"
	local owner="$3"

	local min_num="1"

#	Use pidof by default, bug 121868, except for FreeBSD - 140182
	if type pidof >/dev/null 2>&1 && [ "$os" != "BSD" ]; then
		for pid in `pidof -o $$ -o $PPID -o %PPID -x $ex_f`; do
#	Check for owner
			[ "$opt" = "true" -a "$owner" != "`ps -p $pid -o ruser=`" ] && continue
			min_num=$pid
			break
		done
		common_var=$min_num
		return $min_num
	fi

	case "$opt" in
		false)
			for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | awk '{print $2}' -`; do
				min_num=$i
				break
			done
			;;
		true)
			for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | grep "$owner" | awk '{print $2}' -`; do
				min_num=$i
				break
			done
			;;
		*)
			p_echo "get_pid: wrong parameter"
			die "get_pid $ex_f $opt $owner"
			;;
	esac

	common_var=$min_num
	return $min_num
}

kill_pids()
{
	ex_f="$1"
	owner="$2"

	for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | grep $owner | awk '{print $2}' -`; do
		if [ $i -gt 1 ]; then
			$K_TERM $i >> $product_log 2>&1
		fi
	done
}

getppid()
{
	ps -o ppid= -p "$1"
}

get_pids_byname()
{
	proc_name="$1"
	PIDS=`ps axww | awk '$5 ~ "'$proc_name'$" {print $1}'`
	echo $PIDS
}

wait_after_stop()
{
        PIDS=`echo "$1" | tr ' ' ,`
        count=${2:-50}

	echo_try "Terminate processes $PIDS" >> $product_log

	while [ 0$count -gt 0 ]; do
		if [ "X$machine" = "XDarwin" ]; then 
	           col_procs="`ps -p $PIDS 2>/dev/null|wc -l| xargs echo`"
                   [ 0$col_procs -lt 2 ] && break
		else
                   ps -p $PIDS > /dev/null 2>&1 || break
		fi

		count=`expr $count - 1`
        	[ 0$count -eq 0 ] && kill -9 $1 > /dev/null 2>&1

                sleep 1
	done

	suc
        return 0
}
add_service2etc_services()
{
	### this function adds service description into /etc/services

	service=$1
	port=$2
	protocol=$3 ### can be empty

	if [ -z "$service" ]; then
		warn "add_service_network_service() error: service does not specified."
		return
	fi

	echo $port | grep '^[0-9][0-9]*$' >/dev/null
	if [ 0$? -ne 0 ]; then
		warn "add_service_network_service() error: '$service' service port number '$port' is invalid."
		return
	fi

	if [ ! -z "$protocol" ]; then
		if [ "$protocol" != "tcp" -a  "$protocol" != "udp" ]; then
			warn "add_service_network_service() error: '$service' service protocol name '$protocol' is invalid."
			return
		fi
		protocol_expr="$protocol"
	else
		protocol_expr='..*'
	fi

	grep -q -E "^[[:space:]]*${service}[[:space:]]*${port}/${protocol_expr}(([[:space:]]*"'$'")|([[:space:]]*#.*"'$'"))" $services
	if [ $? -ne 0 ]; then
		awk '{if ($1 != "'$service'" && $2 ~ "^'$port'/'$protocol_expr'([^0-9]|$)") {print "#"$0"\n'$service'\t"$2} else {print $0}}' \
		<$services >"$services.tmp" \
		&& mv -f "$services.tmp" $services >> $product_log 2>&1
	fi
}


#lib_test

test_for_root()
{
	my_id="`id`"
	case "$my_id" in
		uid=0\(root\)*)
			;;
		*)	echo "$0: This script must be run as root"
			echo "Log in as root then run this script again."
			echo
			exit 1
			;;
	esac
}

check_hostname()
{
    local hostname="$1"

    ipaddress="`perl -e '
       use strict;
       use Socket;
       use Errno;

       my $host = shift || "localhost";
       my $port = 715;

       my $proto = getprotobyname("tcp") || die "Protocol\: $! \n";
       my $addr = inet_aton($host) || die "\tUnable to resolve host name.\n\tPlease specify the host name in the /etc/hosts file\n\tor specify DNS configuration in the /etc/resolv.conf file on your system. \n";

       socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "Socket\: $! \n";

       my $sin = sockaddr_in($port, $addr);

       if (!bind(SOCK, $sin) && $! != Errno::EADDRINUSE) {
          die "Can not bind a socket to address $host:$port - $!\nPlease, check your network configuration\n";
       }

       printf inet_ntoa($addr);
       close(SOCK);
       ' $hostname `"

       if [ "X$ipaddress" = "X" ]; then
           return 1
       else
           return 0
       fi
}
get_userID()
{
# try to get UID
	common_var=`id -u "$1" 2>/dev/null` 

# if id returns 0 the all is ok
	if [ "$?" -eq "0" -a ! -z "$common_var" ]; then
		return 1;
	fi

	return 0;
}

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
	if [ ! -z "$common_var" ]; then
		return 1;
	fi

	return 0;
}

delete_user()
{
	local rm_user

	rm_user="$1"

	# if it is mailman user, remove its crontab from system
	if [ "X${rm_user}" = "X${mailman_user}" ]; then

		inten="remove crontab of ${rm_user}"
		echo "y" | $crontab -u "${mailman_user}" -r >> $product_log 2>&1 || die "$inten"

	fi

	inten="remove user $rm_user"
	echo_try "$inten"

	userdel  $rm_user>> $product_log 2>&1 && suc || die "$inten"
}

delete_group()
{
	local rm_group

	rm_group="$1"

	inten="remove group $rm_group"
	echo_try "$inten"

	mk_backup "/etc/group" cp f
	if [ -f "/etc/group" ]; then
		sed -e "/$rm_group/d" < /etc/group > /etc/group.tmp || die $inten
		mv -f /etc/group.tmp /etc/group  >> $product_log 2>&1
		if [ "$?" -ne 0 ]; then
			rsr_backup "/etc/group" cp f
			die $inten
		fi
	fi
	suc
}

ch_user_home()
{
	local user new_home

	user="$1"
	new_home="$2"

	inten="change home directory for user $user"
	echo_try "$inten"

	usermod -d "$new_home" "$user" 2>>"$product_log" && suc || die "$inten"
}

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 "$group" = "`id -gn "$user"`" \
		|| 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"
}

group_mod()
{
	local group group_new grp_res

	group="$1"
	group_new="$2"
	what_done=0

	# check exists source 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 source group '$group'"
			err
	fi

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

	case "$grp_res" in
		0)
			p_echo " Group '$group_new' already exists"
			p_echo " It is necessary to delete target group '$group_new'"
			err
			;;
		*)
			pnnl_echo " Trying to move group '$group' to '$group_new' ... "
			groupmod -n "$group_new" "$group" >> $product_log 2>&1 && suc ||
			die $inten
			what_done=1
			;;
		esac

	p_echo
	common_var=$what_done
	return $what_done
}

group_op()
{
	group="$1"
    gid="$2"
	id_force="$3"
	what_done=0
	local inten

    if [ "X$gid" = "Xsearch" ]; then
        gid=`get_user_group_id "$group" "gid" 30 400` 
    fi

	inten="add group '$group'"

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

	case "$id_force" in
		true)
			case "$grp_res" in
				0)
				    case "$machine" in
				    *)
					etc_grp_res=`egrep "^$group:" /etc/group`
					case "$etc_grp_res" in
					*:*:*:*)
						chk_res=`echo "$etc_grp_res" | grep ":$gid:"`
						case "$chk_res" in
							*:*:*:*)
								p_echo " Group '$group' already exists"
								;;
							*) group_err "$group" "$gid"
								;;
						esac
						;;
					*)
						p_echo " Group '$group' already exists"
						;;
					esac
					;;

				    esac
				    ;;
				*)
					gid_res=`egrep "^[^:]*:[*x]*:$gid:" /etc/group | head -1`
					case "$gid_res" in
						*:*:*:*)
							gid_err "$gid"
							;;
						*)
							echo_try "$inten"
							groupadd -g "$gid" "$group" >> $product_log 2>&1 && suc ||
							die $inten
							what_done=1
							;;
					esac
					;;
			esac
			;;
		false)
			case "$grp_res" in
				0)
					p_echo " Group '$group' already exists"
					;;
				*)
					echo_try "$inten"
					groupadd "$group" >> $product_log 2>&1 && suc ||
					die $inten
					what_done=1
					;;
			esac
			;;
		*)
			p_echo "group_op: wrong last parameter -- must be 'true' or 'false'"
			p_echo
			p_echo "Exiting..."
			p_echo
			smart_undo_install
			exit 1
			;;
	esac

	p_echo
	common_var=$what_done
	if [ "X$what_done" = "X1" ]; then
		groups_created="$groups_created $group";
	fi
	return $what_done
}

user_op()
{
	user="$1"
	uid="$2"
	group="$3"
	u_desc="$4"
	u_home="$5"
	u_shell="$6"
	id_force="$7"
	gid_force="$8"
	what_done=0

    if [ "X$uid" = "Xsearch" ]; then
        uid=`get_user_group_id "$user" "uid" 30 400` 
    fi

	p_echo " Checking for the user '$user'..."
	id_res=`id "$user" 1>/dev/null 2>&1 ; echo $?`

	case "$id_force" in
		true)
			case "$id_res" in
				0)
					chk_res=`id "$user" 2>&1 | egrep '(^uid=.*gid=.*)|(^id.*user)'`
					if [ "X${gid_force}" = "Xfalse" ]; then
						chk_uid=`echo "$chk_res" | egrep "uid=""$uid""\(""$user""\)"`
					else
						chk_uid=`echo "$chk_res" | egrep "uid=""$uid""\(""$user""\)" | egrep "gid=[0-9]*\(""$group""\)"`
					fi
					case "$chk_uid" in
						uid=*gid=*)
							p_echo " User '$user' already exists"
							;;
						*) logname_err "$user" "$uid"
							;;
					esac
					chsh -s "$u_shell" "$user"
					;;
				*)
					uid_res=`egrep "^[^:]*:[^:]*:""$uid"":" /etc/passwd`
					case "$uid_res" in
						*:*:*:*)
							uid_err "$uid"
							;;
						*)
							pnnl_echo " Trying to add user '$user'... "
							useradd $useradd_options -u "$uid" -g "$group" -d "$u_home" -s "$u_shell" -c "$u_desc" "$user" >> $product_log 2>&1 &&
							suc || die "add user '$user'"
							what_done=1
							;;
					esac
					;;
			esac
			;;
		false)
			case "$id_res" in
				0)
					p_echo " User '$user' already exists"
					;;
				*)
					pnnl_echo " Trying to add user '$user'... "
					useradd $useradd_options -g "$group" -d "$u_home" -s "$u_shell" -c "$u_desc" "$user" >> $product_log 2>&1 &&
					suc || die "add user '$user'"
					what_done=1
					;;
			esac
			;;
		*)
			p_echo "user_op: wrong last parameter -- must be 'true' or 'false'"
			p_echo
			p_echo "Exiting..."
			p_echo
			smart_undo_install
			exit 1
			;;
	esac

	p_echo
	common_var=$what_done
	if [ "X$what_done" = "X1" ]; then
		users_created="$users_created $user";
	fi
	return $what_done
}

get_user_group_id()
{
    local name="$1"
    local src_name="$2"
    local min_num="$3"
    local max_num="$4"
    local count="$min_num"

    case "$src_name" in
       uid)
            local src="/etc/passwd"
            local type="users"

            get_userID "$name"
            if [ "X$?" = "X1" ]; then
               echo "$common_var"
               return 0
            fi
       ;;
       gid)
            local src="/etc/group"
            local type="groups"
            get_groupID "$name"
            if [ "X$?" = "X1" ]; then
               echo "$common_var"
               return 0
            fi
       ;;
       *)
            p_echo "$src_name for $name was not set"
            inten="detect uid/gid. Source file was not detect."
            die "$inten"
       ;;
    esac

    if [ ! -f "$src" ]; then
	p_echo
	p_echo "ERROR!"
	p_echo "$src_file: no such file"
	p_echo "Exiting..."
	smart_undo_install
	exit 1
    fi

    if [ $min_num -le 0 -o $min_num -ge $max_num ]; then 
		p_echo "get_user_group_id(): wrong parameters"
		smart_undo_install
		exit 1
    fi 

	nums=`cat $src | awk -F: '{print $3}' - | xargs echo -n " "` 

    while [ "$count" -le "$max_num" ]; do
         echo " $nums " | grep " $count " > /dev/null 2>&1 || break
         count=`expr $count + 1`

         if [ "$count" -ge "$max_num" ]; then 
            p_echo "$src_name for $name was not set"
			inten="get free $src_name. Free $src_name not found."
			die "$inten"
         fi
    done  
    
    echo "$count"
    return 0
}

add_login_shell()
{
	local shell

	shell="$1"

	p_echo " Checking that $shell registered as login shell..."

	case $linux_distr in 
	    debian)
		add-shell $shell
	    ;;
	    *)
		if grep -q "^$shell\$" /etc/shells; then
			p_echo "$shell already registered as a login shell"
		else
			echo "$shell" >> /etc/shells 2>> $product_log || die "register login shell $shell"
		fi
	    ;;
	esac

	p_echo
}
# prep_install

prep_install()
{
	mk_backup $inetd_conf cp f
}
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="0"

	EXTERNAL_PACKAGES=""
	EXTERNAL_PACKAGES_DIR=""

	BUILDER_UID="10007"

	PERL5LIB=/usr/local/psa/lib/perl5/site_perl/5.16.0:/usr/local/psa/lib/perl5/site_perl/5.16.0/x86_64-linux-thread-multi
	export PERL5LIB

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

	product_version="11.0.9"
	product_db_version="011009"
	conceived_os_vendor=SuSE
	conceived_os_version="12.2"
	osrels="suse12.2"

	# This variable contains all versions, which is supported by
	# cumulative upgrade
	known_product_versions="80 81 82 83 84 86 90 92 93 95 100 101 107 108 109 1010 1011 1012 1013 1100"

	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
}

get_my_cnf_param()
{
	local my_cnf cnf_files

	cnf_files="/etc/my.cnf /etc/mysql/my.cnf /var/db/mysql/my.cnf"

	for my_cnf in ${cnf_files}; do
		if [ -f ${my_cnf} ]; then
			break
		fi
	done

	[ -f ${my_cnf} ] && r=`perl -e '$p="'"$1"'";
	undef $/; $_=<>; s/#.*$//gm;
	/\[mysqld\](.*?)\[/sg;
	$_=substr($1, rindex $1,"$p") and
	/$p\s*=(.*)/m and print $1
	' ${my_cnf}`
	echo $r
}

get_mysql_socket()
{
	mysql_socket="/var/run/mysql/mysql.sock"

	local mysqlsock=`get_my_cnf_param  socket`
	local MYSQL_SOCKETS="/var/lib/mysql/mysql.sock /tmp/mysql.sock /var/run/mysqld/mysqld.sock"

	for i in $mysql_socket $mysqlsock $MYSQL_SOCKETS; do
	    if [ -S "$i" ]; then
		    MYSQL_UNIX_PORT=$i
		    export MYSQL_UNIX_PORT
		    mysql_socket="$i"
		    break
	    fi
	done
}

conf_update()
{
	local def
	def="$1.default"
	umask 0022

	[ -s "$def" ] || return 1

	if [ ! -s "$1" ]; then
#		cp -f "$def" "$1"
#		return 0
		echo '#' > "$1"
	fi



perl -e '

open (my $config, $ARGV[0]) or die "Cannot open config $ARGV[0]\n";
while(<$config>){
s/#.*$//;
next if /^\s*$/;
/(\w+)\s+(.+)$/;
$cf{$1}=$2;
}
close $config;

$cf{PRODUCT_ROOT_D}=$ENV{PRODUCT_ROOT_D} if $ENV{PRODUCT_ROOT_D};

open (my $default, $ARGV[1]) or die "Cannot open default config $ARGV[1]\n";
while(<$default>){
 s/^\s*(\w+)(\s+)(.+)$/"$1$2".( (exists($cf{$1}))? $cf{$1}:$3 )/e;
 print;}
close $default;

' "$1" "$def" > "$1.new"

	if [ -s "$1.new" ]; then
	  if cmp -s $1.new $1; then
  		rm -f $1.new
		return 1
	  else
		rm -f $1.old
		ln $1  $1.old
		mv -f $1.new $1
		chmod 644 $1    # bug 64313, 65043
		p_echo "config updated"
		return 0
	  fi
	fi
	return 2
}

# setup new value for parameter
# $1 config file name $2 paramater name, $3 parameter value
conf_setval()
{
	cat $1 | awk -v varname="$2" -v varvalue="$3" 'BEGIN { f = 0 }
{ if ($1 == varname) { f = 1; print varname "\t" varvalue } else { print $0 } }
END { if (f == 0) { print "\n" varname "\t" varvalue } }' 		> $1.new

	if [ -s "$1.new" ]; then
	  if cmp -s $1.new $1; then
  		rm -f $1.new
		return 1
	  else
		rm -f $1.old
		ln $1  $1.old
		mv -f $1.new $1
		rm -f $1.old
		chmod 644 "$1"
		return 0
	  fi
	fi
	return 2
}

# A set of functions for work with config variables
# $1 is config file name, $2 is variable name, $3 is variable value

conf_getvar()
{
	cat $1 | perl -n -e '$p="'$2'"; print $1 if m/^$p\s+(.*)/'
}

conf_rmvar()
{
	cat $1 | perl -n -e '$p="'$2'"; print $_ if(! m/^$p\s+(.*)/)' >$1.new
	if cmp -s $1.new $1; then
		rm -f $1.new
		return 0
	fi
	rm -f $1.old
	ln $1  $1.old
	mv -f $1.new $1
	chmod 644 "$1"
}

conf_setvar()
{
	conf_setval "$@"
}

 #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=/srv/www/vhosts
HTTPD_CONF_D=/etc/apache2
HTTPD_INCLUDE_D=/etc/apache2/conf.d
HTTPD_BIN=/usr/sbin/httpd2
HTTPD_LOG_D=/var/log/apache2
HTTPD_SERVICE=apache2
QMAIL_ROOT_D=/var/qmail
PLESK_MAILNAMES_D=/var/qmail/mailnames
RBLSMTPD=/usr/sbin/rblsmtpd
COURIER_IMAP_ROOT_D=/
FTPD_CONF=/etc/proftpd.conf
FTPD_CONF_INC=/etc/proftpd.include
FTPD_BIN_D=/usr/bin
FTPD_VAR_D=/usr/local/psa/var/run
FTPD_SCOREBOARD=/usr/local/psa/var/run/scoreboard
NAMED_RUN_ROOT_D=/var/lib/named
NAMED_OPTIONS_CONF=/etc/named.conf.include.plesk-options
NAMED_ZONES_CONF=/etc/named.conf.include.plesk-zones
WEB_STAT=/usr/bin/webalizer
MYSQL_VAR_D=/var/lib/mysql
MYSQL_BIN_D=/usr/bin
PGSQL_DATA_D=/var/lib/pgsql/data
PGSQL_CONF_D=/var/lib/pgsql/data
PGSQL_BIN_D=/usr/lib/postgresql91/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.7
CATALINA_HOME=/usr/share/tomcat
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=/srv/www/cgi-bin/awstats
AWSTATS_TOOLS_D=/usr/share/awstats
AWSTATS_DOC_D=/usr/share/apache2/icons/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

}

#-*- vim:syntax=sh

register_service(){

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


# insserv for SuSE
	 /sbin/insserv -f "$1" >/dev/null 2>&1

	suc
}

unregister_service(){

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


	/sbin/insserv -r -f $1


	suc
}

#Need for register/unregister services into /etc/rc.conf for BSD OSes.
#Create or change strings such as service_option_variable="variable"
rc_service()
{
   local service="$1"
   local option="$2"
   local variable="$3"
   local comment="$4"
 
   local config="/etc/rc.conf"

   if [ "X$variable" = "Xdefault" ]; then
      remove_option_string "${service}_${option}" "$config"
      return 0
   fi

   if [ ! -f /etc/rc.conf ]; then
      die 'File /etc/rc.conf not found!'
   fi

   if [ "X$service" = "X" -o "X$option" = "X" -o "X$variable" = "X" ]; then
      die
   fi

   local flag="`grep "${service}_${option}" $config`"
   
   if [ "X$flag" = "X" ]; then
        if [ "X$comment" = "Xyes" ]; then
           echo "#Option for $service created by Plesk installer." >> $config
	fi
	echo "${service}_${option}=\"${variable}\"" >> $config || die 
   else
        sed -i "" -e 's|\('"${service}_${option}"'.*=\"\).*|\1'"${variable}"'\"|' $config  || die
   fi

   return 0
}

remove_option_string()
{
    #using: remove_option_string <option> <file>
    substring="$1"
    file="$2"

    awk '{
	if ($0 ~ "^'"$substring"'") {
	    next;
	}; 
	print $0; 
    }' < $file  > $file.tmp

    mv $file.tmp $file
}
# vim:syntax=sh

selinux_is_active()
{
	if [ -z "$SELINUX_ENFORCE" ]; then
		selinux_getenforce
	fi

	case "$SELINUX_ENFORCE" in
	Enforcing|Permissive) return 0;;
	*) return 1;;
	esac
}

selinux_get_mount_dir()
{
	unset SELINUX_MOUNT_DIR

	if awk '$2 == "/selinux"{exit(1)}' /proc/mounts && mkdir -p /selinux; then
		SELINUX_MOUNT_DIR=/selinux
	else
		SELINUX_MOUNT_DIR="`mktemp -d /tmp/selinuxXXXXXX`"
	fi >>"$product_log" 2>&1
}

selinux_getenforce()
{
	if [ "$1" = "--check" -a -n "$SELINUX_ENFORCE" ]; then
		return
	fi
	unset SELINUX_ENFORCE

	if ! ( command -v selinuxenabled >/dev/null 2>&1 && selinuxenabled ); then
		SELINUX_ENFORCE=Disabled
		return
	fi

	if awk '$3 == "selinuxfs"{exit(1)}' /proc/mounts; then
		selinux_get_mount_dir
		mount -t selinuxfs none "$SELINUX_MOUNT_DIR"
	fi

	if ! command -v getenforce >/dev/null 2>&1; then
		SELINUX_ENFORCE=Disabled
		return
	fi

	SELINUX_ENFORCE="`getenforce`"
	if test $? -ne 0; then
		SELINUX_ENFORCE=Disabled
		return
	fi
}

selinux_init()
{
	unset SELINUX_ENFORCE
	if selinux_is_active; then
		setenforce Permissive
	else
		unset SELINUX_ENFORCE
	fi
}

selinux_check()
{
	selinux_params
	if [ -n "$SELINUX_USE_MODULES" ]; then
		return
	fi

	if [ ! -r /etc/selinux/config ]; then
		return
	fi

	if ! selinux_is_active; then
		return
	fi

	if [ -r /etc/selinux/config ]; then
		. /etc/selinux/config
	fi

	if ! [ -r "/etc/selinux/$SELINUXTYPE/src/policy/file_contexts/program/plesk.fc" ]; then
		report_problem "Security-Enhanced Linux is activated with custom policy, and no Plesk specific rules were found. This may cause problems in Plesk functioning."
	fi
}

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

	setenforce "$SELINUX_ENFORCE"
}

selinux_install_rebuild()
{
	find /etc/selinux -mindepth 1 -maxdepth 1 -type d | while read policy_dir; do
		(
			cd $policy_dir/src/policy || exit
			# this file is from the old version
			rm -f file_contexts/misc/plesk.fc
			make -W file_contexts/program/plesk.fc 				 -W domains/program/plesk.te 				install >>"$product_log" 2>&1
		)
	done

	selinux_getenforce
 	if selinux_is_active; then
		if [ -r "/etc/selinux/config" ]; then
			. /etc/selinux/config >>"$product_log" 2>&1
			make -C "/etc/selinux/$SELINUXTYPE/src/policy" load relabel >>"$product_log" 2>&1 || :
		fi
 	fi
}

selinux_remove_module()
{
	[ -n "$1" ] || return 0
	if semodule -l | grep -q "^$1[[:space:]]"; then
		p_echo "removing selinux module: $1"
		semodule -r "$1"
	fi
}

selinux_fix_booleans()
{
    :
}

selinux_install_module()
{
	local selinux_module="$PRODUCT_ROOT_D/etc/plesk.pp"
	for dir in `find /etc/selinux -maxdepth 1 -mindepth 1 -type d`; do
		policy=`basename "$dir"`
		semodule -s "$policy" -i "$selinux_module"
	done >>"$product_log" 2>&1

	selinux_remove_module qmail
	selinux_remove_module courier
	relabel_plesk_directories

	setsebool -P ftp_home_dir 1 >>"$product_log" 2>&1
	setsebool_ifexists httpd_can_sendmail 1 || report_problem "set httpd_can_sendmail flag"
}


relabel_plesk_directories()
{
	selinux_params
	set_horde_params
	if selinux_is_active; then
		for dir in "$PRODUCT_ROOT_D" "$horde_logdir" "$NAMED_RUN_ROOT_D" 					"$HTTPD_VHOSTS_D" "$QMAIL_ROOT_D" /usr/local/frontpage					/var/db/kav /var/db/Quarantine "$PLESK_DB_DIR" 					"$POSTFIX_LIBEXEC_DIR" 					/var/drweb "$DRWEB_ROOT_D" "$PLESK_LIBEXEC_DIR" 					"/etc/nginx" "/usr/sbin/nginx" /var/lib/nginx 					"/var/log/nginx" "/var/run/nginx.pid" 					"/var/lib/plesk/mail" /opt/kav "/usr/lib64/php/modules" "/var/run" ; do
			if [ -d "$dir" ]; then
				selinux_relabel_dir -e "$NAMED_RUN_ROOT_D/proc" "$dir"
			fi
		done
	fi
}

selinux_get_config()
{
	if ! selinux_is_active || ! [ -r "/etc/selinux/config" ]; then
		return 1
	fi

	. /etc/selinux/config >>"$product_log" 2>&1
}

selinux_install()
{
	#FIXME: possible 'initial_conf', 'set_common_params'  must to be removed
	#already userd in package_script_begin
	initial_conf
	set_common_params
	set_syslog_params

	echo_try "install $PRODUCT_NAME specific permissions"
	selinux_params
	selinux_install_rebuild
	selinux_fix_booleans
	suc

	reload_syslog
}

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

# for modules only
selinux_policy_upgrade_trigger()
{
	if [ -n "$PLESK_INSTALLER_DEBUG" ]; then
		set -x
	fi

	if [ "X${PLESK_INSTALLER_STRICT_MODE}" != "X" ]; then
		set -e
	fi

	initial_conf
	package_script_call_main_function_begin "" 		"$PRODNAME-selinux-policy-trigger" "$product_version" "$product_build"
	if selinux_is_active 	    && [ "`semodule -l | awk '/plesk/{ print $2}'`" != "$product_version" ];
	then
	    echo_try "install Plesk $product_version rules"
	    selinux_install_module
	    suc
	else
	    p_echo "Plesk $product_version rules already installed"
	fi

	selinux_remove_module qmail
	selinux_remove_module courier
	selinux_fix_booleans
	package_script_end_handler ok
}

setsebool_ifexists()
{
	if ! command -v setsebool >/dev/null 2>&1; then
		return
	fi
	if ! getsebool -a|grep -q "$1"; then
		return
	fi
	setsebool -P "$1" "$2"
}


selinux_params()
{
    SELINUX_USE_MODULES=
}

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

selinux_set_exclude_arg_filter()
{
	SELINUX_EXCLUDE_ARG="-e $1"
}


necessary_system_accounts_prep_install()
{
	p_echo
	p_echo "===> Checking for the necessary system accounts"
	common_var=0

# for mysql
	p_echo " Checking for the system groups and users necessary for MySQL..."
	group_op "$mysql_group" "$mysql_GID" false
	user_op "$mysql_user" "$mysql_UID" "$mysql_group" "MySQL Server" "/" "$dummy_shell" false

# for admin
	p_echo " Checking for the system groups and users necessary for admin server..."
	group_op "$admin_group" "search" false
	user_op "$admin_user" "search" "$admin_group" "Admin Server" "$dummy_home" "$dummy_shell" false

# for psaservices (only after creating apache and psaftp)
	group_op "$services_group" "$services_GID" false
	add_user_to_group "$apache_user" "$services_group"
	add_user_to_group "$anonftp_user" "$services_group"
	add_user_to_group "$admin_user" "$services_group"

# clients
	found=`get_user_group_id "clients" "gid" $clients_GID $max_suexec_GID`
	group_op $clients_group $found false

#for bind in MacOS
	if [ -x /usr/bin/niutil ]; then
		/usr/bin/niutil -list / /users/bin >>$product_log 2>&1

		/usr/bin/niutil -list / /groups/bind >>$product_log 2>&1
		if [ "$?" != "0" ]; then 
			group_op "bind" "53" true		
		fi
	fi
}

necessary_system_accounts_post_install()
{
	# these users may not exist before packages isntallation
	add_user_to_group sw-cp-server "$admin_group"
}

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

	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/lib/postfix"
	PRODUCT_BOOTSTRAPPER_DIR="/usr/local/psa/bootstrapper/pp11.0.9-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
}

set_common_params_darwin()
{
	machine="Darwin"
	sendmail="/usr/sbin/sendmail"
	mail_local=""
	ps="ps axw"
	ps_long="ps axSwu"
	dummy_shell="/usr/bin/false"
	dummy_home="/"
	false_shell="/usr/bin/false"
	bash_shell="/bin/bash"
	rbash_shell="/bin/rbash"
	compress="gzip -9 -c"
	uncompress="gunzip -c"
	uudecode="uudecode -p"
	uudecode_full="/usr/bin/uudecode"
	ifconfig="/sbin/ifconfig -a"
	inet_str="inet"
	named_osrelease=0
	fstab="/etc/fstab.hd"

	return 0
}

set_common_params_freebsd()
{
	machine="BSD"
        fstab="/etc/fstab"
	sendmail="/usr/sbin/sendmail"
	mail_local="/usr/libexec/mail.local"
	ps="ps axw"
	ps_long="ps axfwu"
	dummy_shell="/sbin/nologin"
	dummy_home="/"
	false_shell="/usr/bin/false"
	bash_shell="/usr/local/bin/bash"
	rbash_shell="/usr/local/bin/rbash"
	compress="gzip -9 -c"
	uncompress="gunzip -c"
	uudecode="uudecode -p"
	uudecode_full="/usr/bin/uudecode"
	ifconfig="/sbin/ifconfig -a"
	inet_str="inet"
	os_version=`uname -v | sed -e 's/^.*FreeBSD[ \t][ \t]*\([0-9\.][0-9\.]*\)-.*$/\1/'`
	tar="gtar"
	named_osrelease=040100 # "must be >= 020218 for  named -u <named> "

	return 0
}

define_start_script()
{
	if [ -f "$PRODUCT_RC_D/${product}.sh" ]; then
		START_SH="$PRODUCT_RC_D/${product}.sh"
	else
		START_SH="$PRODUCT_RC_D/${product}"
	fi
}

set_local_params()
{
	for i in set_admin_params lock_keyupdate set_apache_params set_awstats_params set_courier_imap_params set_syslog_params set_logrotate_params set_mysqld_params set_qmail_params set_webalizer_params set_horde_params set_atmail_params ; do
		$i
		local res="$?"
		if [ "0$res" -gt 0 ]; then
			return "$res"
		fi
	done
}



# set necessary owner and access permissions under product root after extraction
# there must be additional settings for files, generated by futher installation
set_def_perms()
{
	p_echo
	p_echo "===> Installing default permissions"

	set_mysql_perms

	if [ "X$DEMO_VERSION" != "Xyes" ]; then
		# remove old LICENSE; set perms on new
		[ -f "$PRODUCT_ROOT_D/LICENSE" ] && rm -f "$PRODUCT_ROOT_D/LICENSE"
		# set_ac root 0 444 "$PRODUCT_ROOT_D/license.html"

		set_apache_perms
		set_webalizer_perms
		if [ "X${linux_distr}" = "Xdebian" ]; then
			set_awstats_perms_debian
		fi
	fi

	set_logrotate_perms

	if [ "X$DEMO_VERSION" != "Xyes" ]; then
		set_perl_perms
	fi

	chown root:psacln $PRODUCT_ROOT_D/bin/chrootsh

	### This is not required because --owner=0 --group=0 is specified for tar
	# chown_builder2root

	p_echo
}


chown_builder2root()
{
	### set permissions for all dirs except home dir
	find $PRODUCT_ROOT_D/ -not -name "home" -mindepth 1 -maxdepth 1 | while read dir; do
		find "$dir" -user $BUILDER_UID -exec chown -h root:0 "{}" \;
	done

	### set permissions for home dir
	if [ -d "$PRODUCT_ROOT_D/home" ]; then
		chown -h root:0 "$PRODUCT_ROOT_D/home"
		chown -h root:0 "$PRODUCT_ROOT_D/home/vhosts"
		for dir in default .skel chroot; do
			if [ -d "$PRODUCT_ROOT_D/home/vhosts/$dir" ]; then
				find "$PRODUCT_ROOT_D/home/vhosts/$dir" -user $BUILDER_UID -exec chown -h root:0 "{}" \;
			fi
		done
	fi
}

set_swcpserver_params()
{
	swcpserver_service=sw-cp-server
	swcpserver_binary=/usr/sbin/sw-cp-serverd
	swcpserver_pidfile=/var/run/sw-cp-server.pid

	true swcpserver_status
}

swcpserver_status()
{
	get_pid "$swcpserver_binary" false
	local pid=$common_var
	if [ "$pid" -ne 1 ]; then
		return 0
	fi
	return 1
}
check_opsys()
{
    check_opsys_linux
    
    if [ $? -ne 0 ]; then
       exit 1
    fi
    
    return 0
}

check_opsys_darwin()
{
    if [ "X$machine" != "XDarwin" ]; then
       print_opsys_error
       return 1
    fi

    mkdir -p $PRODUCT_ROOT_D
   
    return 0
}

check_opsys_freebsd()
{
    if [ "X$machine" != "XBSD" ]; then
       print_opsys_error
       return 1
    fi

    local sys_branch=`uname -r | awk -F '-' '{print $1}' | awk -F '.' '{print $1}'`
    local build_branch=`echo "$conceived_os_version" | sed -e 's/^\(.\).*/\1/'`
    local sys_minor_ver=`uname -r | awk -F '-' '{print $1}' | awk -F '.' '{print $2}'`
    local build_minor_ver=`echo "$conceived_os_version" | awk -F '.' '{print $2}'`

    if [ $sys_branch -ne $build_branch ]; then
        p_echo "This build does not support your operating system version."
        p_echo "Please ensure that you have the build appropriate for your" 
        p_echo "operating system version."

        exit 1
    fi

    if [ "X$sys_minor_ver" = "X" -o "$build_minor_ver" = "X" ]; then
       return 0
    fi

    if [ $sys_minor_ver -lt $build_minor_ver ]; then
       p_echo "Your operating system version is out of date. "
       p_echo "We recommend that you update your operating system before" 
       p_echo "proceeding with the upgrade. Otherwise, you might impose"
       p_echo "your system to security risks."
    fi

    return 0
}

check_opsys_linux()
{
    if [ "X$machine" != "Xlinux" ]; then
       print_opsys_error
       return 1
    fi

    return 0  
}

print_opsys_error()
{
    p_echo "This installer is not support $machine platform."
    p_echo "Please obtain proper installer for $machine."
   
    exit 1
}
set_syslog_params()
{
	syslog_service="syslog"
	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
		local syslog_daemon
		for syslog_daemon in rsyslogd syslog-ng syslogd ; do
			syslog_binary="/sbin/$syslog_daemon"
			test -x "$syslog_binary" && break
		done
	fi
}
## @@constructor set_syslog_params


syslog_status_linux_debian()
{
	get_pid "$syslog_binary" false
	local pid=$common_var
	if test "$pid" -ne 1; then
		# running
		return 0
	fi
	return 1
}


reload_syslog()
{
	if [ "X$syslog_service" = "Xsyslog" -a "X$syslog_binary" = "X/sbin/rsyslogd" ]; then
		pleskrc syslog restart
	else
		pleskrc syslog reload
	fi
}


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

register_component()
{
	local name
	local version
	name="$1"
	version="$2"
    serviceNodeId="1"

	db_do "REPLACE ServiceNodeProperties (serviceNodeId, name, value) VALUES ($serviceNodeId, 'server.packages.$name', '$version')"
}

get_product_versions()
{
	local prod_root_d="/usr/local/psa"
	
	product_name="psa"
	product_this_version="11.0.9"
	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
}
set_logrotate_params()
{
	# primary Plesk logrotate config file
	logrotate_conf="${product_etc}/logrotate.conf"

	# directory for logrotate configs of virtual hosts
	logrotate_include_d="${PRODUCT_ETC_D}/logrotate.d"
}

## @@constructor set_logrotate_params

set_logrotate_perms()
{
	inten="set up default logrotate permissions"
	echo_try $inten

	# set permissions, only if logrotate is built-in
	if [ -d ${PRODUCT_ROOT_D}/logrotate ]; then
	    set_ac 0 0 755 "${PRODUCT_ROOT_D}/logrotate" || die "$inten"
	    set_ac 0 0 755 "${PRODUCT_ROOT_D}/logrotate/*" || die "$inten"
	    set_ac 0 0 755 "${PRODUCT_ROOT_D}/logrotate/sbin/*" || die "$inten"
	    set_ac 0 0 755 "${PRODUCT_ROOT_D}/logrotate/man/*" || die "$inten"
	    set_ac 0 0 644 "${PRODUCT_ROOT_D}/logrotate/man/man8/*" || die "$inten"
	fi

	suc
}

install_logrotate()
{
	inten="install logrotate configs"

	if [ ! -f ${logrotate_conf} -o "X$std_to_pkg" = "X1" ]; then

		inten="create logrotate config file"

		parse_logrotate_conf "${PRODUCT_ETC_D}/logrotate.conf.in" "$logrotate_conf" 

		set_ac root ${admin_group} 640 "${logrotate_conf}" && suc || die "$inten"

		rm -f ${PRODUCT_ETC_D}/logrotate.conf-upgrade.in || die "$inten"
		rm -f ${PRODUCT_ETC_D}/logrotate.conf.in || die "$inten"

	fi

	if [ ! -d ${logrotate_include_d} ]; then
		inten="create logrotate include directory"

		mkdir -p "${logrotate_include_d}" || die "$inten"
		set_ac root ${admin_group} 640 "${logrotate_include_d}" || die "$inten"
	fi
}

parse_logrotate_conf()
{
    local config_in="$1"
    local config_out="$2"

    if [ ! -f ${config_in} ]; then
	return 1
    fi

    sed -e "s|@@PRODUCT_ROOT_D@@|${PRODUCT_ROOT_D}|g" \
	-e "s|@@HTTPD_LOG_D@@|${HTTPD_LOG_D}|g" \
	-e "s|@@CATALINA_HOME@@|${CATALINA_HOME}|g" \
	< $config_in > $config_out || die "$inten"
    
    return 0
}

add_tomcat_to_logrotate()
{
    local template="$1"

    inten="add tomcat logs into logrotate configs"
    echo "$inten"

    parse_logrotate_conf "${PRODUCT_ETC_D}/logrotate.conf-tomcat.in" "${logrotate_conf}-tomcat"
    cat ${logrotate_conf}-tomcat >> $logrotate_conf

    rm -f ${logrotate_conf}-tomcat
    
    return 0
}

#all functions in this file are valid for Standard builds only
set_mailman_params()
{
	mailman_user="mailman"
	mailman_group="mailman"
	mailman_UID=72
	mailman_GID=67
	MAILMAN_ROOT_D="/usr/lib/mailman"
	MAILMAN_VHOST_D="${HTTPD_VHOSTS_D}"/mailman

	mailman_service="mailman"
	mailman_log="/dev/null"
}


cleanup_mailman_libs()
{
	set_mailman_params
	rm -rf "$MAILMAN_ROOT_D/Mailman" ||:
	rm -rf "$MAILMAN_ROOT_D/cgi-bin" ||:
	rm -rf "$MAILMAN_ROOT_D/scripts" ||:
	rm -rf "$MAILMAN_ROOT_D/pythonlib" ||:
}

mailman_status_BSD()
{
	local pidfile="${MAILMAN_ROOT_D}/data/master-qrunner.pid"

	if [ -f "$pidfile" ]; then
	    pid="`cat $pidfile`"
	    if [ -z "$pid" ]; then
		    warn "pidfile does not correct"
		    return 1
	    fi

	    ps ax | grep -q $pid 2>&1 >>$product_log
	    [ $? -eq 0 ] && return 0
	fi

	return 1
}
# -*- shell-script -*-
# configures Mailman to use a given mailserver
# Currently Postfix and QMail, both as "Manual" (see comments below)
set_mailman_mailsrv()
{
    local cfg server

    cfg=$1
    server=$2

    if [ -z "$cfg" ]; then
        simply_die "Usage: $0 /path/to/mm_cfg.py (qmail|postfix)"
    fi

    case "$server" in
        qmail)
            server="Manual"
            ;;
        postfix)
            # Although Mailman supports Postfix "directly" (i.e. it has
            # a code to control Postfix system aliases (typically, /etc/aliases)
            # we keep Mailman related system aliases in an additional hashed
            # database (hash:/var/spool/postfix/plesk/aliases)
            # (for various reasons), so we have to manage Mailman-specific alias
            # manually as with QMail
            server="Manual"
            ;;
        *)
            simply_die "Currently only qmail and postfix are supported"
            ;;
    esac

    if [ ! -f "$cfg" ]; then
        simply_die "Usage: no such file or directory \"$cfg\""
    fi

    #declare pymod pydir curmta
    local pydir pymod
    pydir=$(dirname "$cfg")
    [ -z "$pydir" ] && pydir="."
    pymod=$(basename "$cfg")
    pymod=${pymod%%.py}

    local python_bin
    python_bin="/usr/bin/python2.7"

    local currentServer
    currentServer=$(PYTHONPATH="${PYTHONPATH}:$pydir" "${python_bin}" -c "import $pymod; print $pymod.MTA")
    if [ $? -ne 0 ]; then
        simply_die "Unable to load current settings"
    fi

    if [ "x${currentServer}" = "x${server}" ]; then
        # nothing to do
        return 0
    fi

    local tmpcfg bakcfg

    bakcfg="${cfg}.saved_by_plesk"
    tmpcfg=$(mktemp "${cfg}.XXXXXX")
    if [ $? != 0 ]; then
        simply_die "Unable to creare a temporary file for ${cfg}"
    fi
    trap "mailman_trap_handler \"$tmpcfg\"" HUP PIPE INT TERM EXIT
    awk -v server="$server" 'BEGIN { found=0; }
/^[[:space:]]*MTA[[:space:]]*=/ {
    print "### ", $0;
    if (!found) {
        str=$0;
        sub(/=.*/, "='"'"'" server "'"'"'", str);
        $0=str;
        found=1;
    }
}
{ print $0; }
END {
    if (!found) {
        print "MTA='"'"'" server "'"'"'";
    };
    exit 0;
}' "$cfg" >>"$tmpcfg"
    rc=$?
    if [ 0 -eq $rc ]; then
        p_echo "updating configuration file $cfg"
        rm -f "$bakcfg" 2>/dev/null; # errors will be reported later
        ln "$cfg" "$bakcfg" &&             mv -f "$tmpcfg" "$cfg" || simply_die "unable to save new configuration"
        rm -f "$tmpcfg"
        trap - HUP PIPE INT TERM EXIT
    else
        simply_die "unable to process \"$cfg\""
    fi
    return 0
}

# This function tries to configure Plesk-specific
# wrapper (mm_wrapper) which ensures that
# /usr/lib/mailman/mail/mailman will be called with
# the correct group.
# The problem is that on RH* and derivatives
# /usr/lib/mailman/mail/mailman should be called
# from within a process with one of the following groups:
# mail, nobody, postfix, daemon
# while on SuSE this should be a group whose gid is
# stored in either /etc/mailman/mailman.mail-gid or
# /etc/mailman/mailman.cgi-gid. This group must to be
# coincide with GID for postfix-mailman process from
# postfix master.cf config file.
# So if the file /etc/mailman/mailman.mail-gid exist
# we ensure that it contains an appropriate gid and
# change the file if needed (preserving a backup)
# If the file is missing then we make sure that
# mm_wrapper is SGID mail.
#
# Requirements: coreutils, grep, sed, perl

set_mailman_wrapper_perms()
{
    local mm_wrapper initial_group gidfiles backup

    mm_wrapper=/usr/lib64/plesk-9.0/mm_wrapper
    initial_group=popuser
    gidfiles="/etc/mailman/mailman.mail-gid /etc/mailman.mail-gid"
    backup=.saved_by_psa

	[ -f "$mm_wrapper" ] || return

    local mm_wrapper_group

    if mailman_isSGID "$mm_wrapper" ; then
        mm_wrapper_group=$(mailman_getFGID "$mm_wrapper")
    else
        mm_wrapper_group=$(mailman_getGNam "$initial_group")
    fi

    [ -z "$mm_wrapper_group" ] && simply_die "unable to get current mm_wrapper group"

    # Now check the style of operation
    hasGidfile=0;
    for gidfile in $gidfiles; do
        if [ -r "$gidfile" ]; then
            if [ x$(cat "$gidfile") != x$mm_wrapper_group ]; then
                cp -pr "$gidfile" "$gidfile$backup" || simply_die "Unable to create a backup file";
                echo -n "$mm_wrapper_group" > "$gidfile";
            fi;
            hasGidfile=1;
        fi;
    done;

    if [ $hasGidfile = 0 ]; then
        # need to "hardcode" the SGID group
	if [ "X$machine" = "XBSD" ]; then
		chown :mailman "$mm_wrapper"
	else
		chown :mail "$mm_wrapper"
	fi
        chmod g+s "$mm_wrapper"
    fi
    return 0
}

# 1st check if the mm_wrapper is SGID
mailman_isSGID() {
    # Does it really work? ;-)
    ! perl -e "exit(-g \"$1\");"
}

# stat has different options in Linux and in
# other supported systems
mailman_getFGID()
        { stat -c%g "$1"; }

# hack! hack! hack!
mailman_getGNam()
    { grep "^$1:" /etc/group | cut -f 3 -d ':'; }

mailman_trap_handler()
{
    trap - EXIT
    rm -f -- "$1"
    exit
}
upgrade_mailman_86()
{
	if [ "X$machine" = "XBSD" -a "$do_upgrade" = "1" ]; then
		conf_setvar "$prod_conf_t" "MAILMAN_ROOT_D" "/usr/lib/mailman" 
		conf_setvar "$prod_conf_t" "MAILMAN_VAR_D" "/var/lib/mailman" 
	fi
}

install_modules()
{
	if [ ! -f "$PRODUCT_ROOT_D/tmp/modules.list" ]; then
		return 0
	fi

	p_echo
	p_echo "===> Installing modules"

	local moduledist
	for moduledist in `cat $PRODUCT_ROOT_D/tmp/modules.list`; do
		echo_try "install $moduledist"
		"$PRODUCT_ROOT_D/tmp/$moduledist" && suc || warn "installation of $moduledist"
		rm -f "$PRODUCT_ROOT_D/tmp/$moduledist"
	done

	rm -f "$PRODUCT_ROOT_D/tmp/modules.list"
}

remove_modules()
{
	p_echo
	p_echo "===> Removing modules"

	local moduledir
	for moduledir in $PRODUCT_ROOT_D/var/modules/*; do
		if [ -d "$moduledir" -a -x "$moduledir/uninstall" ]; then
			local module=`basename $moduledist`
			echo_try "uninstall $module module"
			"$moduledir/uninstall" && suc || warn "uninstallation of $module module"
		fi
	done
}

set_module_params()
{
	case $machine in
	    BSD*)
		packname="psa-module-$module"
	    ;;
	    *)
		packname="psa-$module"
	    ;;
	esac

	scriptname="psa-$module"

	# This is the version like 10203
	module_version_n=$((`echo "$module_version" | sed -e 's/^\(.*\)\.\(.*\)\.\(.*\)$/\1*10000+\2*100+\3/'`))

	build="110130220.09"

	product_rc_d="/etc/init.d"

	module_db_sql="$PRODUCT_ETC_D/modules/$module/${module}_db.sql"

	module_var="$PRODUCT_ROOT_D/var/modules/$module"

	sedflags="-r"
}

check_module_no_db()
{
	[ -e $vza_file ] && return

	p_echo "===> Checking database"

	get_mysql_socket

	previous_version_n=`echo "select \\\`release\\\` from \\\`Modules\\\` where \\\`name\\\`='$module'" | $mysql`
	if [ "X$previous_version_n" != "X" ]; then
		if [ "$previous_version_n" -gt "$module_version_n" ]; then
			p_echo "A newer version of $module_full module is already installed!"
			exit 1
		fi
	fi
}

module_uninstall_registration()
{
	[ -e $vza_file ] && return

	p_echo "===> Unregistering module"

	get_mysql_socket

	echo "delete from \`Modules\` where \`name\`='$module';" | $mysql;
}

upgrade_modules_permissions_1013()
{
	chown psaadm:0 ${PRODUCT_ROOT_D}/var/modules
}
# -*- vim:syntax=sh

# mysql

set_mysqld_params()
{
	mysql_user="mysql"
	mysql_UID=3306
	mysql_group="mysql"
	mysql_GID=3306

	product_db_sql="$PRODUCT_BOOTSTRAPPER_DIR/db/${PRODNAME}_db.sql"

	set_mysql_server_params
	set_mysql_client_params
}

## @@constructor set_mysqld_params

set_mysql_server_params()
{
	local service

	MYSQL_ROOT="$PRODUCT_ROOT_D/mysql"
	mysql_bindir="$MYSQL_BIN_D"

	get_mysql_socket

	if [ -x "${PRODUCT_RC_D}/mysql" ]; then
	    mysql_service="mysql"
	elif [ -x "${PRODUCT_RC_D}/mysql.sh" ]; then
	    mysql_service="mysql.sh"
	elif [ -x "${PRODUCT_RC_D}/mysqld" ]; then
	    mysql_service="mysqld"
	elif [ -x "${PRODUCT_RC_D}/mysql" ]; then
	    mysql_service="mysql"
	elif [ "X$DEMO_VERSION" = "Xyes" ]; then
	    mysql_service="mysqld"
	else
	    die "$inten"	
	fi
}



set_mysql_client_params()
{
	mysql_client="$MYSQL_BIN_D/mysql"

#	Override these variables as needed
	mysql_db_name="$PRODNAME"
	mysql_passwd_file="$product_etc/.${PRODNAME}.shadow"
	prev_mysql_passwd_file="$PREV_PRODUCT_ROOT_D/admin/conf/admin.conf"

 	if [ -z "$mysql_unconfigured" ];then
#	Need for mysql_status related function
		set_mysql_server_params	
		set_mysql_auth
	fi

	mysql_args="-N"
	mysql_args_raw="-Br"

	# For backward compatibility only, should use mysql() and mysql_raw() instead
	mysql=mysql
	mysql_raw=mysql_raw
}

generate_mysql_credentials()
{
	mysql_defaults="$1"
	shift
	mysql_user=${1:+--user=$1}
	shift
	mysql_passwd=${*:+--password=$*}
}

# This function must be called *ONLY* for psa installation
setup_admin_login()
{
	unset MYSQL_PWD
	local mysql_db_name="mysql"
	local IFS_OLD
	local sl
	local inten="define valid mysql credentials"
	local i

	echo_try "$inten"
	get_admin_passwd
	IFS_OLD=$IFS

# --no-defaults:admin:$admin_passwd		admin with pass
# --no-defaults:root:					root without pass
# :root:								root with pass in defaults
# --no-defaults:admin:					admin withiyt pass
# --no-defaults:admin:$PRODUCT_DEFAULT_PASSWORD		admin with default pass
# :admin:								admin with pass in defaults
# ::									user and pass in defaults
# --defaults-file=/root/.my.cnf			hspc defaults (paranoid)
#
	for sl in `sequence 20`; do
		for i in	"--no-defaults:admin:$admin_passwd" 					"--no-defaults:root:" 					":root:" 					"--no-defaults:admin:" 					"--no-defaults:admin:$PRODUCT_DEFAULT_PASSWORD" 					":admin:" 					"::" 					"--defaults-file=/root/.my.cnf::"; do
			IFS=":"
			generate_mysql_credentials $i
			IFS=$IFS_OLD
			if mysql_test_connection; then
				suc
# 	create/Update admin superuser
				echo "grant all privileges on *.* to 'admin'@'localhost' identified by '$admin_passwd' with grant option;flush privileges" | mysql_direct mysql
				update_psa_shadow
				set_mysql_auth
#	backup private my.cnf if it contains password (vz/hspc related)
				rm -f /.my.cnf
				grep -q '\s*password\s*=' /root/.my.cnf 2>/dev/null && mv -f /root/.my.cnf /root/.my.cnf.bak
				return 0
			fi
		done
		p_echo "One more attempt to connect"
		sleep "$sl"
	done
	die "$inten"
}

update_psa_shadow()
{
	echo "$admin_passwd" > $mysql_passwd_file || die
	chown $admin_user:$admin_group ${mysql_passwd_file} || die
	chmod 600 ${mysql_passwd_file} || die
}

encrypt_psa_shadow()
{
	local init_conf_bin="$PRODUCT_ROOT_D/bin/init_conf"
	[ -x "$init_conf_bin" ] && 	PSA_PASSWORD="$admin_passwd" "$init_conf_bin" --set-admin-password -passwd '' -encrypted-password >> "$product_log" 2>&1
	if [ "$?" -eq 0 ]; then
		admin_passwd=
		set_mysql_auth
	else
		warn "encrypting admin password"
	fi
}

# iF YOUR package want to use mysql db you must call this function directly
set_mysql_auth()
{
	local inten="set up mysql authentification"
	get_admin_passwd

	pleskrc mysql start

	mysql_user="--user=admin"
	mysql_passwd="--password=$admin_passwd"
	unset mysql_defaults

	if [ -z "$MYSQL_AUTH_SKIP_CONNECTION_CHECK" ]; then
		mysql_test_connection 60 || die "$inten"
	fi
	suc
}

get_admin_passwd()
{
    [ -z "$admin_passwd" ] || return 0

    if [ -f "$mysql_passwd_file" ]; then
		admin_passwd=`cat "$mysql_passwd_file"`
		return 0
    fi

	admin_passwd=`get_random_string 12 'A-Za-z0-9_'`

	[ -n "$admin_passwd" ] || admin_passwd="$PRODUCT_DEFAULT_PASSWORD"
}

reset_admin_passwd()
{
	[ -n "$admin_passwd" ] || die "admin_passwd is not set yet"
	# I bet someone somewhere replaces 'localhost' with '%' (for weird automation purposes), so be nice
	echo "SET PASSWORD FOR 'admin'@'localhost' = PASSWORD('$admin_passwd')" | mysql_direct mysql || 	echo "SET PASSWORD FOR 'admin'@'%'         = PASSWORD('$admin_passwd')" | mysql_direct mysql
}

#Invoke mysql
mysql()
{
	mysql_anydb -D$mysql_db_name "$@"
}

mysql_anydb()
{
	$mysql_client $mysql_user $mysql_passwd $mysql_args "$@" 2>>"$product_log"

	local status=$?
	if [ $status -gt 0 ]; then
		$mysql_client $mysql_user $mysql_passwd $mysql_args -D$mysql_db_name $mysql_args_raw -e "SHOW ENGINE innodb status" >>"$product_log" 2>&1
	fi
	return $status
}

# Invoke mysql without any wrapper or something else
mysql_direct()
{
	$mysql_client $mysql_defaults $mysql_user $mysql_passwd $mysql_args "$@" 2>>"$product_log"
}

# Invoke mysql in raw mode
mysql_raw()
{
	mysql $mysql_args_raw "$@"
}

mysql_raw_anydb()
{
	mysql_anydb $mysql_args_raw "$@"
}

set_mysql_perms()
{
###	std only
	inten="set up default mysql permissions"
	echo_try $inten

	chown -R 0:0 "$MYSQL_ROOT"
	
	local dir
	for dir in $MYSQL_ROOT/var $mysql_dbdir; do
		[ -d "$dir" ] || mkdir -m 700 $dir
		chown -R $mysql_user:$mysql_group "$dir"
	done

	suc
}

install_mysql()
{
### std-only
	p_echo "===> Installing MySQL Server"

	pleskrc mysql stop

	local socket_dir=`dirname $mysql_socket`
	
	if [ -n "$socket_dir" -a ! -d "$socket_dir" ]; then
		mkdir -p $socket_dir || err
		set_ac $mysql_user $mysql_group 755 $socket_dir
	fi

	rm -rf $mysql_socket

	pleskrc mysql start

    pnnl_echo " Installing privileges Database... "
    $mysql_bindir/mysql_install_db >> "$product_log" 2>&1 || die

    p_echo "done"
	setup_admin_login

	product_install_db
}

mysql_start_linux_suse_ex()
{
	if [ -x "/sbin/service" ]; then
		action_cmd="/sbin/service mysql"
	else
		action_cmd="$SYSTEM_RC_D/$mysql_service"
	fi

	$action_cmd start >> $product_log 2>&1
}


mysql_start_linux_suse()
{
	inten="start service mysql"
	echo_try "$inten"

	mysql_start_linux_suse_ex
	local rc="$?"

# bug 52690. MySQL init script reports failure if protected mysqld is running (true for SuSE >= 11.3)
	if [ "$rc" -ne 0 ]; then
		local mysqld_bin="/usr/sbin/mysqld"
		killall -TERM mysqld >> $product_log 2>&1
		if [ -x "$mysqld_bin" ]; then
			for i in 2 4 8 16 32; do
				get_pid "$mysqld_bin" false
				local pid="$common_var"
				if test "$pid" -eq 1; then
					break
				fi
				killall -TERM mysqld >> $product_log 2>&1
				sleep $i
			done
		fi
		mysql_start_linux_suse_ex
		rc="$?"
	fi

	[ "$rc" -eq 0 ] && suc || warn "$inten"
	return $rc
}

mysql_test_connection()
{
	inten="establish test connection"
	echo_try $inten
	attempts=${1:-1}	
	for i in `sequence $attempts`; do
		echo "" | mysql_direct mysql >> "$product_log" 2>&1
		if [ "$?" -eq "0" ]; then
			p_echo "connected"
			return 0
		fi
		[ "$attempts" -eq "1" ] || sleep 2
	done

	p_echo "failed"
	return 1
}

###	FIXME: probably need var service_restart warn
mysql_stop()
{
	local op_result i

	inten="stop MySQL server"
	echo_try $inten

	$PRODUCT_RC_D/$mysql_service stop >> $product_log 2>&1

	op_result=$?

	if [ "X$linux_distr" = "Xdebian" ]; then
# Debian has well designed mysql stopping code
		[ "$op_result" -eq 0 ] || die $inten
		suc
		return 0
	fi

	for i in 2 4 6 8 16; do
		if ! mysql_status ; then
			suc
			return 0
		fi

		case $machine in
			BSD*|Darwin*)
				#In BSD systems mysqld must to be killed without -9 flag
				killall mysqld mysqld_safe >> $product_log 2>&1
			;;
			*)
				# I just want to be sure that mysql really stopped
				killall -TERM mysqld mysql safe_mysqld mysqld_safe >> $product_log 2>&1
			;;
		esac
		sleep $i
	done

	die "$inten"
}

mysql_status()
{
	local file

    #Check with native script first
	#debian script always return 0. bug #111825
	[ "X$linux_distr" = "Xdebian" ] && msqld_status_supported="no"
	
	if [ -z "$msqld_status_supported" ]; then
# MySQL AB packages doesn't know about status command
		if LC_MESSAGES=C $PRODUCT_RC_D/$mysql_service 2>&1 | grep -q "status"; then
			msqld_status_supported="yes"
		else
			msqld_status_supported="no"
		fi
	fi

	if [ "$msqld_status_supported" = "yes" ]; then
# Common RPM mysql's and FreeBSD
	$PRODUCT_RC_D/$mysql_service status >> $product_log 2>&1 		&& return 0
	fi

	if [  "$msqld_status_supported" = "no" ]; then
# MySQL AB packages
		file="/usr/sbin/mysqld"
	fi

    if [ -x "$file" ]; then
		#standard build and debian
		get_pid "$file" false
		pid=$common_var
		if test "$pid" -ne 1; then
			echo "$file (pid $pid) is running..." >>$product_log 2>&1
			return 0
		else
			echo "$file is stopped" >>$product_log 2>&1
			return 1
		fi
	fi

	return 1
}

check_db()
{
	local myOK db_connected db_password

	inten="find $PRODNAME database"
	echo_try $inten

#	If database not exists
	if ! db_test --any-db "SHOW DATABASES" '/^psa$/'; then
		p_echo "not found"
		local mysql_db_name="mysql"
		db_do "drop database if exists test"
		db_do "delete from user where User=''"
		db_do "delete from user where User='root'"
		db_do "flush privileges"
		return 1
	fi
#	Database found, but version undefined
	if ! db_select "select val from misc where param='version'" || [ -z "$db_select_output" ]; then
		p_echo "DATABASE ERROR!!!"
		p_echo "Database $PRODNAME found, but version undefined"
		die $inten
	fi

	prev_db_version="$db_select_output"

# Now check psa database version
	p_echo "version is $prev_db_version"
	prev_db_short_version=`expr ${prev_db_version} / 10`

	if [ "0$prev_db_short_version" -ne "0$prev_short_version" -a 		 "0$product_db_version" -ne "0$prev_db_version" ]; then
		p_echo "DATABASE ERROR!!!"
		p_echo "Previous product version is ${prev_version}, but previous database"
		p_echo "version is ${prev_db_version}. In most of cases it is result of"
		p_echo "previous upgrade try failure. Please, restore previous version"
		p_echo "from backup, and try again or contact technical support."
		die "check database version"
    fi

	# this message for situation, where psa was deleted, but database not
    if [ "X$prev_db_version" = "X$product_db_version" -o 		 "X${product_db_version}" = "X$prev_db_version" ]; then
	    p_echo "Version is OK, no need to create $PRODNAME database."
    fi

	return 0;
}

product_install_db()
{
	p_echo "===> Installing $PRODNAME database"

#	Start mysql without test connection mysql isn't initialize yet
	pleskrc mysql start

	setup_admin_login	

	get_mysql_socket

	inten="check ${PRODNAME} database"
	echo_try $inten
	if check_db; then
	    # product database OK, no need to create it
	    return 0
	fi

	inten="install initial $PRODUCT_NAME database"
	echo_try $inten
	[ -f "$product_db_sql" ] || die "$inten: file not found: $product_db_sql"
	mysql_anydb < $product_db_sql && suc || die $inten

	db_do "replace into misc (param,val) values('def_locale', '$default_locale')"
	db_do "$query replace into locales(id) values('$default_locale')"
	db_do "$query alter table clients alter locale set default '$default_locale'"

	db_install_dashboard_presets

	db_init_updater_state

	set_db_version
	db_do "REPLACE INTO misc(param, val) VALUES('mysql41_compatible', 'true')"
}

db_install_dashboard_presets()
{
	local inten
	inten="install initial Desktop presets"
	mysql < "$PRODUCT_BOOTSTRAPPER_DIR/db/${PRODNAME}_db_dashboard_presets.sql" >> "$product_log" 2>&1 || die "$inten"
}

db_init_updater_state()
{
	local disable_updater="false"
	$mysql <<EOF || die "init updater state"
		REPLACE INTO misc(param, val) VALUES('disable_updater', '$disable_updater');
EOF
}

db_init_updater_state_conditionally()
{
	local disable_updater="false"
	db_do_if_not "SELECT * FROM misc WHERE param = 'disable_updater'" 1 		"INSERT INTO misc(param, val) VALUES('disable_updater', '$disable_updater');"
}

set_db_version()
{
	#install db version
	echo_try "set psa database version to $product_db_version"
	db_do "replace into misc (param,val) values('version', '$product_db_version')"
}

configure_mysql_innodb()
{
	local my_cnf awk_script
	my_cnf=$1

	if ! $mysql_client --version | grep -q '3\.23'; then
		return
	fi

	if ! (test -f $my_cnf && grep -q '^\[mysqld\]' "$my_cnf"); then
		echo "[mysqld]" >> $my_cnf
		echo "innodb_data_file_path=ibdata1:10M:autoextend" >> $my_cnf
		echo "safe-show-database" >> $my_cnf
		return
	fi

	awk_script='/^\[mysqld\]$/{print; print "innodb_data_file_path=ibdata1:10M:autoextend"; next;} {print}'
	if ! grep -q '^innodb_data_file_path' "$my_cnf"; then
		awk "$awk_script" "$my_cnf" >"$my_cnf.tmp" && mv "$my_cnf.tmp" "$my_cnf" || die "edit $my_cnf"
	fi

	awk_script='/^\[mysqld\]$/{print; print "safe-show-database"; next;} {print}'
	if ! grep -q '^safe-show-database' "$my_cnf"; then
		awk "$awk_script" "$my_cnf" >"$my_cnf.tmp" && mv "$my_cnf.tmp" "$my_cnf" || die "edit $my_cnf"
	fi
}

#bug #46837. Disable "LOAD DATA LOCAL INFILE" command.
configure_mysql_infile()
{
	local my_cnf awk_script sys
	my_cnf=$1

	if ! (test -f $my_cnf && grep -q '^\[mysqld\]' "$my_cnf"); then
		echo "[mysqld]" >> $my_cnf
		echo "local-infile=0" >> $my_cnf
		return
	fi

	awk_script='/^\[mysqld\]$/{print; print "local-infile=0"; next;} {print}'
	if ! grep -q '^local-infile' "$my_cnf"; then
		awk "$awk_script" "$my_cnf" >"$my_cnf.tmp" && mv "$my_cnf.tmp" "$my_cnf" || die "edit $my_cnf"
	fi
}

configure_mysql_nonlocal()
{
	local my_cnf
	my_cnf=$1

	if grep -q '^bind-address' "$my_cnf"; then
		sed -e "s|^\(bind-address[[:space:]]*=[[:space:]]*127\.0\.0\.1.*\)|# \1|g" 			"$my_cnf" >"$my_cnf.tmp" && mv "$my_cnf.tmp" "$my_cnf" || die "edit $my_cnf"
	fi
}

configure_mysql_disable_old_passwords()
{
	local my_cnf="$1"
	local awk_script='/^[[:space:]]*old_passwords/ { print "# Forced OLD_PASSWORD format is turned OFF by Plesk\n#" $0; next } { print }'

	mysql_disable_old_passwords_conf_changed=0
	if awk "$awk_script" "$my_cnf" > "$my_cnf.tmp" || die "edit $my_cnf"; then
		if diff -q "$my_cnf" "$my_cnf.tmp" 1>/dev/null ; then
			rm -f "$my_cnf.tmp"
		else
			mysql_disable_old_passwords_conf_changed=1
			mv "$my_cnf.tmp" "$my_cnf" || die "disable old_passwords in $my_cnf"
		fi
	fi
}

add_pid_file_to_mysql()
{
	local cfg=/etc/init/mysql.conf

	[ -e "$cfg" ] || return

	if ! grep -q -- '--pid-file' /etc/init/mysql.conf; then
		sed -e "s,^exec[[:space:]]/usr/sbin/mysqld,exec /usr/sbin/mysqld --pid-file=/var/run/mysqld/mysqld.pid,g" "$cfg" >"$cfg.tmp" && mv "$cfg.tmp" "$cfg"
		service mysql stop # Unfortunately restart will not help 
		service mysql start
	fi
	:
}

run_configure_mysql_funcs()
{
	local funcs="$@"
	local cnf_files="/etc/my.cnf /etc/mysql/my.cnf /var/db/mysql/my.cnf"

	for my_cnf in $cnf_files; do
		if [ -f ${my_cnf} ]; then
			break
		fi
	done

	for func in $funcs; do
		eval "$func $my_cnf"
	done

	return 0
}

mysql_install_init()
{
	cnf_files="/etc/my.cnf /etc/mysql/my.cnf /var/db/mysql/my.cnf"

	for my_cnf in $cnf_files; do
		if [ -f ${my_cnf} ]; then
			break
		fi
	done

	#Bug #117044. 
	dir="`echo $my_cnf | sed -e 's|\(.*\)\/.*|\1|g'`"
	if [ ! -d $dir ]; then
	    mkdir -p $dir 
	    chown ${mysql_user}:${mysql_group} $dir
	    chmod 755 $dir
	fi

	configure_mysql_innodb "$my_cnf"
	configure_mysql_infile "$my_cnf"
	configure_mysql_nonlocal "$my_cnf"
	configure_mysql_disable_old_passwords "$my_cnf"


	product_install_db
	update_mysql4_permissions
	mysql_fix_remove_empty_users
	tune_vz_mysql "$my_cnf"
	pleskrc mysql restart
}

mysql_fix_remove_empty_users()
{
	db_do "DELETE FROM mysql.user WHERE user = ''; FLUSH PRIVILEGES;"
}

dump_db()
{
	${MYSQL_BIN_D}/mysqldump $mysql_user $mysql_passwd --quote-names --databases $*
}
# -- start of mysqlnd old passwords upgrade --

# The reason why this code is not in the db/upgrade_db_1100.sh file is the following:
# It turned out that during the upgrade from 8.6 to 11.0 sw-engine may be installed to
# satisfy bootstrapper's dependency; new sw-engine with the mysqlnd extenstion refused to work 
# with the passwords in the old format. So passwords upgrade should be done prior the the database upgrade.
# This is vital as there are PHP-scripts (working with the database) invoked during the upgrade.

upgrade_mysqlnd_old_passwd()
{
	# It's probably better to extract all child functions into .in file
	run_configure_mysql_funcs configure_mysql_disable_old_passwords
	if [ "$mysql_disable_old_passwords_conf_changed" = "1" ]; then
		pleskrc mysql restart
	fi

	db_test "SELECT length(PASSWORD('test'))" '$1 == 41' || die "disable old_passwords=1 in my.cnf"
	check_mysql_users_with_old_passwd_format || return 0

	inten="upgrade MySQL password format"
	reset_admin_passwd || die "$inten for admin"
	reset_sitebuilder_passwd || die "$inten for Sitebuilder user"
	reset_billing_passwd || die "$inten for Billing user"
	reset_apsc_passwd || die "$inten for APS controller user"
	reset_horde_passwd || die "$inten for Horde webmail user"
	reset_atmail_passwd || die "$inten for AtMail webmail user"
	reset_mysql_dbusers_passwd || die "$inten for Panel DB users"
	reset_phpmyadmin_passwd || die "$inten for phpMyAdmin control user"
	reset_siteeditor_passwd || die "$inten for SiteEditor user"
	check_mysql_users_with_old_passwd_format && warn_mysql_old_passwd_users
}

check_mysql_users_with_old_passwd_format()
{
	local mysql_db_name=mysql
	db_test "SELECT User FROM user WHERE length(Password) != 41 LIMIT 1" '1'
}

reset_user_password()
{
	local user="$1"
	local passwd="$2"
	local host="${3:-localhost}"

	echo "SET PASSWORD FOR '$user'@'$host' = PASSWORD('$passwd')" | mysql_direct mysql || 
	[ "$host" = "127.0.0.1" -o "$host" = "::1" ] && host="localhost" && \
	echo "SET PASSWORD FOR '$user'@'$host' = PASSWORD('$passwd')" | mysql_direct mysql ||
	echo "SET PASSWORD FOR '$user'@'%'     = PASSWORD('$passwd')" | mysql_direct mysql
}

is_local_mysql_instance()
{
	local host="$1"
	[ -z "$host" -o "$host" = "localhost" -o "$host" = "127.0.0.1" -o "$host" = "::1" ]
}

check_db_accessible()
{
	local mysql_db_name="$1"
	local mysql_user="--user=$2"
	local mysql_passwd="--password=$3"

	db_do --inten "check that DB $1 is accessible to user $2" ""
}

reset_sitebuilder_passwd()
{
	local sb_conf="/usr/local/sb/config"
	[ -f "$sb_conf" ] || return 0

	local sb_host=`    get_ini_conf_var "$sb_conf" "database" "host"`
	local sb_username=`get_ini_conf_var "$sb_conf" "database" "username"`
	local sb_password=`get_ini_conf_var "$sb_conf" "database" "password"`
	local sb_dbname=`  get_ini_conf_var "$sb_conf" "database" "dbname"`

	is_local_mysql_instance "$sb_host" || return 0

	reset_user_password "$sb_username" "$sb_password" "$sb_host" && \
	check_db_accessible "$sb_dbname" "$sb_username" "$sb_password"
}

reset_billing_passwd()
{
	local billing_db_bin="/usr/share/plesk-billing/billing-db"
	local bil_host bil_user bil_passwd bil_dbname bil_mysql_local bil_info

	[ -x "$billing_db_bin" ] || return 0
	bil_mysql_local=`$billing_db_bin --is-local 2>/dev/null`
	if [ "$?" -eq 0 ]; then
		# New billing-db version is shell-friendly
		bil_dbname=`$billing_db_bin --get name`
		bil_user=`  $billing_db_bin --get user`
		bil_host=`  $billing_db_bin --get host`
	else
		# Slightly older ones provide --info option
		bil_info=`$billing_db_bin --info 2>/dev/null`
		if [ "$?" -eq 0 ]; then
			bil_dbname=`echo "$bil_info" | sed -ne 's/Database Name:\s*\(.*\)/\1/p'`
			bil_user=`  echo "$bil_info" | sed -ne 's/Database User:\s*\(.*\)/\1/p'`
			bil_host=`  echo "$bil_info" | sed -ne 's/Database Hostname:\s*\(.*\)/\1/p'`
			bil_mysql_local=
		fi
	fi
	if [ -z "$bil_dbname" -o -z "$bil_user" ]; then
		# And finally, if invoked w/o arguments, billing-db switches into MySQL prompt
		bil_info=`echo 'select database() \G select current_user() \G' | $billing_db_bin`
		[ "$?" -eq 0 ] || return 1
		local bil_auth=`echo "$bil_info" | sed -ne 's/current_user():\s*\(.*\)/\1/p'`
		bil_dbname=`    echo "$bil_info" | sed -ne 's/database():\s*\(.*\)/\1/p'`
		bil_user=`get_narg_fs "$bil_auth" '@' 1`
		bil_host=`get_narg_fs "$bil_auth" '@' 2`
		bil_mysql_local=
	fi
	bil_passwd=`get_random_string 12 'A-Za-z0-9_'`

	is_local_mysql_instance "$bil_host" || return 0
	[ -z "$bil_mysql_local" -o "$bil_mysql_local" = "yes" ] || return 0

	reset_user_password "$bil_user" "$bil_passwd" "$bil_host" && \
	$billing_db_bin --set --password "$bil_passwd" && \
	check_db_accessible "$bil_dbname" "$bil_user" "$bil_passwd" && 
	{
		$billing_db_bin --is-configured 2>/dev/null | grep -q yes || \
		$billing_db_bin --is_configured 2>/dev/null | grep -q yes 
	}
}

reset_apsc_passwd()
{
	check_apsc_installed || return 0
	read_apsc_connection_params_db

	is_local_mysql_instance "$apsc_db_host" || return 0

	reset_user_password "$apsc_db_user" "$apsc_db_passwd" "$apsc_db_host" && \
	check_db_accessible "$apsc_db_name" "$apsc_db_user" "$apsc_db_passwd"
}

get_webmail_config_param()
{
	local webmail_config="$1"
	local config_var="$2"
	local param="$3"
	local default_val="$4"
	local result=`sw_engine_pleskrun -n -r 'include "'$webmail_config'"; echo $'${config_var}${param}';' 2>/dev/null`
	[ -n "$result" ] || result="$default_val"
	echo "$result"
}

get_horde_config_param()
{
	get_webmail_config_param "/usr/share/psa-horde/config/conf.php" "conf" "$1" "$2"
}

get_atmail_config_param()
{
	get_webmail_config_param "/var/www/atmail/libs/Atmail/Config.php" "pref" "$1" "$2"
}

reset_horde_passwd()
{
	set_horde_params

	local horde_shadow="$horde_passwd_file"
	[ -f "$horde_shadow" ] || horde_shadow="/etc/psa/.webmail.shadow"
	local hor_host=`  get_horde_config_param "['sql']['hostspec']" "localhost"`
	local hor_user=`  get_horde_config_param "['sql']['username']" "horde"`
	local hor_dbname=`get_horde_config_param "['sql']['database']" "horde"`
	local hor_passwd=`get_horde_config_param "['sql']['password']"`
	[ -n "$hor_passwd" ] || hor_passwd=`cat "$horde_shadow" 2>/dev/null`
	[ -n "$hor_passwd" -a -n "$hor_user" -a -n "$hor_dbname" ] || return 0

	is_local_mysql_instance "$hor_host" || return 0

	reset_user_password "$hor_user" "$hor_passwd" "$hor_host" && \
	check_db_accessible "$hor_dbname" "$hor_user" "$hor_passwd"
}

reset_atmail_passwd()
{
	set_atmail_params

	local atmail_shadow="$atmail_passwd_file"
	local at_host=`  get_atmail_config_param "['sql_host']" "localhost"`
	local at_user=`  get_atmail_config_param "['sql_user']" "atmail"`
	local at_dbname=`get_atmail_config_param "['sql_table']" "atmail"`
	local at_passwd=`get_atmail_config_param "['sql_pass']"`
	[ -n "$at_passwd" ] || at_passwd=`cat "$atmail_shadow" 2>/dev/null`
	[ -n "$at_passwd" -a -n "$at_user" -a -n "$at_dbname" ] || return 0

	is_local_mysql_instance "$at_host" || return 0

	reset_user_password "$at_user" "$at_passwd" "$at_host" && \
	check_db_accessible "$at_dbname" "$at_user" "$at_passwd"
}

reset_mysql_dbusers_passwd()
{
	local mysql_db_name=mysql
	db_do --inten "Convert MySQL DB users passwords to new format" \
		"UPDATE mysql.user m 
				INNER JOIN psa.db_users u ON (m.User = u.login) 
				INNER JOIN psa.accounts a ON (u.account_id = a.id) 
				INNER JOIN psa.data_bases d ON (u.db_id = d.id) 
		SET m.Password = PASSWORD(a.password) 
		WHERE d.type = 'mysql' AND a.type = 'plain'; 
		FLUSH PRIVILEGES;"
}

reset_phpmyadmin_passwd()
{
	local pmahost="localhost"
	local controlpass pmadb
	set_phpmyadmin_params

	local pma_config="$PHPMYADMIN_CONFIG.save"
	[ -f "$pma_config" ] || pma_config="$PHPMYADMIN_CONFIG"
	pma__set_values_from_config "$pma_config" 'controluser' 'controlpass' 'pmadb'

	[ -n "$controlpass" -a -n "$controluser" -a -n "$pmadb" ] || return 0

	reset_user_password "$controluser" "$controlpass" "$pmahost" && \
	check_db_accessible "$pmadb" "$controluser" "$controlpass"
}

reset_siteeditor_passwd()
{
        local se_conf="/usr/local/siteeditor/config"
        [ -f "${se_conf}" ] || return 0

        local se_host=`get_ini_conf_var "${se_conf}" "database" "host"`
        local se_username=`get_ini_conf_var "${se_conf}" "database" "username"`
        local se_password=`get_ini_conf_var "${se_conf}" "database" "password"`
        local se_dbname=`  get_ini_conf_var "${se_conf}" "database" "dbname"`

        is_local_mysql_instance "$se_host" || return 0

        reset_user_password "${se_username}" "${se_password}" "${se_host}" && \
        check_db_accessible "$se_dbname" "$se_username" "$se_password"
}

warn_mysql_old_passwd_users()
{
	local mysql_db_name=mysql
	local query="SELECT concat(User, '@', Host) FROM user WHERE length(Password) != 41"

	if [ -n "$controluser" ]; then
		# There is an error in old phpMyAdmin upgrade routine: DB was recreated every time
		query="$query AND (User not like 'pma\_%' OR User = '$controluser')"
	fi

	query="$query AND (User != 'debian-sys-maint')"

	db_select "$query"
	local problem_users="$db_select_output"

	[ -n "$problem_users" ] || return 0
	report_problem "Passwords for some MySQL users were not upgraded." \
		"All MySQL DB users that may be used by Panel MUST have passwords in new 41-character format in order for Panel to function properly." \
		"Currently following users have passwords in old format: `echo -n $problem_users | sed -e 's/ /, /g'`." \
		"Please ensure that MySQL server is not forced to use old password hashing algorithm and upgrade password format manually for users from the list above. Consult with MySQL server manual on detailed steps." \
		"You may skip certain users if you are sure they weren't created and aren't used by Panel."
}

# -- end of mysqlnd old passwords upgrade --
#!/bin/sh

__tune_vz_mysql_sig_handler() {
    local rc=$?
    trap - EXIT
    rm -f -- "$1"
    exit $rc
}

__tune_vz_mysql()
{
    local myCnf myCnfTemp ||:

    myCnf=$1
    if test -z "$myCnf"; then
	warn "E:usage: $PROG /path/to/my.cnf"
	return 1
    fi

    if ! test -s "$myCnf" ; then
	warn "E: $myCnf doesn't exist or empty"
	return 100
    fi
    
    myCnfTemp=`mktemp ${myCnf}.XXXXXXX`
    if test $? -ne 0 ; then
	warn "E:Unable to create a temporary configuration file"
	return 2
    fi
    
    $cp_preserve $myCnf $myCnfTemp || {
	warn "E:Unable to create a temporary configuration file"
	return 2
    }

    trap "__tune_vz_mysql_sig_handler \"$myCnfTemp\""  HUP PIPE INT TERM EXIT

    local rc ||:

    local db_select_output
    db_select "SHOW VARIABLES LIKE 'have_innodb'"
    local have_innodb=`get_narg 2 ${db_select_output}`
    [ -n "$have_innodb" ] || have_innodb="NO"

    db_select "SHOW VARIABLES LIKE 'have_bdb'"
    local have_bdb=`get_narg 2 ${db_select_output}`
    [ -n "$have_bdb" ] || have_bdb="NO"

    cat "$myCnf" | gawk \
		-v have_innodb="${have_innodb}" \
		-v have_bdb="${have_bdb}" \
		'
function getsize(sizestr)
{
  if (match(sizestr, "[^[:digit:]]")) {
    size=substr(sizestr, 0, RSTART);
    mult=substr(sizestr, RSTART, 1);
    if ("K" == mult) {
      mult=1024;
    } else if ("M" == mult) {
      mult=1024*1024;
    } else if ("G" == mult) {
      mult=1024*1024*1024;
    }
    size = size * mult;
  } else {
    size = sizestr;
  }
  return size;
}

# add unspecified variables
function finalize_section()
{
  if (have_bdb && 0 == skipbdb) {
    printf("skip-bdb\n\n");
    changed=1;
  }
  if (have_innodb && 0 == ibp_size) {
    print "innodb_buffer_pool_size=2M"
    changed=1;
  }
  if (have_innodb && 0 == iamp_size) {
    print "innodb_additional_mem_pool_size=500K"
    changed=1;
  }
  if (have_innodb && 0 == ilb_size) {
    print "innodb_log_buffer_size=500K"
    changed=1;
  }
  if (have_innodb && 0 == thread_conc_set) {
    print "innodb_thread_concurrency=2"
    changed=1;
  }
}

# decrease value of "varname" if it exceed the upper bound limit.
# If value fit (less or equal), leave it unmodified.
function adjustSetting(varstr, varname, minsize, sizestr)
{
  if (match(varstr,"^[[:space:]]*(set-variable[[:space:]]*=[[:space:]]*)?" varname "[[:space:]]*=[[:space:]]*")) {
    if (have_innodb) {
      size = getsize(substr(varstr, RSTART+RLENGTH));
      if (minsize < size) {
        changed = 1;
        print "#", $0;
        print varname "=" sizestr;
      } else {
        print $0
      }
    } else {
      # we do not have innodb so we need to disable this setting
      print "#", $0;
      changed = 1;
    }
    return 1;
  }
  return 0;
}

function reset_variables()
{
  skipbdb=0;   # already have skip-bdb
  ibp_size=0;  # already set innodb_buffer_pool_size
  iamp_size=0; # already set innodb_additional_mem_pool_size
  ilb_size=0;  # already set innodb_log_buffer_size
  thread_conc_set=0; # -*- innodb_thread_concurrency
}

BEGIN {
  insect=0;    # within one of server sections
  changed=0;   # already changed smth
  have_bdb = (tolower(have_bdb) == "yes") ;
  have_innodb = (tolower(have_innodb) == "yes") ;
  reset_variables()
}
/^[[:space:]]*\[.+\]/ {
  if (0 != insect) {
# need to close a previous section
    finalize_section();
    # section is ended. Reset variables
    reset_variables()
    insect    = 0;
  }
  if ( match($0, "^[[:space:]]*\\[(mysqld|server|mysqld_safe|safe_mysqld)\\]")) {
    insect = 1;
#    print "# in server section";
  }
}

(match($0, "^[[:space:]]*(set-variable[[:space:]]*=)?[[:space:]]*") && 0 != insect) {
  varstr=substr($0, RSTART+RLENGTH);
  if (adjustSetting(varstr, "innodb_buffer_pool_size", 2 * 1024 * 1024, "2M")) { ibp_size=1; next; }
  if (adjustSetting(varstr, "innodb_additional_mem_pool_size", 500 * 1024, "500K")) { iamp_size=1; next; }
  if (adjustSetting(varstr, "innodb_log_buffer_size", 500 * 1024, "500K")) { ilb_size=1; next; }
  if (adjustSetting(varstr, "innodb_thread_concurrency", 2, "2")) { thread_conc_set=1; next; }
}

(adjustSetting($0, "innodb_buffer_pool_size", 2 * 1024 * 1024, "2M")) { ibp_size=1; next; }
(adjustSetting($0, "innodb_additional_mem_pool_size", 500 * 1024, "500K")) { iamp_size=1; next; }
(adjustSetting($0, "innodb_log_buffer_size", 500 * 1024, "500K")) { ilb_size=1; next; }
(adjustSetting($0, "innodb_thread_concurrency", 2, "2")) { thread_conc_set=1; next; }

/^[[:space:]]*skip-bdb[[:space:]]*(#.*)?$/ { skipbdb=1; }

{ print $0; }

END {
  if (0 != insect) {
    finalize_section();
  }

  if (0 == changed) {
    exit 110;
  }
}
' > "$myCnfTemp"
    rc=$?

    if test $rc -eq 110; then
	# nothing was changed
	p_echo "I: nothing to change in $myCnf"
	return 0
    fi

    if test $rc -ne 0; then
	warn "E: unable to process ${myCnf}: rc=$rc"
	return 2
    fi
    
    local myCnfBak ||:
    myCnfBak="${myCnf}.bak"

    if ! ln -f "$myCnf" "$myCnfBak" ; then
	warn "E: Unable to create a backup file"
	return 3
    fi

    if ! mv -f "$myCnfTemp" "$myCnf"; then
	warn "E: Unable to overwrite the configuration file"
	return 4
    fi
    
    trap - EXIT
    return 0
}

tune_vz_mysql()
{
    # check if we in VZ environment
    test "x$PLESK_VZ" = "x1" || return 0;
    # run in subshell to isolate TRAP usage
    ( __tune_vz_mysql "$1" )
}
#-*- vim:syntax=sh

set_named_params()
{
	# set up default values
	bind_UID=53
	bind_GID=53
	bind_user="named";
	bind_group="named";

	# get UID of named user, if exists
	get_userID $bind_user
	if [ $? -ne 0 ]; then
	    bind_UID=$common_var;
        fi

	# get GID of named group, if exists
	get_groupID $bind_group
	if [ $? -ne 0 ]; then
	    bind_GID=$common_var;
	fi

	# path to directory of internal named
	NAMED_ROOT_D="${PRODUCT_ROOT_D:?'PRODUCT_ROOT_D is undefined'}/named"

	# path to directory of named pid file
	bind_run="${NAMED_RUN_ROOT_D:?'NAMED_RUN_ROOT_D is undefined'}/var/run/named"

	named_service="named"
	named_log="/dev/null"
	
	# path to named config file
	named_conf="/etc/named.conf"
	rndc_conf="/etc/rndc.conf"
	rndc_namedb_conf="/etc/namedb/rndc.conf"
	rndc_bind_conf="/etc/bind/rndc.conf"
}

set_named_accounts()
{
      p_echo " Checking for the system groups and users necessary for named (bind)..."
      group_op "$bind_group" "$bind_GID" false
      user_op "$bind_user" "$bind_UID" "$bind_group" "Bind Sandbox" "$dummy_home" "$dummy_shell" false
}

set_named_perms()
{
	inten="set up default permissions"
	echo_try $inten

	# set up permissions of named files directory, if exists
	if [ -d $NAMED_ROOT_D ]; then
 		chown -R 0:0 "$NAMED_ROOT_D" >> "$product_log" 2>&1 || die $inten
		chmod -R 444 "$NAMED_ROOT_D" || die $inten
		chmod 555 "$NAMED_ROOT_D" "$NAMED_ROOT_D"/* >> "$product_log" 2>&1 || die $inten

		chmod 555 "$NAMED_ROOT_D"/bin/* >> "$product_log" 2>&1 || die $inten
		chmod 555 "$NAMED_ROOT_D"/include/*  >> "$product_log" 2>&1 || die $inten
		chmod 555 "$NAMED_ROOT_D"/man/* "$NAMED_ROOT_D"/sbin/* >> "$product_log" 2>&1 || die $inten
	fi

	# set up permissions of named run-root directory
	[ -d $bind_run ] || mkdir -p $bind_run
	chown -R $bind_user $bind_run >> "$product_log" 2>&1 || die $inten
	chmod 1755 $bind_run >> "$product_log" 2>&1 || die $inten

	chown ${bind_user}:${bind_group} "${NAMED_RUN_ROOT_D}/var" || die $inten
	chmod 755 "${NAMED_RUN_ROOT_D}/var" >> "$product_log" 2>&1 || die $inten
	chown ${bind_user}:${bind_group} "${NAMED_RUN_ROOT_D}/var/run" || die $inten
	chmod 755 "${NAMED_RUN_ROOT_D}/var/run" >> "$product_log" 2>&1 || die $inten

	suc
}

sysconfig_named_debian()
{
	local named_sysconf_file config_rebuild

	named_sysconf_file=/etc/default/bind9

	config_rebuild=0

	if [ -f "${named_sysconf_file}" ]; then

		# check presence of required run-root option
		cat ${named_sysconf_file} | sed -e 's|#.*$||g' | grep -E "^[[:space:]]*OPTIONS\=.*[[:space:]]\-t[[:space:]]*${NAMED_RUN_ROOT_D}" > /dev/null 2>&1
		[ $? -eq 0 ] || config_rebuild=1

		# check presence of required config file option
		cat ${named_sysconf_file} | sed -e 's|#.*$||g' | grep -E "^[[:space:]]*OPTIONS\=.*[[:space:]]\-c[[:space:]]*${named_conf}" > /dev/null 2>&1
		[ $? -eq 0 ] || config_rebuild=1

		# check presence of bind user option 
		cat ${named_sysconf_file} | sed -e 's|#.*$||g' | grep -E "^[[:space:]]*OPTIONS\=.*[[:space:]]\-u[[:space:]]*${bind_user}" > /dev/null 2>&1
		[ $? -eq 0 ] || config_rebuild=1

	else
		config_rebuild=1
	fi

	if [ 0${config_rebuild} -gt 0 ]; then

		[ ! -f ${named_sysconf_file} ] || mk_backup ${named_sysconf_file} mv f
		
		echo "OPTIONS=\"\${OPTIONS} -t ${NAMED_RUN_ROOT_D}  -c ${named_conf} -u ${bind_user}\"" > ${named_sysconf_file}
	fi
}

sysconfig_named_redhat()
{
	[ -d /etc/sysconfig ] || mkdir /etc/sysconfig

	local named_config="/etc/sysconfig/named"
	if [ -f "$named_config" ]; then
		rm -f $named_config.$product_suffo
		cp -fp $named_config $named_config.$product_suffo
	fi
	if [ "$bind_user" = "root" ]; then
		NAMED_START_AS_USER=""
	else
		NAMED_START_AS_USER="-u $bind_user"
	fi
	sed -e "s|##NAMED_RUN_ROOT_D##|$NAMED_RUN_ROOT_D|g" 		-e "s|##NAMED_START_AS_USER##|$NAMED_START_AS_USER|g" 		< "$PRODUCT_ETC_D/sysconfig.named.in" 		> "/etc/sysconfig/named"
}

sysconfig_named()
{

	# sysconfig_named not needed for SuSE
	return 0


	if [ "X$needed_to_restart_syslog" = "Xyes" ]; then
		[ -f /etc/rc.d/syslogd ] && /etc/rc.d/syslogd restart
	fi

	return 0
}


# own -> native transition is not assigned to specific Plesk version
# so we must handle here both the uprade from "own" and "native"
install_named_native()
{
	set_named_params

	pleskrc named stop

	named_conf_restore_system
	sysconfig_named
	named_conf_add_includes
	install_rndc_native
	if [ "$do_upgrade" != 1 ]; then
		"$UTILS_DIR/dnsmng" --dns-recursion localnets
	fi
}

install_rndc_native()
{
	# new rndc works ok without the config, only with /etc/rndc.key
	rm -f /etc/rndc.conf /etc/namedb/rndc.conf

	if [ "X$machine" = "XBSD" ]; then
	    if [ ! -f "/etc/namedb/rndc.key" ]; then
		/usr/sbin/rndc-confgen -a
	    fi
	fi
}

named_conf_restore_system()
{
	if [ "X$std_to_pkg" = "X1" ]; then
            #bug 120791
            cat /etc/rc.conf | awk '/named_chroot/{next;}{print;}' > /etc/rc.conf.tmp
            mv /etc/rc.conf.tmp /etc/rc.conf
            unlink /etc/namedb 2>/dev/null
            ln -s /var/named/etc/namedb /etc/namedb

	    if [ ! -f $named_conf -a -f /etc/named.conf ]; then
		cp -f /etc/named.conf $named_conf
		rm -f /etc/named.conf
	    fi
	fi 

	if ! [ -h "$named_conf" ] ; then
		return
	fi

	if [ "`readlink $named_conf`" != "$NAMED_RUN_ROOT_D""$named_conf" ]; then
		report_problem "$named_conf is a symlink to somewhere (`readlink $named_conf`) which is not a copy which Plesk used to create. Probably you have custom modifications in system configuration." 			"Installation will continue using this link."
		return
	fi

	echo_try "restore system bind9 configuration"

	# restore /etc/named.conf
	if [ -f "$named_conf"."$product_suffo" ]; then
		mv -f "$named_conf"."$product_suffo" "$named_conf" || die "restore named.conf"
	else
		report_problem "backup file $named_conf.$product_suffo not found." 			"A file which Plesk created will be used."
		cp -f `readlink $named_conf` "$named_conf"
		NAMED_CONF_NEEDS_CLEANUP=yes
	fi

	# remove links in the system's jail
	find /var/lib/named -type l | while read link; do
		dest=`readlink "$link"`
		case "$dest" in
		/*) rm "$link";;
		esac
	done
	# Bug 120818
	start_script="/etc/init.d/named"
	sed -e 's|localtime,rndc.key|localtime,named.conf,rndc.key|g' 		< "$start_script" > "$start_script.tmp" &&
		mv -f "$start_script.tmp" "$start_script" &&
		chmod 755 "$start_script"

	suc
}

named_conf_add_includes()
{
	touch "$NAMED_ZONES_CONF"
	label_file_once "${NAMED_ZONES_CONF}" "${AUTOGENERATED_CONFIGS}"

	touch "${NAMED_RUN_ROOT_D}/${NAMED_ZONES_CONF}"
	label_file_once "${NAMED_RUN_ROOT_D}/${NAMED_ZONES_CONF}" "${AUTOGENERATED_CONFIGS}"
	if ! grep -q 'include ".*named\.conf\.include.plesk-zones";$' "$named_conf"
	then
		echo "include \"$NAMED_ZONES_CONF\";" >>"$named_conf"
	fi

	touch "$NAMED_OPTIONS_CONF"
	touch "${NAMED_RUN_ROOT_D}/${NAMED_OPTIONS_CONF}"
	if ! grep -q 'include ".*named\.conf\.include.plesk-options"' "$named_conf"
	then
		awk -v NAMED_OPTIONS_CONF="$NAMED_OPTIONS_CONF" 			'{print} /^options {$/{print "include \"" NAMED_OPTIONS_CONF "\";";}' "$named_conf" 			> "$named_conf.tmp" 		&& mv "$named_conf.tmp" "$named_conf" 		|| die "add include clause to $named_conf:options"
	fi

# PCI-Compliance: hide native bind version
	if ! grep -q '^\s*version' "$NAMED_OPTIONS_CONF"; then
		echo 'version "none";' >> $NAMED_OPTIONS_CONF
	fi
}

configure_named_ipv6 ()
{
	realconf=`readlink $named_conf`
	if [ x"$realconf" = x"" ]; then
		realconf=$named_conf
	fi
        tmp_conf=`mktemp $realconf.XXXXXX`

        if [ -f /proc/net/if_inet6 ]; then
                listen_cmd='/options {/a		listen-on-v6 { any; };'
        else
                listen_cmd=""
        fi
        sed -e "/listen-on-v6/d" -e "$listen_cmd" $realconf > $tmp_conf
	chmod 644 $tmp_conf
        mv $tmp_conf $realconf
}

install_named()
{
	install_named_native
	
	label_file_once $named_conf "${AUTOGENERATED_CONFIGS}"
	pleskrc named stop
	configure_named_ipv6
	pleskrc named start
}

install_named_own()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		return 0;
	fi

	p_echo
	p_echo
	cd "$PRODUCT_ROOT_D" || die "cd $PRODUCT_ROOT_D"
	p_echo "===> Installing and configuring Named Server"
	p_echo

	set_named_params
	set_named_accounts

	get_pid named false
	old_named_pid=$common_var
	if [ $old_named_pid -gt 1 ]; then
		p_echo "Stop running named daemon"
		pleskrc named stop
	fi

	if [ ! -d "$NAMED_RUN_ROOT_D" ]; then

		inten="create named run-root directory"
		echo_try $inten
		mkdir -p "$NAMED_RUN_ROOT_D" && suc || die "$inten"

	fi

	# it is needed write localhost.rev?
	exclude_localhost_rev=
	if [ -f "$NAMED_RUN_ROOT_D/var/localhost.rev" ]; then
		exclude_localhost_rev="--exclude var/localhost.rev"
	fi

	inten="untar named run-root directory structure"
	echo_try $inten
	$tar xpf "$PRODUCT_ROOT_D/tmp/run-root.tar" -C "$NAMED_RUN_ROOT_D" $exclude_localhost_rev || die "$inten"
	(
		cd $NAMED_RUN_ROOT_D
		mkdir -m 755 -p dev

	   if [ "X$machine" = "XBSD" ]; then
			   #Ahtung!! mknod utility is deprecated for BSD systems
			   #Excluded from distributive at 7.x branch.
			   mknod dev/random c 1 8 root:wheel
			   mknod dev/urandom c 1 9 root:wheel
			   chmod 644 dev/random dev/urandom
	   else
			   mknod -m 644 dev/random c 1 8
			   mknod -m 644 dev/urandom c 1 9
			   chown root:root dev/random dev/urandom
	   fi

	) >>"$product_log" 2>&1
	selinux_relabel_dir -e "$NAMED_RUN_ROOT_D/proc" "$NAMED_RUN_ROOT_D"
	suc

	# cp named.conf if not exists or not contain string 'directory "/var";'
	grep_res=`egrep 'directory[[:space:]]*"/var";' "${NAMED_RUN_ROOT_D}${named_conf}" 2>/dev/null`
	if [ $? -ne 0 ]; then
		inten="create named.conf"
		echo_try "$inten"
		cp "${NAMED_RUN_ROOT_D}${named_conf}.default" "${NAMED_RUN_ROOT_D}${named_conf}" && suc || die "$inten"
	fi

	copy_named_localtime

	mk_backup "$named_conf" mv f

	ln -s "$NAMED_RUN_ROOT_D$named_conf" "$named_conf"

	if [ -d /etc/namedb ]; then
		mk_backup "$rndc_namedb_conf" mv f
		ln -s "$NAMED_RUN_ROOT_D$rndc_conf" "$rndc_namedb_conf"

		[ -d "$NAMED_RUN_ROOT_D/etc/namedb" ] || mkdir "$NAMED_RUN_ROOT_D/etc/namedb"

		[ "X$NAMED_RUN_ROOT_D$rndc_conf" != "X$NAMED_RUN_ROOT_D$rndc_namedb_conf" ] && 		    [ ! -f $NAMED_RUN_ROOT_D$rndc_namedb_conf ] && 		    ln -s "$NAMED_RUN_ROOT_D$rndc_conf" "$NAMED_RUN_ROOT_D$rndc_namedb_conf"
	fi

# make named startup script happy

	# Debian
	if [ -d /etc/bind ]; then
		mk_backup "$rndc_bind_conf" mv f
		ln -s "$NAMED_RUN_ROOT_D$rndc_conf" "$rndc_bind_conf"
		[ -d "$NAMED_RUN_ROOT_D/etc/bind" ] || mkdir "$NAMED_RUN_ROOT_D/etc/bind"
		ln -s "$NAMED_RUN_ROOT_D$rndc_conf" "$NAMED_RUN_ROOT_D$rndc_bind_conf"
		start_script="/etc/init.d/bind9"
		if [ -f $start_script ]; then
			# replace pidfile path to the one in chroot; ensure named is dead after 'rndc stop'
			# be carefull not to make replacements more than one time
			sed -e 's|/var/run/bind/run/named.pid|/var/named/run-root/var/run/named/named.pid|g' 				-e 's|\([^a-zA-Z0-9_.]\)/var/run/named/named.pid|\1/var/named/run-root/var/run/named/named.pid|g' 				-e '/killall\|rndc stop -p/!    s|\(/usr/sbin/rndc stop\)|\1 ; sleep 1 ; killall -9 named|g' 				-e '/killall/!                  s|\(/usr/sbin/rndc stop -p\s*\)| ( \1 ; sleep 1 ; killall -9 named ) 2>/dev/null |g' 				< "$start_script" > "$start_script.tmp" &&
			mv -f "$start_script.tmp" "$start_script" &&
			chmod 755 "$start_script"
		fi

	fi

	mk_backup "$rndc_conf" mv f
	ln -s "$NAMED_RUN_ROOT_D$rndc_conf" "$rndc_conf"


	#cd $NAMED_RUN_ROOT_D/var || die "cd $NAMED_RUN_ROOT_D/var"
	#sh make-localhost "$host" "$domain" "$fullhost" || die "sh make-localhost $host $domain $fullhost"

	set_named_perms

	sysconfig_named

	if [ "X$needed_to_restart_syslog" = "Xyes" ]; then
		[ -f /etc/rc.d/syslogd ] &&	/etc/rc.d/syslogd restart
	fi

	if [ "$do_upgrade" != 1 ]; then
		"$UTILS_DIR/dnsmng" --dns-recursion localnets
	fi

	add_manpath "$NAMED_ROOT_D/man"
}

copy_named_localtime()
{
	inten="copy localtime file to named sandbox"

	cp -f /etc/localtime "$NAMED_RUN_ROOT_D/etc/localtime"
	chown -R 0:0 "$NAMED_RUN_ROOT_D/etc/localtime" >> "$product_log" 2>&1 || die $inten
	chmod -R 444 "$NAMED_RUN_ROOT_D/etc/localtime" || die $inten
}

named_writeconf()
{
	pleskrc named stop

	if [ -n "$NAMED_CONF_NEEDS_CLEANUP" ]; then
		awk '
			BEGIN{
				brac_count = 0;
				match = 0;
			}
			brac_count == 0 && /\<acl [a-z_-]* \{$/ {
				match = 1;
			}
			brac_count == 1 && /\<allow-recursion \{$/ {
				match = 1;
			}
			brac_count == 0 && /\<zone "[^"]*"( in)? \{$/ 			&& ! /"(\.|localhost\.|0\.0\.127\.in-addr\.arpa)"/ {
				match = 1;
			}
			{
				brac_count = brac_count + count($0, "{") - count($0, "}");
				if (match == 1) {
					print "#", $0
				} else {
					print
				}
				if (brac_count == 0) match = 0;
			}
			function count(str, symbol,       pos) {
				pos = index(str, symbol);
				if (pos == 0) return 0;
				return count(substr(str, pos + 1), symbol) + 1;
			}
		' "$named_conf" >"$named_conf.tmp" 2>>"$product_log" 		&& mv -f "$named_conf.tmp" "$named_conf" >>"$product_log" 2>&1 		|| report_problem "remove Plesk related changes from named.conf"
	fi

	set_dns_recursion_in_config
	mysql_raw -e "select name from dns_zone" | while read domain; do
		"$UTILS_DIR/dnsmng" --update "$domain" --without-reverse
	done

	pleskrc named start
}

set_dns_recursion_in_config()
{
	db_select "select val from misc where param='dns_recursion'"
	dns_recursion="$db_select_output"
	if [ "any" = "$dns_recursion" -o "localnets" = "$dns_recursion" -o "localhost" = "$dns_recursion" ]; then
		"$UTILS_DIR/dnsmng" --dns-recursion $dns_recursion
	fi
}


named_status_linux_debian()
{
    get_pid "/usr/sbin/named" false
    local pid=$common_var
    if test "$pid" -ne 1; then
# running
		return 0
    fi
    return 1
}
#!/bin/sh

install_package()
{

    local pkgs="$1"
    local path="$2"

    echo_try "install package $1"

    if [ "X$path" = "X" ]; then
      path="/usr/local/psa/tmp/packages"
    fi
    
    if [ "X$pkgs" = "X" ]; then
       die "Unable determine package name for install."
    fi

    local package_name=`echo "$1" | sed -e 's|\(.*\)\(-.*\)|\1|'`
	local installed=`pkg_info | awk  '/^'$package_name'-[0-9]/{print $1}'`

    if [ "X$installed" = "X" ]; then
       pkg_add $path/$1*.t?z > /dev/null 2>> $product_log 
       if [ "$?" -eq "0" ]; then
          suc 
       else
          echo "failed" 
          die
       fi
    else 
       suc
       p_echo "Found $installed package, skipping installation"
    fi 


    return 0
}

install_external_packages()
{
        if [ $machine != "BSD" ]; then
                return
        fi

        cd "$PRODUCT_ROOT_D/$EXTERNAL_PACKAGES_DIR"
        if [ 0$? -ne 0 ]; then
                p_echo "Unable to change dir to $PRODUCT_ROOT_D/$EXTERNAL_PACKAGES_DIR"
                return
        fi

        for pkg_name in ${EXTERNAL_PACKAGES}; do
		install_package $pkg_name
        done

        #For backward compatibility with perl 5.8.5 on FreeBSD-5.3
        if [ "X$os_version" = "X5.3" ]; then
                inten="Making backward compatibility with perl 5.8.5"
                echo_try $inten
                [ -e "${PRODUCT_ROOT_D}/lib/perl5/5.8.7" ] && suc ||                     ln -s ${PRODUCT_ROOT_D}/lib/perl5/5.8.7 ${PRODUCT_ROOT_D}/lib/perl5/5.8.5 && suc || die
                [ -e "${PRODUCT_ROOT_D}/lib/perl5/site_perl/5.8.7" ] && suc || \ 
                    ln -s ${PRODUCT_ROOT_D}/lib/perl5/site_perl/5.8.7 ${PRODUCT_ROOT_D}/lib/perl5/site_perl/5.8.5 && suc || die
        fi
}

pam_params()
{
   local calltype
   calltype=$1
   initial_conf
   local product="psa"
   pam_config_dir="/usr/local/psa/pam_plesk_config"
   [ "x" = "x1" ] && pam_extra_args="-m /lib64/security/pam_plesk.so"
   if [ "x$calltype" != "x1" ]; then # install, not uninstall
       [ "x" = "x1" ] && pam_extra_args="$pam_extra_args --fixup-ftpd"
       [ "x" = "x1" ] && pam_extra_args="$pam_extra_args --fixup-des"
   fi
   pam_inst_script="pam_plesk_install"
   pam_uninst_script="pam_plesk_remove"

   return 0
}

install_pam()
{
  inten="install PAM module"
  pam_params
  echo_try "$inten"

  "$pam_config_dir/$pam_inst_script" -qq 	--install-log "$product_log" 	--problem-log "$product_problems_log" $pam_extra_args
 
  if [ "X$?" = "X0" ]; then
     suc
  else
     warn "install PAM module not successed" 
  fi

  return 0
}

uninstall_pam()
{
  inten="uninstall PAM module"
  echo_try

  pam_params 1 # 1 for uninstall
  "$pam_config_dir/$pam_uninst_script" -qq 	--install-log "$product_log" 	--problem-log "$product_problems_log" $pam_extra_args

  if [ "X$?" = "X0" ]; then
     suc
  else
     warn "uninstall PAM module not successed" 
  fi

}
set_perl_perms()
{
	inten="set up default perl permissions"
	echo_try $inten

	if [ -d ${PRODUCT_ROOT_D}/lib/perl5 ]; then

	    set_ac root 0 755 "${PRODUCT_ROOT_D}/lib/perl5"

		find "${PRODUCT_ROOT_D}/lib/perl5" -type d -print0 | xargs -0 chown root:0
		find "${PRODUCT_ROOT_D}/lib/perl5" -type d -print0 | xargs -0 chmod 755

		find "${PRODUCT_ROOT_D}/lib/perl5" -type f -print0 | xargs -0 chown root:0
		find "${PRODUCT_ROOT_D}/lib/perl5" -type f -print0 | xargs -0 chmod 644

		find "${PRODUCT_ROOT_D}/lib/perl5" -name '*.so*' -print0 | xargs -0 chown root:0
		find "${PRODUCT_ROOT_D}/lib/perl5" -name '*.so*' -print0 | xargs -0 chmod 555

	    if [ -d ${PRODUCT_ROOT_D}/lib/perl5/utils ]; then
		set_ac root 0 755 "${PRODUCT_ROOT_D}/lib/perl5/utils/*"
	    fi

	fi

	suc
}

install_perl()
{
	install_external_packages
}

phpmyadmin_config_backup()
{
	set_phpmyadmin_params
	[ -f "$PHPMYADMIN_CONFIG" ] && cp "$PHPMYADMIN_CONFIG" "$PHPMYADMIN_CONFIG.save"
}

install_phpmyadmin()
{
	p_echo "===> Installing phpMyAdmin"
	set_phpmyadmin_params
	rename_old_configs
	pma__configure
	suc
}

set_phpmyadmin_params()
{
	PHPMYADMIN_D="$PRODUCT_ROOT_D/admin/htdocs/domains/databases/phpMyAdmin"
	PHPMYADMIN_CONFIG="$PHPMYADMIN_D/libraries/config.default.php"
}

rename_old_configs()
{
	for i in $PHPMYADMIN_D/config.*; do
		[ -f "$i" -a "`echo $i | sed 's|config.sample.inc.php||'`" = "$i" ] && mv $i $i.old
	done;
}

pma__read_values_from_config_backup()
{
	if [ -f "$PHPMYADMIN_CONFIG.save" ]; then
		# looking for values of following variables in config.default.php.save
		pma__set_values_from_config "$PHPMYADMIN_CONFIG.save" 'controluser' 'controlpass' 'pmadb' 'bookmarktable' 'relation' 'table_info' 'table_coords' 'pdf_pages' 'column_info' 'history' 'designer_coords' 'tracking' 'userconfig' 'recent' 'table_uiprefs'
	fi
}

pma__write_values_to_config()
{
	# write new config.inc.php
	sed -e "`pma__sed_script`" < "$PHPMYADMIN_CONFIG.tpl" > "$PHPMYADMIN_CONFIG"
}

pma__configure()
{
	local controluser controlpass pmadb
	local bookmarktable column_info history pdf_pages relation table_coords table_info designer_coords tracking userconfig
	local recent table_uiprefs

	controluser=''

	pma__set_default_values
	pma__set_random_values
	pma__read_values_from_config_backup

	# Make sure that phpmyadmin script is idempotent, when phpmyadmin upgrade
	pma__create_pmadb

	pma__write_values_to_config
}

pma__set_values_from_config()
{
	eval `pma__read_values "$@"`
}

pma__read_values()
{
	local PHPMYADMIN_CONFIG="$1"
	shift

	[ -f $PHPMYADMIN_CONFIG ] && sw_engine_pleskrun -r '
			try {
				error_reporting(0);
				$GLOBALS["db_host"] = "localhost";
				class vz {
					public static function in_vzcp_proxy() { return false; }
				}
				function in_vzcp_proxy() { return false; }
				require_once("'$PHPMYADMIN_CONFIG'");
				for ($i = 1; $i < $argc; $i++)
					if (isset($cfg["Servers"][1][$argv[$i]]))
						echo $argv[$i] . "=\"" . $cfg["Servers"][1][$argv[$i]] . "\"\n";
			} catch (Exception $e) {}' -- "$@" 2>/dev/null || true
}

pma__set_default_values()
{
	controluser="pma"
#	controlpass=""

	pmadb="phpmyadmin"
	####
	# WARNING:
	# If you will modify the values you have to add templates (@@PMA_BOOKMARK@@, etc.)
	# in create_tables.sql and create_tables_mysql_4_1_2+.sql.
	####
	bookmarktable="pma_bookmark"
	column_info="pma_column_info"
	history="pma_history"
	pdf_pages="pma_pdf_pages"
	relation="pma_relation"
	table_coords="pma_table_coords"
	table_info="pma_table_info"
	designer_coords="pma_designer_coords"
	tracking="pma_tracking"
	userconfig="pma_userconfig"
	recent="pma_recent"
	table_uiprefs="pma_table_uiprefs"
}

pma__set_random_values()
{
	local pma__random_suffix

	# generate random controluser and pmadb
	while true; do
		pma__random_suffix=`get_random_string 12`
		controluser="pma_$pma__random_suffix" # maximum length is 16 characters
		pmadb="phpmyadmin_$pma__random_suffix"
		# check controluser existance
		# if user already exists then continue
		! db_test "SELECT COUNT(*) FROM mysql.user WHERE User='$controluser' LIMIT 1;" '$1!="0"' || continue
		# check pmadb existance
		# if db already exists then continue
		! db_test_database "$pmadb" || continue
		break
	done
	# generate random controlpass
	controlpass=`get_random_string 16`
}

pma__create_pmadb()
{
	local create_tables_sql
	local inten
	inten="create pmadb"
	echo_try $inten
	create_tables_sql="$PHPMYADMIN_D/examples/create_tables.sql"
	# create pmadb
	sed -e "`pma__sed_script`" < "$create_tables_sql" | mysql_direct >> "$product_log" 2>&1 || warn "$inten"
	suc
}

pma__sed_script()
{
	echo "\
	s/@@CONTROLUSER@@/$controluser/g
	s/@@CONTROLPASS@@/$controlpass/g
	s/@@PMADB@@/$pmadb/g
	s/@@PMA_BOOKMARK@@/$bookmarktable/g
	s/@@PMA_COLUMN_INFO@@/$column_info/g
	s/@@PMA_HISTORY@@/$history/g
	s/@@PMA_PDF_PAGES@@/$pdf_pages/g
	s/@@PMA_RELATION@@/$relation/g
	s/@@PMA_TABLE_COORDS@@/$table_coords/g
	s/@@PMA_TABLE_INFO@@/$table_info/g
	s/@@PMA_DESIGNER_COORDS@@/$designer_coords/g
	s/@@PMA_TRACKING@@/$tracking/g
	s/@@PMA_USERCONFIG@@/$userconfig/g
	s/@@PMA_RECENT@@/$recent/g
	s/@@PMA_TABLE_UIPREFS@@/$table_uiprefs/g
	"
}

poppassd_super_server_config()
{
	local action="$1"

	if [ -f /proc/net/if_inet6 ]; then 
		FLAGS="flags                   = KEEPALIVE IPv6"
	else
		FLAGS="flags                   = KEEPALIVE"
	fi

	case "$superserver" in
	    inetd)
		poppassd_rec="poppassd stream tcp nowait/1000 root /usr/sbin/tcpd $PRODUCT_ROOT_D/admin/sbin/poppassd"
		;;	
	    xinetd)
		poppassd_rec="service poppassd
{
socket_type             = stream
protocol                = tcp
port                    = 106
wait                    = no
disable                 = no
user                    = root
instances               = 1000
$FLAGS
server                  = $PRODUCT_ROOT_D/admin/sbin/poppassd
}"
		;;
	    *)
		    die "Super server name unknown"
		;;
	esac

	super_server_action "$action" poppassd "$poppassd_rec"
}

install_poppassd()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then 
		return 0;
	fi

	case "${machine}_$linux_distr" in
		BSD*)
			add_service2etc_services 'poppassd' 106 'tcp'
			;;
		linux_suse*)
			add_service2etc_services 'poppassd' 106 'tcp'
			;;
		*) ;;
	esac

        set_super_server_params
	poppassd_super_server_config register
}
set_pgsql_params()
{
    pgsql_user="postgres"
    pgsql_group="postgres"
    pgsql_user_old=`cat /etc/passwd | awk -F ':' '        BEGIN { p = 3 };        p > 1 && /^postgres/ { p = 1; s = $1 };        p > 2 && /^pgsql/    { p = 2; s = $1 };        END { print s }        '`

    start_script="postgresql"
    PGSQL_ROOT_D="/usr"
    PGSQL_DATA_D="/var/lib/pgsql/data"
    NEW_PGSQL_VERSION=""

    if [ -x "$PRODUCT_RC_D/$start_script" ]; then
	RC_SCRIPT="$PRODUCT_RC_D/$start_script"
    elif [ -x "$PRODUCT_RC_D/${start_script}.sh" ]; then
	RC_SCRIPT="$PRODUCT_RC_D/${start_script}.sh"
    else
	die "Unable to find postgresql startup script"
    fi

    PGSQL_BIN_D="$PGSQL_ROOT_D/bin"
    PGSQL_BACKUP_D="$PRODUCT_ROOT_D/tmp/postgresql.upgradedb"
}

set_pgsql_accounts()
{
    if [ "X${pgsql_user}" != "X" -a "X${pgsql_group}" != "X" ]; then
        p_echo " Checking for the system groups and users necessary for PostgreSQL..."
        group_op "$pgsql_group" "search" false

        # postgresql utilities are required the postgres user to have shell
        user_op "$pgsql_user" "search" "$pgsql_group" "PostgreSQL Server" "/" "/bin/sh" false
    fi
}

set_pgsql_perms()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		return 0;
	fi

	inten="set up default postgresql permissions"
	echo_try $inten

	# set permissions to postgres root directory
	set_ac root 0 755 "$PGSQL_ROOT_D" || die $inten

	# set default permissions to postgres subdirectories
	chown 0:0 "${PGSQL_ROOT_D}"/* || die $inten
	chmod 755 "${PGSQL_ROOT_D}"/* || die $inten

	# postgres data directory has diffreent permissions
	set_ac ${pgsql_user} 0 700 "${PGSQL_DATA_D}" || die $inten
	chown -R "$pgsql_user:0" "$PGSQL_DATA_D" || die "$inten"

	# set permissions to postgres utilities
	chown -h root:0 "${PGSQL_BIN_D}"/* || die $inten
	chmod 755 "${PGSQL_BIN_D}"/* || die $inten

	# set permissions to postgres libraries
	if [ -d "$PGSQL_ROOT_D/lib" ]; then
		find "$PGSQL_ROOT_D/lib" -name '*.so*' -print0 | xargs -0 chown -h root:0
		find "$PGSQL_ROOT_D/lib" -name '*.so*' -print0 | xargs -0 chmod 555

		find "$PGSQL_ROOT_D/lib" -name '*.la' -print0 | xargs -0 chown root:0
		find "$PGSQL_ROOT_D/lib" -name '*.la' -print0 | xargs -0 chmod 555

		find "$PGSQL_ROOT_D/lib" -name '*.a' -print0 | xargs -0 chown root:0
		find "$PGSQL_ROOT_D/lib" -name '*.a' -print0 | xargs -0 chmod 444
	fi

	# set permissions to postgres headers
	find "$PGSQL_ROOT_D/include" -type d -print0 | xargs -0 chown root:0
	find "$PGSQL_ROOT_D/include" -type d -print0 | xargs -0 chmod 555

	find "$PGSQL_ROOT_D/include" -type f -print0 | xargs -0 chown root:0
	find "$PGSQL_ROOT_D/include" -type f -print0 | xargs -0 chmod 444

	# set permissions to postgres manuals
	find "$PGSQL_ROOT_D/man" -type d -print0 | xargs -0 chown root:0
	find "$PGSQL_ROOT_D/man" -type d -print0 | xargs -0 chmod 555

	find "$PGSQL_ROOT_D/man" -type f -print0 | xargs -0 chown root:0
	find "$PGSQL_ROOT_D/man" -type f -print0 | xargs -0 chmod 444

	# set permissions to postgres share directory
	find "$PGSQL_ROOT_D/share" -type d -print0 | xargs -0 chown root:0
	find "$PGSQL_ROOT_D/share" -type d -print0 | xargs -0 chmod 555

	find "$PGSQL_ROOT_D/share" -type f -print0 | xargs -0 chown root:0
	find "$PGSQL_ROOT_D/share" -type f -print0 | xargs -0 chmod 444

	suc

	return 0
}

need_upgrade()
{
	if [ "X$do_upgrade" = "X1" ]; then 
        if [ -z "$pgsql_user_old" ]; then
                NEED_UPGRADE="NO"
                die "postgresql upgrade preparing: unable to detect postgresql user in /etc/passwd file"
        fi
		check_pgsql_version

		if [ "X$NEED_UPGRADE" = "XYES" ]; then
			 return 0
		fi
	else
		return 1
	fi

	[ -d "X$PGSQL_ROOT_D" ] || return 1

	return 0
}

install_pgsql_std()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		return 0;
	fi

	set_pgsql_params
	set_pgsql_accounts

	# postgres database initialisation is required for installation only
	if [ "X${do_upgrade}" != "X1" ]; then
		inten="installing postgresql server"
		echo_try $inten
		
		set_pgsql_perms
		create_new_pgdata_dir

		# all was commenting
		cp "${PGSQL_DATA_D}/pg_hba.conf" "${PGSQL_DATA_D}/pg_hba.conf.def"
		cat "${PGSQL_DATA_D}/pg_hba.conf.def" | sed -e 's/^\([^#].*\)/#\1/' > "${PGSQL_DATA_D}/pg_hba.conf"
		chown "${pgsql_user}:0" "${PGSQL_DATA_D}/pg_hba.conf" "${PGSQL_DATA_D}/pg_hba.conf.def"
		chmod 600 "${PGSQL_DATA_D}/pg_hba.conf" "${PGSQL_DATA_D}/pg_hba.conf.def"

		suc
	fi
}
check_pgsql_version()
{
	p_echo "Checking postgresql version ..."

	PG_BIN_VERSION=`su -l $pgsql_user_old -c "$PGSQL_BIN_D/pg_ctl --version" | sed -e 's/^.*\([0-9]\.[0-9]\)\.[0-9]$/\1/'`
	if [ -z "$PG_BIN_VERSION" ]; then
		die "postgresql upgrade preparing: unable to detect version of old postgresql"
	fi

	PG_DATA_VERSION=`cat $PGSQL_DATA_D/PG_VERSION | sed -e 's/^.*\([0-9]\.[0-9]\)\.[0-9]$/\1/'`
	if [ -z "$PG_DATA_VERSION" ]; then
		die "postgresql upgrade preparing: unable to detect version of postgres data dir"
	fi

	if [ "X$PG_BIN_VERSION" != "X$PG_DATA_VERSION" -a "X$std_to_pkg" != "X1" ]; then
		p_echo "postgresql upgrade preparing: you have PGDATA and postgresql with different versions(PGDATA:$PG_DATA_VERSION!=PGSQL:$PG_BIN_VERSION)"
		#die "postgresql versions inconsistent"
	elif [ "X$PGSQL_VERSION" != "X$NEW_PGSQL_VERSION" -o "X$std_to_pkg" = "X1" ]; then
		NEED_UPGRADE="YES"
	fi

	p_echo "done"
	PGSQL_VERSION=$PG_DATA_VERSION
}

postgresql_rc()
{
        ACTION=$1

        echo_try "$ACTION postgresql server"
        sh $RC_SCRIPT $ACTION >> $product_log 2>&1
        sleep 3
        if [ "X$ACTION" = "Xstop" ]; then
                killall postmaster >> $product_log 2>&1
                sleep 1
                killall -9 postmaster >> $product_log 2>&1
        fi

        suc
}

set_trust_permission_format()
{
	pgsql_ver=$1
	case $pgsql_ver in
		7.2)
			PGUSER_PERMS_STR='local\tall\t\t\ttrust'
			;;
		7.3|7.4*|8*)
			PGUSER_PERMS_STR='local\tall\tall\t\t\ttrust'
			;;
		*)
			die "defining trust permissions format: unsupported for upgrading postgresql version"
			;;
	esac
}

add_pguser_perms()
{
	inten="add permissions for $pgsql_user"

	echo_try $inten

	cp -f $PGSQL_DATA_D/pg_hba.conf $PGSQL_DATA_D/pg_hba.conf.saved || error_exit
	cat $PGSQL_DATA_D/pg_hba.conf | 	awk '{ if (("#" != $1) && (first != 1)) {first=1; print "'$PGUSER_PERMS_STR'";} print $0;}' 		> $PGSQL_DATA_D/pg_hba.conf.tmp 	&& mv -f $PGSQL_DATA_D/pg_hba.conf.tmp $PGSQL_DATA_D/pg_hba.conf 	&& chmod 644 $PGSQL_DATA_D/pg_hba.conf || die $inten

	p_echo "done"
}

remove_pguser_perms()
{
	if [ ! -f $PGSQL_DATA_D/pg_hba.conf.saved ]; then
		return 
	fi

	echo_try "remove permissions for $pgsql_user_old ... "
	cp -f $PGSQL_DATA_D/pg_hba.conf.saved $PGSQL_DATA_D/pg_hba.conf || error_exit
	chmod 644 $PGSQL_DATA_D/pg_hba.conf || die $inten

	p_echo "done"
}

backup_all_pgsql_db()
{
    backup_all_pgsql_db_linux
}

restore_all_pgsql_db()
{
    restore_all_pgsql_db_linux
}

backup_all_pgsql_db_freebsd()
{
	echo_try "dumping all databases"
	echo ""

	postgresql_rc stop	
	add_pguser_perms
	postgresql_rc start

	p_echo
	echo_try "vacuuming"
	$PGSQL_BIN_D/vacuumdb -U$pgsql_user_old -a -z -q
	if [ $? -gt 0 ]; then
	    die "vacuuming"
	fi

	#Save all databases with globals. 
	#Using pg_dumpall from _NEW_ version postgres.
	#bug 106329
	file="${PGSQL_BACKUP_D}/pgdump_all"
	/usr/local/bin/pg_dumpall -U$pgsql_user_old | gzip -9 > ${file}.gz
	if [ 0$? -gt 0 ]; then
	    die "backing up all databases"
	fi

	postgresql_rc start
	remove_pguser_perms

	p_echo "done"
}

restore_all_pgsql_db_freebsd()
{
	echo_try "restoring all databases"

	postgresql_rc stop
	add_pguser_perms
	postgresql_rc start

	chown -R $pgsql_user $PGSQL_BACKUP_D

	file="$PGSQL_BACKUP_D/pgdump_all"
	gunzip -c $file.gz | psql -U$pgsql_user -d template1

	postgresql_rc stop
	remove_pguser_perms
	postgresql_rc start

	p_echo "done"
}

backup_all_pgsql_db_darwin()
{
	echo_try "dumping all databases"
	echo ""

	postgresql_rc stop	
	add_pguser_perms
	postgresql_rc start

	# Protect the data
	dbnames=`$PGSQL_BIN_D/psql -U$pgsql_user_old -q -t -A -d template1 -c "SELECT datname FROM pg_database WHERE datname != 'template0'"`
	if [ 0$? -gt 0 ]; then
	    die "database list fetching"
	fi

	#Save users and groups information only. Not databases.
	file="${PGSQL_BACKUP_D}/pgglobals"
	$PGSQL_BIN_D/pg_dumpall -U$pgsql_user_old -g | gzip -9 > ${file}.gz
	if [ 0$? -gt 0 ]; then
	    die "backing up of global objects"
	fi

	#Save databases only. 
	for db in ${dbnames}; do
	    p_echo -n " $db"
	    file=${PGSQL_BACKUP_D}/pgdump_$db
	    $PGSQL_BIN_D/pg_dump -U$pgsql_user_old -b -F c -f $file "$db"
		if [ 0$? -gt 0 ]; then
		    p_echo "Errors were reported during database '$db' backup"
		fi
	done

	p_echo
	echo_try "vacuuming"
	$PGSQL_BIN_D/vacuumdb -U$pgsql_user_old -a -z -q
	if [ $? -gt 0 ]; then
	    die "vacuuming"
	fi

	postgresql_rc start
	remove_pguser_perms

	p_echo "done"
}

restore_all_pgsql_db_darwin()
{
	echo_try "restoring all databases"

	postgresql_rc stop
	add_pguser_perms
	postgresql_rc start

	chown -R $pgsql_user $PGSQL_BACKUP_D

	file="$PGSQL_BACKUP_D/pgglobals"
#	gzip -d --to-stdout $file.gz | $PGSQL_BIN_D/pg_restore -U$pgsql_user -F c -d template1
	gzip -d --to-stdout $file.gz | $PGSQL_BIN_D/psql -U$pgsql_user -d template1

	tmpl1=1
	for file in $PGSQL_BACKUP_D/pgdump_template1 `ls $PGSQL_BACKUP_D/pgdump_*`; do
		db=`basename $file | awk -F '_' '{print $2}'`
		if [ 0$tmpl1 -le 0 -o "X$db" != "Xtemplate1" ]; then
			$PGSQL_BIN_D/psql -U$pgsql_user -c "CREATE DATABASE \"$db\"" template1
			$PGSQL_BIN_D/pg_restore -U$pgsql_user -F c -d "$db" $file
		fi
		if [ "X$db" = "Xtemplate1" ]; then
			tmpl1=1
		fi
	done

	postgresql_rc stop
	remove_pguser_perms
	postgresql_rc start

	p_echo "done"
}

backup_pgsql_dbusers_files()
{
	### copy users list files
	mkdir -p $PGSQL_BACKUP_D/users
	cp -f $PGSQL_DATA_D/usrs_* $PGSQL_BACKUP_D/users/ || true
	cp -f $PGSQL_DATA_D/pg_hba.conf $PGSQL_BACKUP_D/users/
}

restore_pgsql_dbusers_files()
{
	### copy users list files
	cp -f $PGSQL_BACKUP_D/users/usrs_* $PGSQL_DATA_D/

	################################################
	## Converting pg_hba.conf
	################################################
	src_pg_hba=$PGSQL_BACKUP_D/pg_hba.conf
	dst_pg_hba=$PGSQL_DATA_D/pg_hba.conf

	cp -f $dst_pg_hba $dst_pg_hba.saved
	mv -f $dst_pg_hba.saved $dst_pg_hba

	chmod 644 $dst_pg_hba 
}

backup_db_with_old_pgsql()
{
	need_upgrade || return 

	set_trust_permission_format $PGSQL_VERSION 

	OLD_PGSQL_VERSION=$PGSQL_VERSION

	if [ "X$std_to_pkg" != "X1" ]; then 
		[ -d $PGSQL_BACKUP_D ] && rm -rf $PGSQL_BACKUP_D
	fi

	mkdir -p $PGSQL_BACKUP_D || die "Unable to create $PGSQL_BACKUP_D"
	chown $pgsql_user $PGSQL_BACKUP_D
	chmod 660 $PGSQL_BACKUP_D

	backup_all_pgsql_db
	backup_pgsql_dbusers_files
}

move_old_datadir()
{
	[ -d "$PGSQL_DATA_D.old" ] || mv -f $PGSQL_DATA_D "$PGSQL_DATA_D.old"
}

create_new_pgdata_dir()
{
	inten="create a new PGDATA dir"
	echo_try "$inten"
	
	if [ ! -f $PGSQL_DATA_D/PG_VERSION ]; then
		if [ "X$machine" = "XBSD" ]; then
			[ -f $RC_SCRIPT ] && $RC_SCRIPT initdb || die "$inten"
		else
			chown $pgsql_user:0 $PGSQL_DATA_D
			su $pgsql_user -c "${PGSQL_BIN_D}/initdb -D ${PGSQL_DATA_D}" >> "$product_log" 2>&1 || die $inten
		fi
	fi

	suc
}

restore_db_with_new_pgsql()
{
	need_upgrade || return 

	set_trust_permission_format $NEW_PGSQL_VERSION

	if [ ! -d $PGSQL_BACKUP_D ]; then
		p_echo "Unable to upgrade postgresql: backup directory $PGSQL_BACKUP_D is not exist"
		return 0
	fi

	if [ "X$std_to_pkg" != "X1" ]; then
		move_old_datadir
	fi

	create_new_pgdata_dir

	restore_all_pgsql_db
	restore_pgsql_dbusers_files

#	p_echo "Do not forget remove old databases dir $PGSQL_BACKUP_D"
	[ -d $PGSQL_BACKUP_D ]  || rm -rf $PGSQL_BACKUP_D || p_echo "Unable to remove $PGSQL_BACKUP_D"
}


# vim:syntax=sh

mail_restore_all()
{
	# temporary solution to close #143977 and #144076: three keys to turn on
	if [ ! -e "$PRODUCT_ROOT_D/version" -a ! -e "$PRODUCT_ROOT_D/core.version" ]; then
		p_echo "$PRODUCT_ROOT_D/version isn't yet on its place. Deferring mail_restore execution to a later stage" >&2
		return
	fi
	if [ ! -x "/usr/lib64/plesk-9.0/mailsrv_entities_dump" ]; then
		p_echo "/usr/lib64/plesk-9.0/mailsrv_entities_dump isn't yet on its place. Deferring mail_restore execution to a later stage" >&2
		return
	fi
	if [ ! -x "/usr/lib64/plesk-9.0/mail_restore" ]; then
		p_echo "/usr/lib64/plesk-9.0/mail_restore isn't yet on its place. Deferring mail_restore execution to a later stage" >&2
		return
	fi

	# FIXME: There's a possible race during upgrade procedure. Noone
	# managed to catch the bug in debug mode, so be stupid:
	sync; sync; sleep 3

	inten="executing mail_restore to synchronize mail server settings and Plesk Database"
	echo_try $inten
	/usr/lib64/plesk-9.0/mail_restore --fast >>$product_log 2>&1
	suc
}
	
mail_init_conf()
{
	/usr/lib64/plesk-9.0/mailsrv_conf_init >>"$product_log" 2>&1
	if [ -x /sbin/restorecon ]; then
		/sbin/restorecon /etc/aliases.db
	fi
	# if Mailman is installed, adapt its configs for QMail
	if [ -f "/usr/lib/mailman/Mailman/mm_cfg.py" ]; then
		/usr/lib64/plesk-9.0/mailman_conf_init "/usr/lib/mailman/Mailman/mm_cfg.py" ||:
	fi
}


exim_status_linux_debian()
{
	get_pid /usr/lib/exim/exim3 false
	local pid=$common_var

	if test "$pid" -ne 1; then
		#running
		return 0;
	fi
	return 1
}

# this fucntion designed for use on Debian-based systems only.
# this restriction comes from using extended mode of GNU sed.
disable_inetd_mail()
{
	return 0
}

disable_foreign_mtas()
{
	[ -n "$1" ] || simply_die "No MTA to disable"

	for mta in $@; do
		if [ "$mta" = "qmail" ]; then
# disable_qmail work only on superserver part
			disable_qmail
		fi

		if pleskrc $mta exists; then
			pleskrc $mta stop
			unregister_service $mta
		fi

# Special code for sendmail
		if [ "$mta" = "sendmail" ]; then
# Bugs 146251, 146486  sendmail is not properly stopped by its own script
			remove_sendmail
			:
		fi # sendmail
done
}

install_postfix_smtpd_sasl_config()
{
	local smtpd_sasl_conf smtpd_sasl_conf_bak saslauthd_path saslauthd_path_relative

	saslauthd_path_relative=/private/plesk_saslauthd

	saslauthd_path=/var/spool/postfix${saslauthd_path_relative}
	
	smtpd_sasl_conf='/etc/sasl2/smtpd.conf'

	if [ -f "$smtpd_sasl_conf" ]; then
	   smtpd_sasl_conf_bak="${smtpd_sasl_conf}.saved_by_plesk.`date +%s`"
	   rm -f "$smtpd_sasl_conf_bak" ||:
	   if ! ln "$smtpd_sasl_conf" "$smtpd_sasl_conf_bak" ; then
	      simply_die "unable to preserve $smtpd_sasl_conf to $smtpd_sasl_conf_bak"
	   fi
	fi
	mkdir -p "$(dirname $smtpd_sasl_conf)"
	cat >"$smtpd_sasl_conf" <<EOF
pwcheck_method: auxprop saslauthd
auxprop_plugin: plesk
saslauthd_path: $saslauthd_path
mech_list: DIGEST-MD5 CRAM-MD5 PLAIN LOGIN
auto_transition: yes
sql_engine: intentionally disabled
log_level: 4
EOF
}

qmail_admin_alias()
{
	local userdata="`getent passwd $1`"
	local uid="`echo $userdata | awk -F':' '{print $3}'`"
	local gid="`echo $userdata | awk -F':' '{print $4}'`"
	local home="`echo $userdata | awk -F':' '{print $6}'`"

	if [ -z "$uid" -o -z "$gid" -o ! -d "$home" ]; then
		report_problem "Userinfo for $1 is incomplete. Qmail alias for this user will not be created" 			"Manually create .qmail file in $1 home directory"
		return 1
	fi

	[ ! -s "$home/.qmail" ] || return
	echo "&root" > "$home/.qmail"
	chmod 0600 "$home/.qmail"
	chown $uid:$gid "$home/.qmail"
}

set_postfix_auth()
{
	local run="$PRODUCT_ROOT_D/admin/sbin/mailmng --set-mail-params"

	if db_test "SELECT val FROM misc WHERE param='relay' AND val='open'" 1 ; then
		run="$run --relayclient"
	fi

	if db_test "SELECT * FROM misc WHERE param='disable_smtp_auth' and val=0" 1 ; then
		run="$run --smtpauth"
	fi

	if db_test "SELECT * FROM misc WHERE param='disable_pop_auth' and val=0" 1 ; then
		run="$run --popauth"
	fi

	db_select "SELECT val FROM misc WHERE param='poplock_time'"
	if [ -n "$db_select_output" ]; then
		# this will also set correct crontab for poplock.db cleanup
		run="$run --poplock-time=$db_select_output"
	fi

	$run >> $product_log 2>&1
}

update_postfix_poplockdb_cleanup_crontab()
{
	[ -x "${PRODUCT_RC_D}/postfix" -a ! -f "${PRODUCT_RC_D}/qmail" ] || return 0
	set_postfix_auth
}


set_mail_params()
{
	HANDLERS_USER="mhandlers-user"
	MAIL_USERGROUP="popuser"
}

set_foreign_mtas_params()
{
	# need for pleskrc to work properly
	exim_service="exim"
	exim4_service="exim4"
	sendmail_service="sendmail"
}
## vim:filetype=sh

upgrade_dk_86()
{
	$PRODUCT_ROOT_D/admin/sbin/mailmng --remove-handler --handler-name='dd51-domainkeys' --handler-type='global' --hook='before-remote' >> "$product_log" 2>&1
	$PRODUCT_ROOT_D/admin/sbin/mailmng --remove-handler --handler-name='dd52-domainkeys' --handler-type='global' --hook='before-local' >> "$product_log" 2>&1
	/usr/lib64/plesk-9.0/mail_dk_restore
}
#-*- 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"


	[ -d "$PRODUCT_ROOT_D/var/log" ] || mkdir -p "$PRODUCT_ROOT_D/var/log"
	touch $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
}

#qmail

set_qmail_accounts()
{
	p_echo " Checking for the system groups and users necessary for Qmail..."
### Processing qmail groups
	for qgroup in ${QMAIL_GROUPS}; do
		local qgname=`get_narg_fs "$qgroup" ":" 1`
		local qgid=`get_narg_fs "$qgroup" ":" 2`
		if [ -z $qgname -o -z "$qgid" ]; then
			die "Empty group name or gid for name=$qgname, gid=$qgid"
		fi
		group_op "$qgname" "$qgid" true
	done
  
### Processing qmail groups
	for quser in ${QMAIL_USERS}; do
		local quname=`get_narg_fs "$quser" ":" 1`
		local quid=`get_narg_fs "$quser" ":" 2`
		local qgname=`get_narg_fs "$quser" ":" 3`
		local qforcedgid=`get_narg_fs "$quser" ":" 4`
		local qdir=`get_narg_fs "$quser" ":" 5`
		if [ -z $quname -o -z "$quid" ]; then
			die  "Empty user name or uid for name=$quname, gid=$quid"
		fi
		user_op "$quname" "$quid" "$qgname" "Qmail User" "$QMAIL_DIR/$qdir" "$dummy_shell" true $qforcedgid
    done
}

comment_out_comsat()
{

    if [ -f "$superserver_conf" ]; then
	mk_backup $superserver_conf cp f

	grep_res=`egrep '^comsat' $superserver_conf`
	inten="comment out comsat service record from $superserver_conf"
	echo_try $inten

	case "$grep_res" in
		comsat*)
			sed -e "s/^comsat/#comsat/g" < "$superserver_conf" > "$superserver_conf.${product}_tmp" || die
			mv -f "$superserver_conf.${product}_tmp" "$superserver_conf" && suc || die $inten
			;;
		*)
			p_echo " there is no comsat service record in $superserver_conf"
			;;
	esac
    fi
}

fix_mailman_cfg()
{
	inten="fix mailman configuration"
	# when installing psa, psa.conf does not exists
	# so we're to test all possible places
	for MAILMAN_ROOT_D in /var/mailman /usr/lib/mailman; do
		mm_cfg="$MAILMAN_ROOT_D/Mailman/mm_cfg.py"
		if test -r "$mm_cfg" && grep -q "^MTA[[:space:]]*=" "$mm_cfg"; then
			echo_try "$inten in $MAILMAN_ROOT_D"
			grep -v "^MTA[[:space:]]*=" "$mm_cfg" > "$mm_cfg.new" || die "$inten"
			mv -f "$mm_cfg.new" "$mm_cfg" || die "$inten"
			suc
		fi
	done
}

add_qmail_alternatives()
{
    if type update-alternatives >/dev/null 2>&1; then
        # SuSe, Debian and Ubuntu not use alternatives for MTAs
	    if [ "$linux_distr" != "suse" -a "$linux_distr" != "debian" -a "$linux_distr" != "ubuntu" ]; then
            /usr/sbin/update-alternatives --install /usr/sbin/sendmail mta "$QMAIL_ROOT_D/bin/sendmail" \
                100 --slave /usr/lib/sendmail mta-in_libdir "$QMAIL_ROOT_D/bin/sendmail"
        fi
    fi
}

set_default_spf()
{
	inten="set default values for SPF support"
	if db_test "select COUNT(*) from misc where param='spf_rules'" '$0 == 0'; then
		db_do --inten "$inten" "replace into misc (param, val) values('spf_rules', 'include:spf.trusted-forwarder.org')"
		if [ -f $PRODUCT_ROOT_D/admin/sbin/mailmng ]; then
			$PRODUCT_ROOT_D/admin/sbin/mailmng --update-spf --spf-rules="include:spf.trusted-forwarder.org"
		fi
	fi
	suc
}

remove_sendmail()
{
	sendmail_pid="`$ps | grep \"sendmail:\|$sendmail\" | grep -v grep | awk '{print $1}' -`"
	if [ "X$sendmail_pid" != "X" ]; then
		inten="shutdown running sendmail"
		echo_try $inten
		$K_TERM $sendmail_pid >/dev/null 2>&1 
		if [ "$?" -ne "0" ]; then
			wait_after_stop $sendmail_pid
		fi 
	fi

	if [ -f "$mail_local" ]; then
		case "$machine" in
			BSD)
				chflags noschg "$mail_local" ||
				die "chflags noschg $mail_local"
                                rm -f /usr/sbin/sendmail >/dev/null 2>&1
                                ln -s $QMAIL_ROOT_D/bin/sendmail /usr/sbin/sendmail
			   ;;
			*)
			   ;;
		esac

		mk_backup "$mail_local" cp f

		chmod 0 "$mail_local" ||
		die "chmod 0 $mail_local"
	fi

	case "$machine" in
		linux )
		    case "$linux_distr" in
			redhat)
				[ -f /etc/init.d/sendmail ] && chkconfig --del sendmail

#			    mk_backup "$sndml_ini" mv f
#				if [ -f "$sndml_ini" ]; then
#					inten="move $sndml_ini to $sndml_ini.${product}"
#					echo_try $inten
#					mv -f "$sndml_ini" "$sndml_ini.${product}" && suc || die $inten
#				fi
				;;
		   esac
		;;
		*)
			;;
	esac

}

install_qmail()
{
	p_echo

	# At upgrade time, old qmail tunings keeped untouched
	if [ ! -f "$QMAIL_ROOT_D/control/me" ]; then
		echo "$fullhost"	> "$QMAIL_ROOT_D/control/me" || die
	fi

	if [ ! -f "$QMAIL_ROOT_D/control/locals" ]; then
		echo "localhost"	> "$QMAIL_ROOT_D/control/locals" || die
	fi

	touch "$QMAIL_ROOT_D/control/rcpthosts" || die
	touch "$QMAIL_ROOT_D/control/virtualdomains" || die

	chown 0:0 "$QMAIL_ROOT_D/control"/* || die
	chmod 644 "$QMAIL_ROOT_D/control"/* || die
	# it's not used anymore
	rm -f "$QMAIL_ROOT_D/users/poppasswd" ||:

	if [ ! -f "$QMAIL_ROOT_D/users/assign" ]; then
		echo "." > "$QMAIL_ROOT_D/users/assign" || die
		set_ac 0 0 644 "$QMAIL_ROOT_D/users/assign" || die
	fi

	if [ "X$do_upgrade" != "X1" ]; then

		if [ -f "/etc/alternatives/mta" ]; then
			mta=`readlink /etc/alternatives/mta`
			unregister_service "${mta#*.}" stop
		else
			remove_sendmail
		fi
	fi
	generate_tls_certificates

	[ -x "/etc/init.d/qmail" ] && register_service qmail defaults defaults /usr/sbin/sendmail mta /var/qmail/bin/sendmail 90

	add_qmail_alternatives

	add_manpath "$QMAIL_ROOT_D/man"

	if [ "X$do_upgrade" = "X1" ]; then
	    pleskrc qmail start
	fi
}

mail_poppasswd_long_names()
{
    if db_test "SELECT val FROM misc WHERE param = 'allow_short_pop3_names'" '/^disabled$/'; then
	"$PRODUCT_ROOT_D/admin/sbin/mailmng" --set-accounts-format --account-format="compound"
    fi
}

qmail_superserver_fix()
{
    # set-mail-params

    run_str="$UTILS_DIR/mailmng --set-mail-params"

    db_select "select val from misc where param='relay'"
    if [ "open" = "$db_select_output" ]; then
        run_str="$run_str --relayclient"
    fi

    db_select "select * from misc where param='disable_smtp_auth' and val>0"
    if [ -z "$db_select_output"  ]; then
        run_str="$run_str --smtpauth"
    fi

    db_select "select * from misc where param='disable_pop_auth' and val>0"
    if [ -z "$db_select_output"  ]; then
        run_str="$run_str --popauth"
    fi

    db_select "select val from misc where param='poplock_time'"
    if [ -n "$db_select_output"  ]; then
        run_str="$run_str --poplock-time=$db_select_output"
    fi

    db_select "select val from misc where param='allow_short_pop3_names'"
    if [ -z "$db_select_output" -o "disabled" != "$db_select_output" ]; then
        run_str="$run_str --shortnames"
    fi

    $run_str

    # RBL

    db_select "select val from misc where param='rbl'"
    if [ "true" = "$db_select_output" ]; then
        db_select "select val from misc where param='rbl_server'"
        if [ -n "$db_select_output"  ]; then
            server_list=`echo $db_select_output|sed -e "s|;|,|g"`
            $UTILS_DIR/mailmng --set-maps-protection --maps-zones=$server_list
        fi
    fi
    true
}

disable_qmail()
{
    qmail_super_server_config remove smtp
    qmail_super_server_config remove smtps
    qmail_super_server_config remove submission
    superserver_reconfig
}

# $1 - openssl binary
# $2 - openssl args
# $3 - cert file name
# $4 - bits number
qmail_tls_cert()
{
	local QMAIL_CONTROL_D TLS_CERT

	QMAIL_CONTROL_D=${QMAIL_ROOT_D}/control
	TLS_CERT=${QMAIL_CONTROL_D}/$3

	if [ ! -f ${TLS_CERT} ]; then
		$1 $2 -out ${TLS_CERT} $4 >> $product_log 2>&1
		if [ $? -ne 0 ]; then
			report_problem "Certificate for qmail TLS sessions ${TLS_CERT} was not generated. Qmail will generate it at each TLS session. It is too slow and will make high CPU load."
		fi
		p_echo
	fi

	if [ -f ${TLS_CERT} ]; then
		chmod 600 ${TLS_CERT} && chown qmaild:0 ${TLS_CERT}
		if [ $? -ne 0 ]; then
			# Fallback for case when qmail is not installed
			chmod 600 ${TLS_CERT} && chown root:0 ${TLS_CERT}
			report_problem "Unable to set proper permission to ${TLS_CERT} Normally, owner user and group should be qmaild:0 and access should be 0600."
		fi
	fi
}

generate_tls_certificates()
{
	local SSL_BIN inten umask_sav

	inten="generate SSL certificates for TLS sessions"

	echo_try $inten

	SSL_BIN=/usr/bin/openssl

	# store old umask and set very secure one
	umask_sav=`umask`
	umask 0077

	qmail_tls_cert ${SSL_BIN} "genrsa" rsa512.pem 512
	#qmail_tls_cert ${SSL_BIN} "dhparam -2" dh512.pem 512
	#qmail_tls_cert ${SSL_BIN} "dhparam -2" dh1024.pem 1024

	umask ${umask_sav}

	suc
}
#qmail

set_qmail_params()
{
    QMAIL_DIR="/var/qmail"
    QMAIL_USERS="alias:2021:nofiles:false:alias  qmaild:2020:nofiles:false:  qmaill:2022:nofiles:false:  qmailp:2023:nofiles:false:  qmailq:2520:qmail:  qmailr:2521:qmail:  qmails:2522:qmail:"
    QMAIL_GROUPS="qmail:2520  nofiles:2020"

    #variable from psa.conf but used in mail-qc-driver
    #so we need define this before install psa base package
    if [ -z "$QMAIL_ROOT_D" ]; then 
	    QMAIL_ROOT_D="/var/qmail"
    fi

    mm_mailgroup=12

    qmail_service="qmail"
    qmail_extra_cmd=""
    qmail_log="/var/log/maillog"
}

## @@constructor set_qmail_params
qmail_super_server_config()
{
    local action="$1"
    local service="$2"
    qmail_xinetd_templates

    eval "template=\$${service}_rec"
    super_server_action "$action" "$service" "$template"
}

qmail_xinetd_templates()
{
    local TRUE_BIN
    TRUE_BIN=$QMAIL_DIR/bin/true

    if [ -f /proc/net/if_inet6 ]; then
	    V6_FLAGS="flags		= IPv6"
    else
	    V6_FLAGS=""
    fi

smtp_rec="service smtp
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = root
	$V6_FLAGS
	instances       = UNLIMITED
	env             = SMTPAUTH=1
	server          = $QMAIL_DIR/bin/tcp-env
	server_args     = -Rt0 $QMAIL_DIR/bin/relaylock $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $TRUE_BIN $QMAIL_DIR/bin/cmd5checkpw $TRUE_BIN
}" 

smtps_rec="service smtps
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = root
	$V6_FLAGS
	instances       = UNLIMITED
	env             = SMTPAUTH=1
	server          = $QMAIL_DIR/bin/tcp-env
	server_args     = -Rt0 $QMAIL_DIR/bin/relaylock $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $TRUE_BIN $QMAIL_DIR/bin/cmd5checkpw $TRUE_BIN
}" 

submission_rec="service submission
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = qmaild
	$V6_FLAGS
	instances       = UNLIMITED
	env             = SUBMISSION=1 SMTPAUTH=1
	server          = $QMAIL_DIR/bin/tcp-env
	server_args     = -Rt0 $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $TRUE_BIN $QMAIL_DIR/bin/cmd5checkpw $TRUE_BIN
}" 

}

upgrade_qmail_80()
{
	set_mail_params
	ch_user_home $MAIL_USERGROUP "$QMAIL_DIR/$MAIL_USERGROUP"
	qmail_fix_domain_disabling_80
}

qmail_fix_domain_disabling_80()
{
	[ -e "$QMAIL_ROOT_D/users/poppasswd" ] || return 0

	echo_try "fix domains disabling"
	perl -e '
		use File::stat;

		$poppasswd_path = shift;

		%disabled_domains = ();

		$popuser_uid = getpwnam("popuser");
		$popuser_gid = getgrnam("popuser");

		open(POPPASSWD_IN, "<", $poppasswd_path) or die("Cannot read poppasswd: $!");
		open(POPPASSWD_OUT, ">", $poppasswd_path . ".new")
		and chmod(0600, $poppasswd_path . ".new")
		or die("Cannot write poppasswd: $!");

		sub out ($) {
			my $str = shift;
			print POPPASSWD_OUT $str or die("Cannot write poppasswd: $!");
		}

		while(<POPPASSWD_IN>) {
			if (/^([^:]*):(\$[^:]*):popuser:([^:]+)(\/[^:\/]+$)/) {
				my $dir = $3;
				if (exists $disabled_domains{$dir}) {
					out $1 . ":!" . $2 . ":popuser:" . $3 . $4;
				} elsif ((stat($dir)->mode & 0777) == 0) {
					chmod(0700, $dir);
					chown($popuser_uid, $popuser_gid, $dir);
					$disabled_domains{$dir} = 1;
					out $1 . ":!" . $2 . ":popuser:" . $3 . $4;
				} else {
					out $_;
				}
			} else {
				out $_;
			}
		}

		close($poppasswd_path . ".new");
		rename ($poppasswd_path . ".new", $poppasswd_path) or die("Cannot replace poppasswd: $!");

	' "$QMAIL_ROOT_D/users/poppasswd" >>"$product_log" 2>&1 \
	|| {
		rm -f "$QMAIL_ROOT_D/users/poppasswd.new"
		report_problem "fix domains disabling"
	}

	suc
}


upgrade_qmail_82()
{
		qmail_super_server_config register submission
		qmail_super_server_config comment submission
		pleskrc superserver restart
}
upgrade_qmail_83()
{
		if [ "$linux_distr" = "debian" -o "$linux_distr" = "ubuntu" ]; then
			if [ -d "/etc/xinetd.d" ]; then
				echo_try "remove old xinetd.d mail entries"
				for mail_service in smtp smtps submission; do
					rm -fv /etc/xinetd.d/${mail_service}_psa /etc/xinetd.d/${mail_service}.psa
				done
				suc
			fi
		fi

		inten="reconfigure mail superserver records"
		echo_try $inten

		qmail_super_server_config remove smtp
		qmail_super_server_config register smtp
		qmail_super_server_config remove smtps
		qmail_super_server_config register smtps
		qmail_super_server_config remove submission
		qmail_super_server_config register submission

		db_select "select val from misc where param='message_submission'"
		if [ ! "true" = "$db_select_output" ]; then
			qmail_super_server_config disable submission	
		fi
		
		# set-mail-params
		qmail_superserver_fix

		pleskrc superserver restart
		suc
}
fix_get_pid()
{
	grep '## get_pid patched 7\.1\.5' "$PRODUCT_RC_D/httpd" >/dev/null 2>&1
	if [ 0$? -ne 0 ]; then
		cd $PRODUCT_RC_D/ || return
		file="$PRODUCT_RC_D/functions"
		orig_file="$file.orig"
		echo "Trying to patch $file script ... " >> "$product_log"
		
		### store old file into funstions.orig
		[ -f "$orig_file" ] || cp -vf "$file" "$orig_file" >> "$product_log" 2>&1

		### keep content before get_pid() function
		awk '{ if ($0 ~ "^get_pid()") { exit 0; }; print $0; }' < "$file" > "$file.tmp" 2>> "$product_log"
		## check awk errors
		if [ 0$? -ne 0 ]; then
			warn "ERROR: unable to fix get_pid() function bug in '$file'"
			return
		fi

		### replace get_pid() function
		cat >> "$file.tmp"  2>> "$product_log" <<'EOF'
get_pid()
{
	## get_pid patched 7.1.5
	local proc_name proc_basename
	proc_name="$1"
	proc_basename=`basename "$proc_name"`

	PID=`ps axww | awk '($5 ~ "('"$proc_name"'|\\\\('"$proc_basename"'\\\\))$" && ($1 > 0)) {print $1}'`
	echo $PID
}
EOF
		## check cat errors
		if [ 0$? -ne 0 ]; then
			warn "ERROR: unable to fix get_pid() function bug in '$file'"
			return
		fi

		### keep content after get_pid() function
		awk '{
		if (!skip && ($0 ~ "^get_pid()")) { skip = 1; }
		if (keep) { print $0; }
		if (skip && ($0 ~ "^}")) { skip = 0; keep = 1; }
		}' < "$file" >> "$file.tmp" 2>> "$product_log"
		## check awk errors
		if [ 0$? -ne 0 ]; then
			warn "ERROR: unable to fix get_pid() function bug in '$file'"
			return
		fi

		### move tmp file to source file
		mv -f "$file.tmp" "$file"
		[ 0$? -ne 0 ] || suc
	fi
}


fix_rc_functions()
{
	fix_get_pid
}
#!/bin/sh
install_start_script_darwin()
{
     local psa_dir="/Library/Startupitems/PSA"
     local startup_items="$psa_dir/StartupParameters.plist"

     cp -f /etc/hostconfig /etc/hostconfig.saved_by_psa || exit 1

     register_service PSA
     register_service SSHSERVER


  [ -d $psa_dir ] || mkdir -p $psa_dir

  echo ' 
{
  Description     = "PSA start script";
  Provides        = ("PSA");
  OrderPreference = "Last";
  Messages =
  {
    start = "Starting PSA services";
    stop  = "Stoping PSA service";
  };
}
' > "$startup_items"

  echo '#!/bin/sh 

script="/etc/init.d/psa.sh"

. /etc/rc.common

StartService()
{
    if [ "${PSA:=-NO-}" = "-YES-" ]; then
       "$script" start
    fi
}

StopService()
{
    if [ "${PSA:=-NO-}" = "-YES-" ]; then
       "$script" stop
    fi 
}

RestartService()
{
    if [ "${PSA:=-NO-}" = "-YES-" ]; then
       "$script" restart
    fi
}

RunService "$1"

' > "$psa_dir/PSA"

   chmod 755 "$psa_dir"
   chmod 755 "$psa_dir/PSA"
   chmod 644 "$startup_items"
}

install_startup_scripts()
{
	p_echo
	pnnl_echo "===> Installing startup scripts... "

        install_start_script_darwin
	p_echo "done"
}


rsr_backup()
{
	target="$1"
	dup="$2"
	opts="$3"
	common_var=0

#	if [ -$opts "$target" ]; then
		if [ -$opts "$target.$product_suff" ]; then
			case "$dup" in
				mv)
					mv -f  $target.$product_suff $target>> $product_log 2>&1
					common_var=1
					return 1
					;;
				cp)
					cp -fp  $target.$product_suff $target>> $product_log 2>&1
					common_var=1
					return 1
					;;
				*)
					p_echo " rsr_backup: wrong option -- must be 'cp' or 'mv'"
					;;
			esac
		else
			if [ -$opts "$target.$product_suffo" ]; then
			    case "$dup" in
				mv)
					mv -f  $target.$product_suffo $target>> $product_log 2>&1
					common_var=1
					return 1
					;;
				cp)
					cp -fp  $target.$product_suffo $target>> $product_log 2>&1
					common_var=1
					return 1
					;;
				*)
					p_echo " rsr_backup: wrong option -- must be 'cp' or 'mv'"
					;;
			    esac
			fi
		fi
#	else
#		case "$opts" in
#			f|d)
#				;;
#			*)
#				p_echo " rsr_backup: wrong option -- must be 'f' or 'd'"
#				;;
#		esac
#	fi
}

restore_named()
{
	cd "$PRODUCT_ROOT_D" >> $product_log 2>&1
	[ -f /etc/sysconfig/named ] && mv -f "/etc/sysconfig/named" "/etc/sysconfig/named.bak"
	rsr_backup "/etc/sysconfig/named" mv f

	[ -L $named_conf ] && rm -f "$named_conf"
	rsr_backup "$named_conf" mv f

	[ -L $rndc_conf ] && rm -f "$rndc_conf"
	rsr_backup "$rndc_conf" mv f

	case "$machine" in
		BSD*)
			rsr_backup /etc/named.boot mv f
			;;
		linux)
		    case "$linux_distr" in
			redhat)
			    chkconfig --add named >> $product_log 2>&1
#			    std_named_sh="/etc/rc.d/init.d/named"
#			    rsr_backup $std_named_sh mv f
#				if [ -f "$std_named_sh" ]; then
#					mv -f "$std_named_sh.${product}" "$std_named_sh"
#				fi
				;;
			slackware)
			    rsr_backup /etc/rc.d/rc.inet2 cp f
				;;
		    esac
			rsr_backup /etc/named.boot mv f
			;;
		solaris)
			rsr_backup /etc/named.boot mv f
			;;
	esac
}


restore_sendmail()
{
	[ -L $sendmail ] && rm -f "$sendmail"
	[ -L /usr/lib/sendmail ] && rm -f "/usr/lib/sendmail"

	rsr_backup "$sendmail" mv f

	case "$machine" in
		BSDI)
			rsr_backup /etc/sendmail.cf mv f
			;;
		*)
			;;
	esac

	if [ -f "$mail_local" ]; then
#		case "$machine" in
#			BSD)
#				chflags schg "$mail_local" >> $product_log 2>&1
#				;;
#			*)
#				;;
#		esac

		rsr_backup "$mail_local" mv f

		chmod 4555 "$mail_local" >> $product_log 2>&1
	fi
	case "$machine" in
		linux )
		    case "$linux_distr" in
			redhat)
			    chkconfig --add sendmail >> $product_log 2>&1
#			    rsr_backup "$sndml_ini" mv f
				;;
			slackware)
			     rsr_backup /etc/rc.d/rc.M mv f
				;;
		    esac
			;;
		solaris)
			rsr_backup "$sndml_ini" mv f
			;;
		*)
			;;
	esac

}

delete_startup_scripts()
{
	cd "$PRODUCT_ROOT_D" >> $product_log 2>&1

	case "$machine" in
		BSD)
			rm -f /usr/local/etc/rc.d/${product}.sh >> $product_log 2>&1
	#		rsr_backup /etc/rc.conf cp f

			rc_service "sendmail" "enable" "YES"
			rc_service "named" "enable" "YES"
			rc_service "mysqld" "enable" "NO"
			;;
		BSDI)
			if [ -f /etc/rc.local.${product} ]; then
				cp -p  /etc/rc.local.${product} /etc/rc.local >> $product_log 2>&1
			fi
			;;
		linux)
		    case "$linux_distr" in
			redhat)
			    chkconfig --del ${product}
			    rm -f /etc/rc.d/init.d/${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc0.d/K15${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc1.d/K15${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc2.d/K15${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc3.d/S77${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc4.d/S77${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc5.d/S77${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc6.d/K15${product} >> $product_log 2>&1
				;;
			slackware)
			    if [ -f /etc/rc.d/rc.local.${product} ]; then
				cp -p  /etc/rc.d/rc.local.${product} /etc/rc.d/rc.local >> $product_log 2>&1
			    fi
				;;
		    esac
		    ;;
		solaris)
			rm -f  /etc/init.d/${product} >> $product_log 2>&1
			if [ -f /etc/rc0.d/K01${product} ]; then
				rm -f /etc/rc0.d/K01${product} >> $product_log 2>&1
			fi

			if [ -f /etc/rc1.d/K01${product} ]; then
				rm -f /etc/rc1.d/K01${product} >> $product_log 2>&1
			fi

			if [ -f /etc/rc2.d/S77${product} ]; then
				rm -f /etc/rc2.d/S77${product} >> $product_log 2>&1
			fi
			;;
	esac
}

delete_crontab()
{

	$crontab -l 2>/dev/null > /tmp/crontab.${product}

	sed -e "s/^.*\/${product}\/admin\/sbin\/statistics.*//g" \
		-e "s/^.*\/${product}\/bin\/mysqldump.*//g" \
		-e "s/^.*\/usr\/sbin\/ntpdate.*//g" \
		< /tmp/crontab.${product} > /tmp/crontab.${product}_tmp

	mv -f /tmp/crontab.${product}_tmp /tmp/crontab.${product} >> $product_log 2>&1

	$crontab /tmp/crontab.${product}  >> $product_log 2>&1

	rm -f /tmp/crontab.${product} >> $product_log 2>&1

}

remove_ftpuser()
{
	user=$1
	ftpusers_file="/etc/ftpusers"

	egrep "^$user" $ftpusers_file >> /dev/null 2>&1

	case "$?" in
			0)
				sed -e "/$user/d" < $ftpusers_file > $ftpusers_file.tmp
				mv -f $ftpusers_file.tmp $ftpusers_file
				;;
			1)
				;;
			*)
				;;
	esac

}

remove_product_users_groups()
{

#	delete users of this(unsuccessful) installation
	for i in $users_created; do
		delete_user "$i"
	done
#	delete users with group=psacln (ftpusers and webusers)
	for i in `perl -e '$gid=getgrnam("'$clients_group'"); exit if (($gid eq "") || ($gid == 0)); while(($n,$u,$g) = (getpwent)[0,2,3]) {print "$n\n" if (($gid == $g) && ($u >= 500))}'`
	do
		delete_user "$i"
		remove_ftpuser "$i"
	done
#	delete users psaadm, psaftp
#	delete_user "$admin_user"  >> "$product_log" 2>&1
#	delete_user "$anonftp_user"  >> "$product_log" 2>&1

#	delete groups of this(unsuccessful) installation
	for i in $groups_created; do
		delete_group "$i"
	done
#	delete groups psaadm, psaftp, psacln
	delete_group "$admin_group"  >> "$product_log" 2>&1
	delete_group "$anonftp_group"  >> "$product_log" 2>&1
	delete_group "$clients_group"  >> "$product_log" 2>&1

}


undo_install()
{
	p_echo

	if pleskrc mysql status; then
		p_echo "===>Removing installed $PRODUCT_NAME components ... "
		remove_modules
		pleskrc mysql stop

		mysql_pid_file=$mysql_bddir/*.pid
		if [ -f "$mysql_pid_file" ]; then
			rm -f "$mysql_pid_file"
		fi
	fi

	$START_SH stop >> "$product_log" 2>&1

	proftpd_super_server_config remove

	super_server_action remove pop3
	super_server_action remove pop-3
	super_server_action remove imap4
	super_server_action remove imap2
	super_server_action remove imap
	qmail_super_server_config remove smtp
	qmail_super_server_config remove smtps
	qmail_super_server_config remove submission
	poppassd_super_server_config remove

	remove_product_users_groups

	if [ -f "/etc/ftpchroot" ]; then
	    sed -e "s/^@$clients_group//g" < /etc/ftpchroot > /etc/ftpchroot.tmp
	    mv -f /etc/ftpchroot.tmp /etc/ftpchroot  >> $product_log 2>&1
	fi

	if [ -f /etc/shells ]; then
	    case "$machine" in
		BSD|BSDI)
		    sed -e "s/[/]*sbin[/]*nologin//" < /etc/shells > /etc/shells.tmp
		;;
		linux|solaris)
		    sed -e "s/[/]*bin[/]*false//" < /etc/shells > /etc/shells.tmp
		;;
	    esac
	    mv -f /etc/shells.tmp /etc/shells  >> $product_log 2>&1
	fi

	remove_tmp_state

	restore_named
	restore_sendmail
	delete_startup_scripts
	delete_crontab

	cd /usr/local  >> $product_log 2>&1

	suc
}

smart_undo_install()
{
	[ "X$trigger_uninstall" = "X1" -o "X$do_patch" = "X1" -o "X$do_reconfigure" = "X1" ] && return
	[ "X$PLESK_INSTALLER_NOUNDO" != "X" ] && return
	# trigger_uninstall - trigger what smart_undo_install is already working now(recurrence)
	trigger_uninstall=1

	if [ "X$can_uninstall" = "X1" ]; then
		if [ "X$do_upgrade" = "X1" ]; then
			undo_upgrade
		else
		    if [ "X$machine" != "XBSD" ]; then
			undo_install
		    fi
		fi
	fi

	# put suggestions for user what to do
	call_optional_function failure_note
}


prepare_upgrader()
{

    INSTALLED_VERSION=`form_undotted_version ${prev_version}`

    PRODKEY_CHANGED=0

    echo "===> Preparing upgrade"

    db_backup

    save_old_key_id

	get_old_domain

	db_added_columns=''

	stop_before_upgrade

	phpmyadmin_config_backup

	upgrade_mysqlnd_old_passwd
}

save_old_key_id()
{
    if test "$INSTALLED_VERSION" -le 70; then
		awk 'NR == 3 { print; }' $PRODUCT_ROOT_D/admin/conf/settings >$PRODUCT_ROOT_D/tmp/old_key_id
	else
		# it must be already registered
		rm -f $PRODUCT_ROOT_D/tmp/old_key_id
	fi
}

db_backup()
{
	local timestamp
	timestamp=`date +%Y%m%d-%H%M%S`
	dfile="$DUMP_D/mysql.preupgrade.${prev_version}-${product_version}.${timestamp}.dump.gz"

	if test -f $dfile; then
		# dump names should not collide, but better be safe than sorry
		local i
		i=1
		while test -f "$dfile.$i"; do
			i=$(($i+1))
		done
		mv -v "$dfile" "$dfile.$i" >> "$product_log" || die "save previous backup $dfile"
	fi

	inten="backup MySQL database"
	echo_try "$inten"
	if ! test -d "$DUMP_D"; then
		mkdir -p "$DUMP_D"
	fi
	touch "$dfile" || die "$inten"
	chown 0:0 "$dfile" || die "$inten"
	chmod 600 "$dfile" || die "$inten"
	dump_db "$PRODNAME" horde mysql | gzip > "$dfile" || die "$inten"
	suc
	p_echo " MySQL databases are dumped to $dfile"
}
safe_prep_db_upgrade()
{
	p_echo
	p_echo "===> Upgrading database"
	p_echo

	mysql_unconfigured=
	set_mysqld_params
	check_db

	# backup database and register rollback action
	db_backup
	SAFE_PREP_DB_BACKUP="$dfile"
	transaction_add_rollback_action "safe_prep_db_upgrade_rollback"

	run_db_upgrade_functions
}

safe_prep_db_upgrade_rollback()
{
	if [ -n "$SAFE_PREP_DB_BACKUP" ]; then
		p_echo
		p_echo "===> Restoring database from backup $SAFE_PREP_DB_BACKUP"
		p_echo
		zcat "$SAFE_PREP_DB_BACKUP" | mysql_anydb
		if [ $? -ne 0 ]; then
			p_echo
			p_echo "    [ERROR] Database restoring failed"
			p_echo "    Try to restore database from $SAFE_PREP_DB_BACKUP manually"
			p_echo
			return
		fi
		SAFE_PREP_DB_BACKUP=
	fi
}

safe_prep_db_install()
{
	mysql_unconfigured=1
	set_default_locale
	mysql_install_init
	insert_fullhostname
}

safe_prep_db()
{
	p_echo
	p_echo "===> Performing safe prep-install database actions"
	p_echo

	# perform database-related prep actions
	if [ "$do_upgrade" -ne 0 ]; then
		safe_prep_db_upgrade
	else
		safe_prep_db_install
	fi
}

transaction_begin()
{
	[ -n "$TRANSACTION_STARTED" ] && die "Another transaction in progress!"
	TRANSACTION_STARTED="true"
	TRANSACTION_ROLLBACK_FUNCS=
	TRANSACTION_COMMIT_FUNCS=
	trap "transaction_rollback" HUP PIPE INT QUIT TERM EXIT
}

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
}

is_transaction_in_progress()
{
	[ -z "$TRANSACTION_STARTED" ] && false || true
}

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_rollback_action()
{
	[ -z "$TRANSACTION_STARTED" ] && die "Transaction is not started!"
	# LIFO rollback order
	[ -z "$TRANSACTION_ROLLBACK_FUNCS" ] \
		&& TRANSACTION_ROLLBACK_FUNCS="$1" \
		|| TRANSACTION_ROLLBACK_FUNCS="$1 $TRANSACTION_ROLLBACK_FUNCS"
}

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"
}
undo_upgrade()
{
	p_echo   "    The attempt to upgrade $prev_product_full"
	p_echo   "    from version $prev_version to $product_full $product_version has failed."

	if [ -f "$product_sav_tar" ]; then
	
		p_echo 

		p_echo "    Now restore contents of $PRODUCT_NAME from $product_sav_tar"
		p_echo 
		get_pid $PRODUCT_ROOT_D/mysql/bin/safe_mysqld true root
		req_pid=$common_var
		if [ $req_pid -gt 1 ]; then
			$K_KILL $req_pid >> $product_log 2>&1 
			sleep 2
			mysql_pid_file=$mysql_bddir/*.pid
			kill_pids $PRODUCT_ROOT_D/mysql/libexec/mysqld mysql
			sleep 2
			if [ -f "$mysql_pid_file" ]; then
				rm -f $mysql_pid_file
			fi
		fi

		$START_SH stop >> $product_log 2>&1
		sleep 2

		rm -Rf $PRODUCT_ROOT_D
		qmail_super_server_config remove "smtp"
		qmail_super_server_config remove "smtps"
		proftpd_super_server_config remove
		poppassd_super_server_config remove
		

		cd /
        	tar xvf $product_sav_tar > /dev/null 2>&1
		case "$?" in
			0)
#				rm -f $product_sav_tar 		
			;;
			*)
				p_echo 
				p_echo 
				p_echo "ERROR: restoration of files from $product_sav_tar has failed."
				p_echo "       Please restore them manually."
				p_echo 
				p_echo "Exiting..."
				p_echo 
				exit 0
			;;
		esac
	fi
	
}

# For now we left QMail upgrading procedures from ancient Plesks here.
# Starting from Plesk-9.0 all MTA-related upgrading procedures should be
# placed into *ON-DISK* scripts which *MUST* belong to the corresponding
# mail-driver

#----------------------- Upgrade functions list constructors --------------------
#@@db_upgrade
DB_UPGRADE_FUNCTIONS_80()
{
	db_fix_bf1492_column_types_80
	db_fix_set_dns_recursion

	# 8.0 -> 8.1
	upgrade_db_80
}

UPGRADE_FUNCTIONS_80()
{
	db_fix_bf1492_column_types_80
	db_fix_set_dns_recursion
	upgrade_proftpd_754

	# 8.0 -> 8.1
	upgrade_db_80
	mail_poppasswd_long_names
	remove_cron_somely_80
	upgrade_qmail_80
}
## @@upgraders UPGRADE_FUNCTIONS_80

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_81()
{
	db_fix_81
	# 8.1 -> 8.2
	upgrade_db_81
}

UPGRADE_FUNCTIONS_81()
{
	fix_crontab_810
	db_fix_81
	# 8.1 -> 8.2
	upgrade_db_81
}
## @@upgraders UPGRADE_FUNCTIONS_81

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_82()
{
	db_fix_82
	#upgrade 8.2 -> 8.3
	upgrade_db_82
}

UPGRADE_FUNCTIONS_82()
{
	upgrade_proftpd_820
	db_fix_82
	#upgrade 8.2 -> 8.3
	upgrade_awstats_82
	upgrade_db_82
}
## @@upgraders UPGRADE_FUNCTIONS_82

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_83()
{
	db_fix_83
}

UPGRADE_FUNCTIONS_83()
{
	upgrade_cf_83
	db_fix_83
	pbm_create_certificate
}
## @@upgraders UPGRADE_FUNCTIONS_83

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_84()
{
	db_fix_84
}

UPGRADE_FUNCTIONS_84()
{
	db_fix_84
	upgrade_awstats_84
}
## @@upgraders UPGRADE_FUNCTIONS_84

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_86()
{
	db_fix_86
}

UPGRADE_FUNCTIONS_86()
{
	key_upgrade_86
	db_fix_86
	db_update_notifications

	set_mail_params
	upgrade_dk_86
	upgrade_mailman_86

	set_horde_webmail
}
## @@upgraders UPGRADE_FUNCTIONS_86

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_90()
{
	db_pmm_dashboard_90
	db_fix_90
}

UPGRADE_FUNCTIONS_90()
{
	db_pmm_dashboard_90
	db_fix_90
}
## @@upgraders UPGRADE_FUNCTIONS_90

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_92()
{
	add_db_changes 920
}

UPGRADE_FUNCTIONS_92()
{
	add_db_changes 920
	upgrade_mailman_86
}
## @@upgraders UPGRADE_FUNCTIONS_92

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_95()
{
	db_update_exp_event
}

UPGRADE_FUNCTIONS_95()
{
    db_update_dashboard_951

	db_update_exp_event
}
# #@@upgraders UPGRADE_FUNCTIONS_95

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_107()
{
	add_db_changes 1070
	db_update_sessions_107
	db_add_ftp_sys_users
#	db_add_plans
	db_add_plans_schema
	db_add_webspaces
	db_add_domain_permissions
	db_billing_integration_107
	db_migrate_sa_prefs_107
	db_upgrade_hp_mail_107
	db_default_skin_107
}

UPGRADE_FUNCTIONS_107()
{
	add_db_changes 1070
	db_add_ftp_sys_users
	db_add_plans_schema
	db_add_plans_data
	db_add_webspaces
	db_add_domain_permissions
	db_migrate_sb_data_107
	db_default_skin_107
	db_unlimited_client_expiration_107
	db_clean_up_ip_pool_107
	db_billing_integration_107
	db_migrate_sa_prefs_107
	db_upgrade_hp_mail_107
	db_generate_guids_82
	db_create_default_templates
	db_update_plesk10
	set_swkey_params
	key_upgrade_cmd
}
## @@upgraders UPGRADE_FUNCTIONS_107

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_108()
{
	db_change_domain_admins_length_108
	db_subscription_limits_default_values_108 'max_site_builder' -1
	db_subscription_limits_default_values_108 'max_unity_mobile_sites' -1
}

UPGRADE_FUNCTIONS_108()
{
	db_change_domain_admins_length_108
	db_subscription_limits_default_values_108 'max_site_builder' -1
	db_subscription_limits_default_values_108 'max_unity_mobile_sites' -1
	upgrade_postfix_enforce_tls_108
	upgrade_postfix_chroot_108
}
## @@upgraders UPGRADE_FUNCTIONS_108

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_109()
{
	add_db_changes 1090
	db_upgrade_clients_idn_109
	db_upgrade_custom_buttons_109
	db_upgrade_maintenance_mode_109
}

UPGRADE_FUNCTIONS_109()
{
	add_db_changes 1090
	db_upgrade_clients_idn_109
	fix_crontab_109
	db_upgrade_subscriptions_109
	db_upgrade_custom_buttons_109
	db_upgrade_maintenance_mode_109
	upgrade_vhosts_109
}
## @@upgraders UPGRADE_FUNCTIONS_109

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_1010()
{
    api_rpc_create_persistent_tables
    api_rpc_upgrade_persistent_tables
    add_db_changes 10100
    db_upgrade_ip_addresses_1010
    db_upgrade_dns_recs_t_1010
    db_upgrade_domain_services_1010
    db_upgrade_hosting_1010
    db_upgrade_subdomains_1010
	db_upgrade_sso_port_1010
    db_optimize_configurations_table_1010
	db_cleanup_exp_event_1010
}

UPGRADE_FUNCTIONS_1010()
{
    api_rpc_create_persistent_tables
    api_rpc_upgrade_persistent_tables
    add_db_changes 10100
    db_upgrade_ip_addresses_1010
    fix_ip_addresses_1010
    db_upgrade_dns_recs_t_1010
    db_upgrade_domain_services_1010 
    db_upgrade_web_domain_services_1010
    db_upgrade_hosting_1010
    db_upgrade_subdomains_1010
	db_upgrade_sso_port_1010
    db_optimize_configurations_table_1010
	db_cleanup_exp_event_1010
}
## @@upgraders UPGRADE_FUNCTIONS_1010

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_1011()
{
    add_db_changes 10110
	migrate_backup_management_db_into_core_1011
	migrate_pmm_management_db_into_core_1011
	db_upgrade_backups_scheduled_1011
	db_upgrade_exp_event_obj_class_1011
	db_upgrade_ssobranding_port_1011
}

UPGRADE_FUNCTIONS_1011()
{
    add_db_changes 10110
	migrate_backup_management_db_into_core_1011
	migrate_pmm_management_db_into_core_1011
	db_upgrade_backups_scheduled_1011
	db_upgrade_exp_event_obj_class_1011
	db_upgrade_ssobranding_port_1011
	create_php_ini_1011
	apsc_import_data_1011
    db_upgrade_filesharing_1011
}
## @@upgraders UPGRADE_FUNCTIONS_1011

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_1012()
{
    add_db_changes 10120
    db_upgrade_parent_domain_id_1012
    db_upgrade_service_nodes_1012
    db_upgrade_resp_attach_1012
	db_upgrade_dns_reverse_ptr_ipv6_1012
	db_upgrade_upgrade_history_1012
	db_upgrade_dns_schema_1012
}

UPGRADE_FUNCTIONS_1012()
{
    add_db_changes 10120
    db_upgrade_parent_domain_id_1012
    db_upgrade_service_nodes_1012
	db_upgrade_dns_schema_1012
	db_upgrade_dns_data_1012
    db_upgrade_resp_attach_1012
	db_upgrade_dns_reverse_ptr_ipv6_1012
    db_upgrade_subdomains_1012
	db_upgrade_permissions_1012
	db_upgrade_add_simple_plan_1012
	upgrade_postfix_1012
	upgrade_mailname_domain_dirs_perms_1012
	db_upgrade_php_settings_1012
	db_upgrade_mail_domain_services_1012
# moved from 107 because of the BL dependency (#80977)
	upgrade_proftpd_107
	db_upgrade_dns_wwwprefix_1012
	db_upgrade_upgrade_history_1012
	[ !  -x "@@PLESK_LIBEXEC_DIR@@/handlers-tmpfs" ] || @@PLESK_LIBEXEC_DIR@@/handlers-tmpfs stop
}
## @@upgraders UPGRADE_FUNCTIONS_1012

#@@db_upgrade
DB_UPGRADE_FUNCTIONS_1013()
{
	add_db_changes 10130
	db_upgrade_configurations_1013
	db_upgrade_secret_key_1013
	db_upgrade_sessions_1013
}

UPGRADE_FUNCTIONS_1013()
{
	add_db_changes 10130
	upgrade_courier_imap_auth_1013
	db_upgrade_configurations_1013
	db_upgrade_subdomains_zones_1013
	upgrade_modules_permissions_1013
	upgrade_adminlogs_permissions_1013
	generate_encryption_key
	db_upgrade_admin_simple_plan_permissions_1013
	db_upgrade_secret_key_1013
	upgrade_postfix_sasl_1013
	db_upgrade_dns_1013
	db_upgrade_sessions_1013
	db_upgrade_aps_settings_1013 # This function os executed on post stage only due to absence of table in early versions of plesk
}
## @@upgraders UPGRADE_FUNCTIONS_1013

# DO NOT RUN BEFORE UPGRADE!!!
cumulative_upgrade()
{
	# line to prevent upgrade functions from being optimized out
	true UPGRADE_FUNCTIONS_80 UPGRADE_FUNCTIONS_81 UPGRADE_FUNCTIONS_82 UPGRADE_FUNCTIONS_83 UPGRADE_FUNCTIONS_84 UPGRADE_FUNCTIONS_86 UPGRADE_FUNCTIONS_90 UPGRADE_FUNCTIONS_92 UPGRADE_FUNCTIONS_95 UPGRADE_FUNCTIONS_107 UPGRADE_FUNCTIONS_108 UPGRADE_FUNCTIONS_109 UPGRADE_FUNCTIONS_1010 UPGRADE_FUNCTIONS_1011 UPGRADE_FUNCTIONS_1012 UPGRADE_FUNCTIONS_1013 

	echo "===> Cumulative upgrade has been started"
	if run_upgrade_functions "UPGRADE_FUNCTIONS" "`form_undotted_version ${prev_version}`"; then
		echo "===> Upgrade completed."
	else
		echo "===> Your version does not require any upgrade."
	fi

	if [ "X$PLESK_IDEMPOTENCY_CHECK" = "XYes" ]; then
		die "We die to reconfigure psa package again and check that upgrader has an idempotency property"
	fi

	set_db_version
}

run_db_upgrade_functions()
{
	# line to prevent upgrade functions from being optimized out
	true DB_UPGRADE_FUNCTIONS_80 DB_UPGRADE_FUNCTIONS_81 DB_UPGRADE_FUNCTIONS_82 DB_UPGRADE_FUNCTIONS_83 DB_UPGRADE_FUNCTIONS_84 DB_UPGRADE_FUNCTIONS_86 DB_UPGRADE_FUNCTIONS_90 DB_UPGRADE_FUNCTIONS_92 DB_UPGRADE_FUNCTIONS_95 DB_UPGRADE_FUNCTIONS_107 DB_UPGRADE_FUNCTIONS_108 DB_UPGRADE_FUNCTIONS_109 DB_UPGRADE_FUNCTIONS_1010 DB_UPGRADE_FUNCTIONS_1011 DB_UPGRADE_FUNCTIONS_1012 DB_UPGRADE_FUNCTIONS_1013 

	echo "===> Cumulative database upgrade has been started"
	if run_upgrade_functions "DB_UPGRADE_FUNCTIONS" "$prev_db_short_version"; then
		echo "===> Upgrade completed."
	else
		echo "===> Your version does not require any upgrade."
	fi

	set_db_version
}

run_upgrade_functions()
{
	local FUNC_PREFIX="$1"
	local INSTALLED_VERSION="$2"

	# Flag for skipping already upgraded versions
	local UPGRADE_STARTED="0"

	for i in ${known_product_versions}; do

		if [ "X${UPGRADE_STARTED}" = "X0" -a ${INSTALLED_VERSION} -lt ${i} ]; then
			echo "    Your version is too old and not supported by this upgrader."
			exit 1;
		fi

		if [ "X${INSTALLED_VERSION}" = "X${i}" ]; then
			UPGRADE_STARTED="1"
		fi

		if [ "X${UPGRADE_STARTED}" = "X1" ] && is_function "${FUNC_PREFIX}_${i}"; then
			echo "===> Perform upgrade from ${i}" >> $product_log
			"${FUNC_PREFIX}_${i}"
		else
			echo "no upgrade from ${i}" >> $product_log
		fi

	done;

	if [ "X${UPGRADE_STARTED}" = "X1" ]; then
		return 0
	else
		return 1
	fi
}

#vhosts

install_vhosts()
{
	set_common_params
	read_conf

	inten="create Virtual Hosts directory"
# Paranoia
	echo_try $inten
	mkdir -p "$HTTPD_VHOSTS_D/default"
	mkdir -p "$HTTPD_VHOSTS_D/.skel"
	suc

	inten="sync default virtual host"
	echo_try $inten

	rsync -rlptgoD --ignore-existing @@DATADIR/plesk-vhost/ $HTTPD_VHOSTS_D/default/
	suc
# Dir check for awoid overwrite in future
	if [ ! -d "$HTTPD_VHOSTS_D/.skel/0" ]; then
		$PRODUCT_ROOT_D/admin/sbin/skelmng --install-default --id 0 >> "$product_log" 2>&1
	fi
}

chown_webstat()
{
	# select only domains with hosting
	query="select d.id from domains d, hosting h where d.id=h.dom_id";

	for dom_id in `echo $query | $mysql`; do

		query1="select s.login from sys_users s, hosting h where s.id=h.sys_user_id and h.dom_id='$dom_id'";
		login=`echo $query1 | $mysql`;

		query1="select name from domains where id='$dom_id'";
		dom_name=`echo $query1 | $mysql`;

		if [ -d "$HTTPD_VHOSTS_D/$dom_name/httpdocs/webstat" ]; then
#			chown $login:$clients_group `get_ls full "$HTTPD_VHOSTS_D/$dom_name/httpdocs/webstat"`
			find "$HTTPD_VHOSTS_D/$dom_name/httpdocs/webstat" -exec chown $login:$clients_group {} \;
		fi

	done >> "$product_log" 2>&1
}

vhosts_install_error_doc()
{
	local document dir file default_skeleton wrkdir sample_doc sample_file
	sample_doc="not_found.html"
	document="$1"
	default_skeleton="$PRODUCT_ROOT_D/tmp/default_skeleton.tgz"

	echo_try " Installing error document $document"

	wrkdir=`mktemp -d /tmp/skelXXXXXXXX`
	if test $? -ne 0; then
		p_echo " $wrkdir"
		die "create temporary directory";
	fi
	$tar xzf "$default_skeleton" -C "$wrkdir" "./error_docs/$document" >>"$product_log" 2>&1 \
	|| die "extract $document from default skeleton"

	find "$HTTPD_VHOSTS_D/.skel" "$HTTPD_VHOSTS_D" \
			-maxdepth 2 -type d -name error_docs \
	| while read dir; do
		file="$dir/$document"
		sample_file="$dir/$sample_doc"
		if ! test -e "$file"; then
			local doc_owner doc_group doc_perms
			doc_owner=0
			doc_group=0
			doc_perms=644
			if test -e "$sample_file"; then
				doc_owner=`stat -c %u "$sample_file"`
				doc_group=`stat -c %g "$sample_file"`
				doc_perms=`stat -c %a "$sample_file"`
			else
				warn "Unable to determine correct owner, group and access rights for $file. Please check them manually"
			fi
			install -o $doc_owner -g $doc_group -m $doc_perms "$wrkdir/error_docs/$document" "$file" >>"$product_log" 2>&1 \
			|| die "install document $document in $dir"

			domain_name=`echo "$dir" | awk -F/ '{ print $(NF-1) }'`
			sed -i -e "s/@domain_name@/$domain_name/g" "$file"
		fi
	done
	if test $? -ne 0; then exit 1; fi

	rm -rf "$wrkdir" >> "$product_log" 2>&1

	suc
}
upgrade_vhosts_109()
{
	vhosts_install_error_doc maintenance.html
}


#webalizer

set_webalizer_params()
{
	WEBALIZER_ROOT_D="$PRODUCT_ROOT_D/webalizer"
}

## @@constructor set_webalizer_params

set_webalizer_perms()
{
	inten="set up default webalizer permissions"
	echo_try $inten

	chown root:0 "$WEBALIZER_ROOT_D"
	chmod 755 "$WEBALIZER_ROOT_D"

	find "$WEBALIZER_ROOT_D" -type d -print0 | xargs -0 chown root:0
	find "$WEBALIZER_ROOT_D" -type d -print0 | xargs -0 chmod 555

	find "$WEBALIZER_ROOT_D" -type f -print0 | xargs -0 chown root:0
	find "$WEBALIZER_ROOT_D" -type f -print0 | xargs -0 chmod 444

	find "$WEBALIZER_ROOT_D/bin" -type f -print0 | xargs -0 chown -h root:0
	find "$WEBALIZER_ROOT_D/bin" -type f -print0 | xargs -0 chmod 755

	add_manpath "$WEBALIZER_ROOT_D/man"

	[ -d "$PRODUCT_ROOT_D/var/lib/webalizer" ] || mkdir -p "$PRODUCT_ROOT_D/var/lib/webalizer"
	chmod 755 "$PRODUCT_ROOT_D/var/lib/webalizer"

	suc
}
reconfigure_watchdog()
{
    [ -x $PRODUCT_ROOT_D/admin/bin/modules/watchdog/wd ] && $PRODUCT_ROOT_D/admin/bin/modules/watchdog/wd --adapt >>$product_log 2>&1 || true
}


set_postfix_params()
{
	postfix_service="postfix"
	pc_remote_service="pc-remote"
}


postfix_status()
{
	# here be dragons.
	# the practical experience shows that simple checking of status of
	# Postfix "master" process is not enough. So we read Postfix master
	# process pid file if any, then try to look for a process with
	# name ``qmgr'' and parent pid being equal to
	# the pid read from the pidfile. If pgrep finds such a process
	# it returns 0, if not its exit status is non-zero.
	# pgrep is portable enough to prefer it to "hand-made" alternatives
	# such as famous ``ps | grep $name | grep -v grep...'' pipes
	# bug 147822. do not interrupt installation for FreeBSD

	[ -f "/var/spool/postfix/pid/master.pid" ] || return 1

	local ppid

	read ppid </var/spool/postfix/pid/master.pid 2>/dev/null
	if [ $? -ne 0 -o -z "$ppid" ]; then
		# not found or other error
		return 1;
	fi
	pgrep -P $ppid qmgr >/dev/null 2>/dev/null
}
## vim:filetype=sh

upgrade_postfix_1012()
{
	# Remove excessive smtp proxies from master.cf, as we are going to use milter
	local master_cf_path=/etc/postfix/master.cf
	[ -s "$master_cf_path" ] || return;
	perl -ne '
		next if ($_ =~ /^.?127.0.0.1:1002[567]\s+/);
		if ($_ =~ /^(.?(smtp|smtps|submission)\s+.*)-o\s+smtpd_proxy_filter=127.0.0.1:10025(.*)$/) { print "$1$3\n"; next; }
		if ($_ =~ /^(.?pickup\s+.*)-o\s+content_filter=smtp:127.0.0.1:10027(.*)$/) { print "$1$2\n"; next; }
		print $_;
	' < $master_cf_path > $master_cf_path.tmp && mv -f $master_cf_path.tmp $master_cf_path
}

upgrade_mailname_domain_dirs_perms_1012()
{
	# this is for mailname folders that were created when Postfix was in charge
	local popuser="popuser"
	for domain_mail_dir in /var/qmail/mailnames/* ; do
		chown $popuser:$popuser "$domain_mail_dir"
	done
}

upgrade_postfix_sasl_1013()
{
	local smtpd_sasl_conf='/etc/sasl2/smtpd.conf'
	[ -f "$smtpd_sasl_conf" ] || return 0
	install_postfix_smtpd_sasl_config
}
## vim:filetype=sh

upgrade_postfix_enforce_tls_108()
{
	local master_cf_path
	master_cf_path=/etc/postfix/master.cf

	[ -f $master_cf_path ] || return 0

	sed -e '
		/submission[[:space:]]\+inet/ {
			/smtpd_tls_security_level/ !{
				s/-o[[:space:]]\+smtpd_enforce_tls=yes/& -o smtpd_tls_security_level=encrypt/
			}
		}
	' < $master_cf_path > $master_cf_path.tmp && 	mv -f $master_cf_path.tmp $master_cf_path
}

upgrade_postfix_chroot_108()
{
	local master_cf_path srv_re srv_type_re space_re bool_re
	local passwd_db_path passwd_db_path_chrooted
	master_cf_path=/etc/postfix/master.cf

	[ -f $master_cf_path ] || return 0

	srv_re="\([[:alnum:]_:#.]\+\)"
	srv_type_re="\([[:lower:]]\+\)"
	space_re="\([[:space:]]\+\)"
	bool_re="\([-yn]\)"

	passwd_db_path=`echo "/var/spool/postfix/plesk/passwd.db" | sed -e 's:[]\[\^\$\.\*\/]:\\\\&:g'`
	passwd_db_path_chrooted=`echo "/plesk/passwd.db" | sed -e 's:[]\[\^\$\.\*\/]:\\\\&:g'`

	sed -e '
		/^#'"$space_re"'/ ! {
			#    1      2        3           4        5       6        7       8        9
			s/^'"$srv_re$space_re$srv_type_re$space_re$bool_re$space_re$bool_re$space_re$bool_re"'/\1\2\3\4\5\6\7\8n/
		}
	' < $master_cf_path > $master_cf_path.tmp && 	sed -e '
		/plesk_saslauthd'"$space_re"'unix/ {
			/dbpath='"$passwd_db_path"'/ !{
				s/\(dbpath=\)'"$passwd_db_path_chrooted"'/\1'"$passwd_db_path"'/
			}
		}
	' < $master_cf_path.tmp > $master_cf_path.tmp2 && 	install_postfix_smtpd_sasl_config && 	mv -f $master_cf_path.tmp2 $master_cf_path

	rm -f $master_cf_path.tmp $master_cf_path.tmp2
}

register_webmail()
{
		local name="$1"
		local inten="register webmail '$1'"

		[ -z "$name" ] && die $inten

		$webmail_tool --install --name="$name" || warn $inten
		[ -x $httpdmng_tool ] && $httpdmng_tool --reconfigure-server || p_echo "Deferring webserver configuration"
}

unregister_webmail()
{
		local name="$1"

		local inten="unregister webmail '$1'"
		[ -z "$name" ] && warn $inten

		$webmail_tool --remove --name="$name" || warn $inten
		[ -x $httpdmng_tool ] && $httpdmng_tool --reconfigure-server || p_echo "Deferring webserver configuration"
}

install_db_file()
{
	local file="$1"
	local mysql_db_name="$2"
	local inten="$3"
	echo_try $inten
	[ -f "$file" ] || die "Unable to $inten: $file not found"
	cat $file | mysql >>"$product_log" 2>&1 || die "Unable to $inten, see $product log for details"
	suc
}

set_horde_webmail()
{
	set_horde_params # for horde layout
	set_webmail_params # for httpdmng

	[ -f "$horde_datadir/imp/login.php" ] || return 0

	local id
	db_select "SELECT name FROM domains WHERE id NOT IN (SELECT id FROM domains LEFT JOIN dom_param ON domains.id=dom_param.dom_id WHERE dom_param.param ='webmail')"
	local domains="$db_select_output"
	for name in $domains; do
		db_select "SELECT host from dns_recs WHERE host='webmail.${name}.'"
		if [ -n "$db_select_output" ]; then
			db_select "SELECT id FROM domains WHERE name='$name'"
			id="$db_select_output"
			db_do "replace into dom_param (dom_id, param, val) VALUES('$id', 'webmail', 'horde')"
		fi
	done

	[ -x $httpdmng_tool ] && $httpdmng_tool --reconfigure-all
}
set_webmail_params()
{
	webmail_conf_d="/etc/psa-webmail"
	webmail_tool="${PRODUCT_ROOT_D}/admin/bin/webmailmng"
	httpdmng_tool="${PRODUCT_ROOT_D}/admin/bin/httpdmng"
}

set_horde_params()
{
	horde_datadir="/usr/share/psa-horde"
	horde_confdir="/etc/psa-webmail/horde"
	horde_sysconfd="$horde_confdir/horde"
	horde_logdir="/var/log/psa-horde"
	horde_passwd_file="/etc/psa-webmail/horde/.horde.shadow"
	horde_title="Horde Web Based mail client"

	imp_datadir="$horde_datadir/imp"
	imp_sysconfd="$horde_sysconfd/imp"
	
	mimp_datadir="$horde_datadir/mimp"
	mimp_sysconfd="$horde_sysconfd/mimp"

	turba_datadir="$horde_datadir/turba"
	turba_sysconfd="$horde_sysconfd/turba"

	kronolith_datadir="$horde_datadir/kronolith"
	kronolith_sysconfd="$horde_sysconfd/kronolith"

	ingo_datadir="$horde_datadir/ingo"
	ingo_sysconfd="$horde_sysconfd/ingo"

	mnemo_datadir="$horde_datadir/mnemo"
	mnemo_sysconfd="$horde_sysconfd/mnemo"
	
	passwd_datadir="$horde_datadir/passwd"
	passwd_sysconfd="$horde_sysconfd/passwd"
}

## @@constructor set_horde_params
set_horde_perms()
{
    local inten="install permissions for $horde_title"
    echo_try $inten
    chown -R root:0 $horde_datadir || die $inten
    chown -R root:0 $horde_confdir || die $inten
    set_ac root "$apache_group" 640 "$horde_passwd_file"

    [ -e $horde_logdir/psa-horde.log ] || touch $horde_logdir/psa-horde.log
	set_ac $apache_user $apache_group 640 $horde_logdir/psa-horde.log || die $inten
	suc
}

horde_run_php_script()
{
	sw-engine -d include_path="$horde_datadir:/usr/share/psa-pear:." $@
}

horde_upgrade_sequences()
{
	[ -f "$horde_datadir/scripts/upgrades/2008-08-29_fix_mdb2_sequences.php" ] || return
	local inten="upgrade horde db sequences"
	echo_try "$inten"

	horde_run_php_script "$horde_datadir/scripts/upgrades/2008-08-29_fix_mdb2_sequences.php" >>$product_log 2>&1 && suc || warn "$inten"
}

install_horde_db()
{
if ! db_test_database "horde" ; then
### DB not found - create
	local inten="install horde database"
	echo_try $inten
	cat "$horde_datadir/scripts/sql/create.mysql.sql" | sed -e "s/@WEBMAIL_PASSWORD@/$horde_password/" | mysql
	suc
	return 0
fi

local mysql_db_name="horde"

if ! db_test_table "horde_vfs" ; then
	install_db_file "$horde_datadir/scripts/upgrades/2.2_to_3.0.mysql.sql" \
		"horde" \
		"upgrade horde database from 2.x to version 3.0"

###	Clean some old db entries - #53711
	db_do --inten "clean old database entries" "
		delete from horde_prefs where pref_scope!='horde' and pref_name='last_login'
	"
fi

	db_test_table "horde_histories" || \
	install_db_file "$horde_datadir/scripts/upgrades/3.0_to_3.1.mysql.sql" \
		"horde" \
		"upgrade horde database from 3.0 to version 3.1"

	db_test_table "horde_syncml_map" || \
		install_db_file "$horde_datadir/scripts/upgrades/3.1_to_3.2.mysql.sql" \
		"horde" \
		"upgrade horde database from 3.1 to version 3.2"

	if db_test_column "horde_signups" "signup_email"; then
		horde_upgrade_sequences # Upgrade from 3.2 -> 3.3
		install_db_file "$horde_datadir/scripts/upgrades/3.3_to_3.3.5.mysql.sql" \
		"horde" \
		"upgrade horde database from 3.3 to version 3.3.5" || :
	fi
}

install_turba_db()
{
	local mysql_db_name="horde"

	db_test_table "turba_objects" || \
	install_db_file "$turba_datadir/scripts/sql/turba.sql" \
		"horde" \
		"install turba database"

	db_test_column "turba_objects" "object_uid" || \
	install_db_file "$turba_datadir/scripts/upgrades/1.2_to_2.0.sql" \
		"horde" \
		"upgrade turba database from 1.2 to 2.0"

	if ! db_test_column "turba_objects" "object_firstname"; then
		echo_try "upgrade turba database from 2.1 to 2.2"
		horde_run_php_script "$turba_datadir/scripts/upgrades/2.1_to_2.2_sql_schema.php" >>$product_log 2>&1 && suc || warn "upgrade turba database schema from 2.1 to 2.2"
	
		echo_try "flatten turba shares"
		horde_run_php_script "$turba_datadir/scripts/upgrades/2007-06-17_flatten_shares.php" >>$product_log 2>&1 && suc || warn "flatten turba shares"
	fi

	if ! db_test_table "turba_shares"; then
		install_db_file "$turba_datadir/scripts/upgrades/2.1_to_2.2_add_sql_share_tables.sql" \
			"horde" \
			"upgrade turba database from 2.2.1 to 2.3"
		horde_upgrade_sequences
	fi

	db_test "DESC horde.turba_shares" "\$1 == \"share_owner\" && \$2 ~ (255)" || \
	install_db_file "$turba_datadir/scripts/upgrades/2.2.1_to_2.3.sql" \
		"horde" \
		"upgrade turba database from 2.2.1 to 2.3"
}

install_kronolith_db()
{
	local mysql_db_name="horde"

	db_test_table "kronolith_events" || \
	install_db_file "$kronolith_datadir/scripts/sql/kronolith.mysql.sql" \
		"horde" \
		"install kronolith database"

	db_test_table "kronolith_storage" || \
	install_db_file "$kronolith_datadir/scripts/upgrades/1.1_to_2.0.mysql.sql" \
		"horde" \
		"upgrade kronolith database from 1.1 to 2.0"

	db_test "DESC kronolith_events" "\$1 == \"event_recurtype\" && \$2 ~ \"smallint\"" || \
	install_db_file "$kronolith_datadir/scripts/upgrades/2006-08-20_fix_recur_int_fields.mysql.sql" \
		"horde" \
		"fix the SQL types of several recurrence fields"

	if ! db_test_table "kronolith_shares"; then
		install_db_file "$kronolith_datadir/scripts/upgrades/2.1_to_2.2.sql" \
			"horde" \
			"upgrade kronolith database from 2.1 to 2.2"
		horde_upgrade_sequences
	fi

	db_test "DESC horde.kronolith_shares" "\$1 == \"share_owner\" && \$2 ~ (255)" || \
	install_db_file "$kronolith_datadir/scripts/upgrades/2.2_to_2.3.sql" \
		"horde" \
		"upgrade kronolith database from 2.2 to 2.3"
}

install_mnemo_db()
{
	local mysql_db_name="horde"
	db_test_table "mnemo_memos" || \
	install_db_file "$mnemo_datadir/scripts/sql/mnemo.sql" \
		"horde" \
		"install mnemo database"

#   Fix up creating passwordless user, bug 41358
	db_do_if \
		"SELECT user FROM mysql.user where user='horde' and host='%' LIMIT 1" "1" \
			"DELETE FROM mysql.user WHERE user='horde' and host='%';
			DELETE FROM mysql.tables_priv WHERE user='horde' and host='%';
			GRANT SELECT, INSERT, UPDATE, DELETE ON mnemo_memos TO horde@localhost;
			FLUSH PRIVILEGES;"	

	if ! db_test_table "mnemo_shares"; then
		install_db_file "$mnemo_datadir/scripts/upgrades/2.1_to_2.2.sql" \
			"horde" \
			"upgrade mnemo database from 2.1 to 2.2"
		horde_upgrade_sequences
	fi

	db_test "DESC horde.mnemo_shares" "\$1 == \"share_owner\" && \$2 ~ (255)" || \
	install_db_file "$mnemo_datadir/scripts/upgrades/2.2_to_2.2.1.sql" \
		"horde" \
		"upgrade mnemo database from 2.2 to 2.2.1"

	db_test "DESC horde.mnemo_shares_groups" "\$1 == \"group_uid\" && \$2 ~ (255)" || \
	install_db_file "$mnemo_datadir/scripts/upgrades/2.2.1_to_2.2.2.sql" \
		"horde" \
		"upgrade mnemo database from 2.2.1 to 2.2.2"
}

generate_horde_password()
{
	generate_password_file "$horde_passwd_file" "$horde_title" root "$apache_group" 640
	horde_password=`cat $horde_passwd_file` || die $inten
}

install_horde()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		return 0;
	fi

	p_echo
	cd "$PRODUCT_ROOT_D" || die
	p_echo "===> Installing $horde_title"
	
	set_horde_params
	set_horde_perms
	generate_horde_password	

	db_test_database "horde" >>$product_log 2>&1 && dump_db "horde" || \
		p_echo "Cannot dump, database 'horde' not exists"

	install_horde_db
	install_turba_db
	install_kronolith_db
	install_mnemo_db
}

#	Keep for compatibility issue
check_mysql()
{
	mysql_test_connection
}
set_atmail_params()
{
    atmail_passwd_file="/etc/psa-webmail/atmail/.atmail.shadow"
    atmail_db_tables_template="/srv/www/atmail/install/atmail.mysql"
    atmail_db_create_template="/etc/psa-webmail/atmail/create_db.sql"
    atmail_title="Atmail Web Based mail client"
    atmail_root_d="/srv/www/atmail"
}

## @@constructor set_atmail_params
generate_atmail_password()
{
	generate_password_file "$atmail_passwd_file" "$atmail_title" root $apache_group 640
	atmail_password=`cat $atmail_passwd_file` || die "get atmail password"
}

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

fix_anacron_permissions()
{
	anacron_scripts_dir="/var/spool/anacron"
	test -d "${anacron_scripts_dir}" || return

	inten="fix anacron daily and weekly scripts permissions"
	echo_try "${inten}"

	chmod go+x /var/spool/anacron/cron.{daily,weekly} >/dev/null 2>&1
	suc
}
label_logrote_configs()
{
    for logrotate_config in ${logrotate_include_d}/*; do
        test -f "${logrotate_config}" || continue

        label_file_once "${logrotate_config}" "${AUTOGENERATED_CONFIGS}"
    done
}
upgrade_adminlogs_permissions_1013()
{
    chown psaadm:0 ${PRODUCT_ROOT_D}/admin/logs
    chmod 750 ${PRODUCT_ROOT_D}/admin/logs
}
#!/bin/sh

PACKAGE_NAME="phpmyadmin"
PACKAGE_VERSION="3.5"
PACKAGE_RELEASE="6"
PACKAGE_PATCH="0"

package_script_begin

unpack_new_version()
{
	# Save config file
	cp -f $PHPMYADMIN_CONFIG $PRODUCT_ROOT_D/tmp/

	# Replace the old phpmyadmin
	echo_try "remove old phpmyadmin directory"
	rm -rf $PHPMYADMIN_D
	suc

	echo_try "unpack new phpmyadmin version"
	tar -zxf $PRODUCT_ROOT_D/tmp/phpmyadmin.tar.gz -C ${PHPMYADMIN_D%/*}
	suc

	# Restore config file
	cp -f $PRODUCT_ROOT_D/tmp/config.default.php ${PHPMYADMIN_CONFIG}.save

	echo_try "set permissions"
	chown -R root:root $PHPMYADMIN_D
	find ${PHPMYADMIN_D} -type d -print0 | xargs -0 chmod 755
	find ${PHPMYADMIN_D} -type f -print0 | xargs -0 chmod 644
	suc
}

pma__replace_vars()
{
	local src="$1"
	local designer_coords tracking userconfig

        designer_coords="pma_designer_coords"
        tracking="pma_tracking"
        userconfig="pma_userconfig"

        if [ -f "${PHPMYADMIN_CONFIG}.save" ]; then
                pma__set_values_from_config "${PHPMYADMIN_CONFIG}.save" "designer_coords" "tracking" "userconfig"
        fi

	sed -e "s|@@PMA_DESIGNER_COORDS@@|$designer_coords|g" \
		-e "s|@@PMA_TRACKING@@|$tracking|g" \
		-e "s|@@PMA_USERCONFIG@@|$userconfig|g" \
	< $src >${src}.new

	mv -f ${src}.new $src
}

pma__fix_templates()
{
	pma__replace_vars "$PHPMYADMIN_D/examples/create_tables.sql"
	pma__replace_vars "$PHPMYADMIN_CONFIG"
	pma__replace_vars "${PHPMYADMIN_CONFIG}.tpl"
}

pma__configure_additional()
{
        local designer_coords tracking userconfig controluser controlpass pmadb
        local bookmarktable column_info history pdf_pages relation table_coords table_info
	local recent table_uiprefs

	controluser=''

        if [ -f "$PHPMYADMIN_CONFIG.save" ]; then
		pma__set_values_from_config 'controluser' 'controlpass' \
			'pmadb' 'bookmarktable' 'relation' 'table_info' \
			'table_coords' 'pdf_pages' 'column_info' 'history' \
			'designer_coords' 'tracking' 'userconfig' 'recent' \
			'table_uiprefs'
	fi

	if [ -z "$controluser" ]; then
		pma__set_default_values
		pma__set_random_values
	fi

	# create additional database tables
	pma__create_pmadb

	# write new config.inc.php
        sed -e "`pma__sed_script`" < "$PHPMYADMIN_CONFIG.tpl" > "$PHPMYADMIN_CONFIG"
}

check_pma_version()
{
	# fix buggy installation
	path="$PHPMYADMIN_D/libraries/config.default.php.tpl"
	grep -q '@@PMA_RECENT@@' $path && return 1

	path="$PHPMYADMIN_D/libraries/Config.class.php"
	old_version="`cat $path | awk -F "'" '/PMA_VERSION/ {print $4}'`"
	new_version="`echo $PACKAGE_VERSION| tr -d '.'`"
	pma_version="`echo $old_version | awk -F '.' '{print $1$2}'`"
	pma_release="`echo $old_version | awk -F '.' '{print $3}'`"
	pma_patch="`echo $old_version | awk -F '.' '{print $4}'`"

	[ -z "$pma_patch" ] && pma_patch="0"
	[ "$new_version" -gt "$pma_version" ] && return 1
	[ "$PACKAGE_RELEASE" -gt "$pma_release" ] && return 1
	[ "$PACKAGE_PATCH" -gt "$pma_patch" ] && return 1

	return 0
}

# Is upgrade
do_upgrade=1
PLESK_INSTALLER_VERBOSE=1

# Set common parameters
set_mysqld_params
set_phpmyadmin_params

# Check version
check_pma_version && exit 0

# Remove old version.
# Save configs and unpack new version from archive
unpack_new_version

# Install new database scheme and configs
pma__configure_additional
pma__fix_templates

package_script_end
