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

#
# Plesk script
#


#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()
{
	# it seems, that these lines is not required anymore     #
	# because respective directories are empty at build time #
	if [ "X$do_upgrade" != "X1" ]; then
		rm -f $ADMIN_ROOT/cgi-bin/*
		rm -f $ADMIN_ROOT/logs/*
		[ -d $ADMIN_ROOT/proxy ] && rm -Rf $ADMIN_ROOT/proxy
	fi

   	#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"
		set_ac root 0 500 "$ADMIN_ROOT/sbin/statistics"
	fi
}

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
Plesk
plesk
info@plesk.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
}

# upgrade_admin.sh

upgrade_admin_131()
{

	p_echo
	p_echo
	p_echo "===> Upgrading Admin Server"

# move SSL certificate
	inten="move SSL Certificate file"
	echo_try "$inten"
	cp -f "$PREV_PRODUCT_ROOT_D/admin/conf/httpsd.pem" "$ADMIN_CERT" >> "$product_log" 2>&1 && suc || die $inten

	inten="change Certificate file mode"
	echo_try "$inten"
	chmod -R 700 "$ADMIN_CERT" >> "$product_log" 2>&1 && suc || die $inten
	
	inten="change Certificate file owner"
	echo_try "$inten"
	chown -R 0:0 "$ADMIN_CERT" >> "$product_log" 2>&1 && suc || die $inten
	

#	inten="change password file mode"
#	echo_try "$inten"
#	chmod -R 700 "$ADMIN_CERT" >> "$product_log" 2>&1 && suc || die $inten
#	
#	inten="change password file owner"
#	echo_try "$inten"
#	chown -R 0:0 "$ADMIN_CERT" >> "$product_log" 2>&1 && suc || die $inten


# save plesk.key
	save_key="${product_etc}/${prev_product}.key.${prev_version}"

	inten="save old plesk.key file"
	echo_try "$inten"
	cp -f "$PREV_PRODUCT_ROOT_D/admin/utils/${prev_product}.key" "${save_key}" >> "$product_log" 2>&1 && suc || die $inten

	inten="change old plesk.key file owner"
	echo_try "$inten"
	chmod -R 700 "$save_key" >> "$product_log" 2>&1 && suc || die $inten

	inten="change old plesk.key file owner"
	echo_try "$inten"
	chown -R 0:0 "$save_key" >> "$product_log" 2>&1 && suc || die $inten

# check if logo file was changed, if yes - copy to a new location

	inten="find logo image"
	echo_try "$inten"

 	query="select val from misc where param='logo_file'"
	logo_file=`echo $query | $mysql`

	if [ ! -z "$logo_file" ]; then

		prev_logo="$PREV_PRODUCT_ROOT_D/admin/htdocs/locale/$default_locale/images/logo/$logo_file"
 		logo="$PRODUCT_ROOT_D/admin/htdocs/locale/common/images/logo/$logo_file"

		if [ -f "$prev_logo" ]; then

			p_echo "found."

			inten="copy logo image to a new location"
			echo_try "$inten"
			cp "$prev_logo" "$logo" >> "$product_log" 2>&1 && suc || die $inten

		else
			p_echo "not found."
		fi
	else
		p_echo "not found."
	fi

}

clean_old_skins_500()
{
	# remove old standard skins (1 and 2) to avoid of garbaging skin directories
	rm -rf "$PRODUCT_ROOT_D/admin/htdocs/skins/Standard_1" >> "$product_log" 2>&1
	rm -rf "$PRODUCT_ROOT_D/admin/htdocs/skins/Standard_2" >> "$product_log" 2>&1
}

move_sys_skel_500()
{
	inten="move vhost skeleton to new location"
	echo_try ${inten}

	old_skel_dir="$HTTPD_VHOSTS_D/.skel"
	new_skel_dir="$HTTPD_VHOSTS_D/.skel/0"
	backup_file="$HTTPD_VHOSTS_D/old_skel_sav_50.tgz"

	# backup old skeleton
	tar -czf "$backup_file" "$old_skel_dir" >> "$product_log" 2>&1 

	# remove 'dangerous' directory
	if [ -e "$new_skel_dir" ]; then
		rm -rf "$new_skel_dir" >> "$product_log" 2>&1 
	fi
	
	# create new skel dir and move old content there
	mkdir -p "$new_skel_dir"  >> "$product_log" 2>&1 
	find "$HTTPD_VHOSTS_D/.skel" -mindepth 1 -maxdepth 1 '!' -name '0' -exec mv -f '{}' "$new_skel_dir" ';' >> "$product_log" 2>&1 

	# remove files&dirs, which no more required
	[ -e "$new_skel_dir/webstat"     ] && rm -rf "$new_skel_dir/webstat"     >> "$product_log" 2>&1 
	[ -e "$new_skel_dir/webstat-ssl" ] && rm -rf "$new_skel_dir/webstat-ssl" >> "$product_log" 2>&1 
	[ -e "$new_skel_dir/ftpstat"     ] && rm -rf "$new_skel_dir/ftpstat"     >> "$product_log" 2>&1 
	[ -e "$new_skel_dir/logs"        ] && rm -rf "$new_skel_dir/logs"        >> "$product_log" 2>&1 
	[ -e "$new_skel_dir/cert"        ] && rm -rf "$new_skel_dir/cert"        >> "$product_log" 2>&1 

	chown -R root:0 "$new_skel_dir"
	
	# set specific permissions on skeleton content
	find "$new_skel_dir" -type d -mindepth 0 -exec chmod 0755 '{}' ';' >> "$product_log" 2>&1 
	find "$new_skel_dir" -type f -mindepth 0 -exec chmod 0644 '{}' ';' >> "$product_log" 2>&1 

	suc 

	echo "Notice: Old skeleton was saved as '$backup_file'"
}

make_sessions_dir_500()
{
	inten="add sessions dir"
	echo_try ${inten}
	
	dir="$PRODUCT_ROOT_D/admin/sessions"
	[ -d "$dir" ] || mkdir -p "$dir" >> "$product_log" 2>&1 || die ${inten}
	set_ac root $admin_group 0770 "$dir"

	suc
}

remove_old_semaphores_500()
{
	inten="remove old System V semaphores"
	echo_try ${inten}

	sem=`ipcs -s | grep -e '^0x' | grep -e 'psaadm' | awk '{ print $2;}'` 
	if [ "X$sem" != "X" ] ; then
	  echo "$sem" | xargs ipcrm sem >> "$product_log" 2>&1 || warn ${inten}
	fi

	suc
}

move_logo_files_500()
{
	local OLD_LOGO_D NEW_LOGO_D files_num

	inten="move logo files to new logo directory"

	OLD_LOGO_D="$PRODUCT_ROOT_D/admin/htdocs/locale/common/images/logo"
	NEW_LOGO_D="$PRODUCT_ROOT_D/admin/htdocs/locale/common/logos"

	# RPM build may not have old logos directory
	if [ -d ${OLD_LOGO_D} ]; then

		# check, that there is some files inside it
		files_num=`ls -al "$OLD_LOGO_D" | wc -l`
		if [ "$files_num" -gt 3 ]; then

			mv -f "${OLD_LOGO_D}"/* "${NEW_LOGO_D}"/ || die ${inten}

			chown root:${admin_group} "${NEW_LOGO_D}"/* || die ${inten}
			chmod 444 "${NEW_LOGO_D}"/* || die ${inten}

		fi

		rm -rf "$PRODUCT_ROOT_D/admin/htdocs/locale/common/images" || die ${inten}

	fi

	find "$PRODUCT_ROOT_D/admin/htdocs/locale" -type f -name "logo_anim.gif" -exec rm -f '{}' ';' >> "$product_log" 2>&1 || die ${inten}
	find "$PRODUCT_ROOT_D/admin/htdocs/locale" -type f -name "powered_by.gif" -exec rm -f '{}' ';' >> "$product_log" 2>&1 || die ${inten}
}

check_rootchain_cert_500()
{
	local rootchain_state

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

	if [ "X${rootchain_state}" = "Xtrue" ]; then

		if [ -f "$PRODUCT_ROOT_D/admin/conf/rootchain.pem" ]; then

			inten="restore control panel rootchain certificate"
			
			echo_try $inten

			"$PRODUCT_ROOT_D"/admin/sbin/certmng rootchain on1 >> "$product_log" 2>&1 || die $inten
			
			suc

		else
			p_echo
			p_echo "WARNING!! Cannot find rootchain certificate file of control panel."
			p_echo "Feature will remain disabled."
			p_echo
			
		fi
	fi
}

move_logo_files_700()
{
	local OLD_LOGO_D NEW_LOGO_D logos_list id logo_file

	inten="move logo files to new logo directory"

	OLD_LOGO_D="$PRODUCT_ROOT_D/admin/htdocs/locale/common/logos"
	NEW_LOGO_D="$PRODUCT_ROOT_D/admin/htdocs/images/logos"

	# RPM build may not have old logos directory
	if [ -d ${OLD_LOGO_D} ]; then

		# we must move only those logos, that are registered in database

		query="SELECT id FROM Logos"

		logos_list=`echo $query | $mysql`

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

		    for id in ${logos_list}; do

			# get filename of logo
			query="SELECT fake FROM Logos WHERE id='${id}'"
			logo_file=`echo $query | $mysql`

			if [ -f "${OLD_LOGO_D}/${logo_file}" ]; then

			    mv -f "${OLD_LOGO_D}/${logo_file}" "${NEW_LOGO_D}/${logo_file}" || die ${inten}
			    chown root:${admin_group} "${NEW_LOGO_D}/${logo_file}" || die ${inten}
			    chmod 444 "${NEW_LOGO_D}/${logo_file}" || die ${inten}
			fi
		    
		    done

		fi

		rm -rf "${OLD_LOGO_D}"
	fi
}

move_locales_files_710()
{
	mkdir -p "$PRODUCT_ROOT_D/admin/htdocs/locales"
	set_ac root $admin_group 555 "$PRODUCT_ROOT_D/admin/htdocs/locales"

	mkdir -p "$PRODUCT_ROOT_D/admin/plib/locales"
	set_ac root $admin_group 550 "$PRODUCT_ROOT_D/admin/htdocs/locales"

	TRANSLATE_LOCALES="al>sq-AL ar>ar-SY br>pt-BR ca>ca-ES cn>zh-CN de>de-DE en>en-US es>es-ES fr>fr-FR it>it-IT jp>ja-JP pl>pl-PL pt>pt-PT ro>ro-RO ru>ru-RU nl>nl-NL fi>fi-FI tr>tr-TR el>el-GR ko>ko-KR"

	for rule in $TRANSLATE_LOCALES; do
		old_locale=`echo $rule | cut -d '>' -f 1`
		new_locale=`echo $rule | cut -d '>' -f 2`

		if [ -d "$PRODUCT_ROOT_D/admin/htdocs/locale/$old_locale" ]; then
			if [ -d "$PRODUCT_ROOT_D/admin/htdocs/locales/$new_locale" ]; then
				rm -rf "$PRODUCT_ROOT_D/admin/htdocs/locale/$old_locale"
			else
				mv -f "$PRODUCT_ROOT_D/admin/htdocs/locale/$old_locale" "$PRODUCT_ROOT_D/admin/htdocs/locales/$new_locale"
				set_ac root $admin_group 555 "$PRODUCT_ROOT_D/admin/htdocs/locales/$new_locale"
			fi
		fi

		if [ -f "$PRODUCT_ROOT_D/admin/plib/locale/messages_$old_locale.php3" ]; then
			if [ -d "$PRODUCT_ROOT_D/admin/plib/locales/$new_locale" ]; then
				rm -rf "$PRODUCT_ROOT_D/admin/plib/locale/messages_$old_locale.php3" "$PRODUCT_ROOT_D/admin/plib/locale/conhelp_$old_locale.php3"
			else
				mkdir -p "$PRODUCT_ROOT_D/admin/plib/locales/$new_locale"
				set_ac root $admin_group 550 "$PRODUCT_ROOT_D/admin/htdocs/locales/$new_locale"

				mv -f "$PRODUCT_ROOT_D/admin/plib/locale/messages_$old_locale.php3" "$PRODUCT_ROOT_D/admin/plib/locales/$new_locale/messages_$new_locale.php"
				mv -f "$PRODUCT_ROOT_D/admin/plib/locale/conhelp_$old_locale.php3" "$PRODUCT_ROOT_D/admin/plib/locales/$new_locale/conhelp_$new_locale.php"
			fi
		fi
	done

	rm -rf "$PRODUCT_ROOT_D/admin/htdocs/locale/default"

	for locale in `find "$PRODUCT_ROOT_D/admin/htdocs/locale" -mindepth 1 -maxdepth 1 -type d -print | sed -e "s|^$PRODUCT_ROOT_D/admin/htdocs/locale/||"`; do
		mv -f "$PRODUCT_ROOT_D/admin/htdocs/locale/$locale" "$PRODUCT_ROOT_D/admin/htdocs/locales/$locale"
	done

	if [ -z "`ls $PRODUCT_ROOT_D/admin/htdocs/locale`" ]; then
		rm -rf "$PRODUCT_ROOT_D/admin/htdocs/locale"
	fi

	for locale in `find "$PRODUCT_ROOT_D/admin/plib/locale" -maxdepth 1 -name 'messages_??.php3' -type f -print | sed -e 's/^.*_\([[:alpha:]][[:alpha:]]\)\.php3$/\1/'`; do
		mkdir -p "$PRODUCT_ROOT_D/admin/plib/locales/$locale"
		set_ac root $admin_group 550 "$PRODUCT_ROOT_D/admin/htdocs/locales/$locale"

		mv -f "$PRODUCT_ROOT_D/admin/plib/locale/messages_$locale.php3" "$PRODUCT_ROOT_D/admin/plib/locales/$locale/messages_$locale.php"
		mv -f "$PRODUCT_ROOT_D/admin/plib/locale/conhelp_$locale.php3" "$PRODUCT_ROOT_D/admin/plib/locales/$locale/conhelp_$locale.php"
	done
}

upgrade_admin_750()
{
#	generate_httpsd_conf
:
}
set_apache_params()
{
	apache_user="www"
	apache_UID=80
	apache_group="www"
	apache_GID=80

	user_apxs="/usr/local/sbin/apxs"

	set_apache_params_freebsd

	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/local"

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

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

fix_apache_path()
{
    fix_apache_path_freebsd
}

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

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
}

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_add_listen_443()
{
    local config="$1"

    sed -i -e "/^Listen[[:space:]]*443/d" "$config"
    add_string '[[:space:]]*Listen[[:space:]]*443' 		"Listen 443" "$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 '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"
		if [ -f $apache_listen_conf ]; then
			apache_conf_add_listen_443 $apache_listen_conf
		fi

		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"
		if [ -f $apache_listen_conf ]; then
			apache_conf_add_listen_443 $apache_listen_conf
		fi
		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 in Debian
	add_apache_module ssl

	# 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

	# insert NameVirtualHost IP into the MySQL database, if no

	if [ 0${do_upgrade} -eq 0 ]; then
		inten="insert default PTR to the MySQL database"
		echo_try $inten
		
		if [ "X${fullhost}" = "X" -o "X${ipaddress}" = "X" ]; then
			die "fullhost or ipaddress not defined"
		fi
		
		query="
			REPLACE INTO dns_zone SET
				name='${fullhost}',
				displayName='${fullhost}';
			SELECT LAST_INSERT_ID();"
		default_dns_zone_id=`echo ${query} | $mysql`
		query="
			REPLACE INTO misc SET
				param='default_dns_zone_id',
				val='${default_dns_zone_id}';"
		echo $query | $mysql || die $inten
		local ip_addr
		for ip_addr in ${ipaddress};do
			db_do "REPLACE dns_recs SET dns_zone_id='${default_dns_zone_id}', 					type='PTR', host='$ip_addr', val='${fullhost}.', 					displayHost='$ip_addr', displayVal='${fullhost}.', 					opt='24'"
		done
	fi

	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|www|$apache_user|g" 				-e "s|www|$apache_group|g" 				-e "s|/usr/local/www/vhosts|$HTTPD_VHOSTS_D|g" 				-e "s|/usr/local|$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
	

	# Upgrade cannot handle this situation correctly because of old database
	if [ "X${do_upgrade}" != "X1" ]; then
	    inten="reconfigure Apache"
	    echo_try $inten
	    "$UTILS_DIR"/websrvmng -v -a  >> $product_log 2>&1 && suc || die "$inten"
	fi

	add_manpath "$APACHE_ROOT/man"

	move_sitebuilder_conf

}

fake_latest_apache_restart()
{
	inten="rewind latest apache restart"
	query="REPLACE INTO misc (param, val) VALUES ('latest_apache_restart', NOW() - INTERVAL 20 MINUTE)"
	echo $query | $mysql || die $inten
}

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
}

# Run before it
#        read_conf
#        # set_common_params
#        set_apache_params
add_apache_module()
{
	local module_name="$1"
	local sys

	if [ ! -e "${apache_modules_d}/mod_${module_name}.so" ]; then
		p_echo "Shared object mod_${module_name}.so not found in ${apache_modules_d}...skipped."
		return
	fi

	sys="${machine}_${linux_distr}_${conceived_os_version}"

	case "$sys" in

	linux_redhat_el2.1|linux_redhat_7.3|BSD_*|Darwin*)
	    if [ -x ${user_apxs} ]; then
		${user_apxs} -e -a -n ${module_name} ${apache_modules_d}/mod_${module_name}.so
	    else
		warn "apxs utilily not found! Module $module_name was NOT enabled."
	    fi
	;;

	linux_suse_*)
		if ! grep -q "^APACHE_MODULES=.*${module_name}" /etc/sysconfig/apache2; then
			if sed -r "s/^(APACHE_MODULES=.*)\".*$/\\1 ${module_name}\"/" 					/etc/sysconfig/apache2 > /etc/sysconfig/apache2.new ; then
				mv -f /etc/sysconfig/apache2.new /etc/sysconfig/apache2
			else
				warn "Could now add ${module_name} to apache modules list"
				warn "Please edit /etc/sysconfig/apache2 to enable the feature"
			fi
		fi
	;;

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

	linux_*)
		cat ${apache_httpd_conf} | 			perl -e '
				@lines = <STDIN>;
				$found = 0;
				$lastline = 0;
				for ($i=0; $i<=$#lines; $i++)
				{
					if ( @lines[$i] =~ /^\s*?#\s*?LoadModule.*@ARGV[0]_module.*mod_@ARGV[0].so/ )
					{
						if ( $found > 0 || $deep > 0 )
						{
							@lines[$i] =~ s/^(.*)$/####This line was duplicated: $1/;
						}else{
							@lines[$i] =~ s/^\s*?#\s*?L/L/;
							$found++;
						}
					}
					elsif ( @lines[$i] =~ /^\s*?(LoadModule.*@ARGV[0]_module.*mod_@ARGV[0].so)/ )
					{
						if ( $found > 0 || $deep > 0 )
						{
							@lines[$i] =~ s/^(.*)$/####This line was duplicated: $1/;
						}else{
							$found++;
						}
					}
					elsif ( @lines[$i] =~ /^[^#\s]*?<If/ )
					{
						$deep++;
					}
					elsif ( @lines[$i] =~ /^[^#\s]*?<\/If/ )
					{
						$deep--;
					}
					if ( @lines[$i] =~ /LoadModule.*_module.*mod_.*so/  && $deep <= 0 )
					{
						$lastline = $i;
					}
				}
				if ( $found == 0 && $lastline > 0 )
				{
					print @lines[0..$lastline];
					print "LoadModule @ARGV[0]_module @ARGV[1]/mod_@ARGV[0].so\n";
					print @lines[$lastline+1..$#lines];
				}else{
					print @lines;
				}
			' "${module_name}" "${apache_modules_d}" 		> ${apache_httpd_conf}.new
		mv ${apache_httpd_conf}.new ${apache_httpd_conf}
	;;

	*)
		warn "$module_name was NOT enabled. Unsupported operating system"
	esac
}

true apache_status_linux_debian apache_stop_BSD

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
}

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

install_suexec()
{
	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 -fvp $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_D/httpd -V | grep -q SUEXEC_BIN
		if [ "$?" -ne "0" ]; then 
		    add_apache_module "suexec"
		fi
	    ;;
	    *)
		    add_apache_module "suexec"
	    ;;
	esac
}

set_upgrade_apache_params_131()
{
	PREV_APACHE_ROOT_D="$PREV_PRODUCT_ROOT_D/apache"
	PREV_HTTPD_VHOSTS_D="$PREV_APACHE_ROOT_D/vhosts"
}

upgrade_apache_131()
{
	p_echo
	p_echo
	p_echo "===> Upgrading Apache Server"
	
	set_upgrade_apache_params_131

	move_apache_certificate_131

	move_skel_131

	move_defaults_131

	upgrade_vhosts_131

	update_vhosts_conf_131

}

move_apache_certificate_131()
{
	# move sertificate
	inten="move Apache SSL Certificate file"
	echo_try "$inten"
	cp -f "$PREV_APACHE_ROOT_D/conf/httpsd.pem" "$APACHE_CERT" >> "$product_log" 2>&1 && suc || die "$inten"

	inten="change Certificate file owner and mode"
	set_ac root 0 400 "$APACHE_CERT"
}

move_skel_131()
{
	# move skeleton for vhosts
	inten="move .skel to a new location"
	echo_try "$inten"

	if [ -d "$PREV_APACHE_ROOT_D/skel" ]; then
		if [ -d "$PREV_HTTPD_VHOSTS_D/.skel" ]; then
			rm -rf "$PREV_HTTPD_VHOSTS_D/.skel"
		fi
		mv -f "$PREV_APACHE_ROOT_D/skel" "$PREV_HTTPD_VHOSTS_D/.skel" >> "$product_log" 2>&1 || die "$inten"
	else
		mkdir -p "$PREV_HTTPD_VHOSTS_D/.skel" >> "$product_log" 2>&1 || die "$inten"
	fi

	if [ ! -d "$PREV_HTTPD_VHOSTS_D/.skel/error_docs" ]; then
		mv -f "$HTTPD_VHOSTS_D/.skel/error_docs" "$PREV_HTTPD_VHOSTS_D/.skel/error_docs" >> "$product_log" 2>&1 || die "$inten"
	fi
	if [ ! -d "$PREV_HTTPD_VHOSTS_D/.skel/cert" ]; then
		mv -f "$HTTPD_VHOSTS_D/.skel/cert" "$PREV_HTTPD_VHOSTS_D/.skel" >> "$product_log" 2>&1 || die "$inten"
	fi
	if [ ! -d "$PREV_HTTPD_VHOSTS_D/.skel/httpdocs" ]; then
		mv -f "$HTTPD_VHOSTS_D/.skel/httpdocs" "$PREV_HTTPD_VHOSTS_D/.skel/" >> "$product_log" 2>&1 || die "$inten"
	else
		if [ ! -d "$PREV_HTTPD_VHOSTS_D/.skel/httpdocs/webstat" ]; then
			mv -f "$HTTPD_VHOSTS_D/.skel/httpdocs/webstat" "$PREV_HTTPD_VHOSTS_D/.skel/httpdocs/" >> "$product_log" 2>&1 || die "$inten"
		fi
	fi

	rm -rf "$HTTPD_VHOSTS_D/.skel" || die "$inten"

	suc
}

move_defaults_131()
{
	# move defaults for vhosts
	inten="move defaults to a new location"
	echo_try "$inten"

	if [ ! -d "$PREV_HTTPD_VHOSTS_D/default" ]; then
		mkdir "$PREV_HTTPD_VHOSTS_D/default"  >> $product_log 2>&1 || die "$inten"
	fi

	if [ -d "$PREV_APACHE_ROOT_D/htdocs" ]; then
		if [ -d "$PREV_HTTPD_VHOSTS_D/default/htdocs" ]; then
			rm -rf "$PREV_HTTPD_VHOSTS_D/default/htdocs"
		fi
		mv -f "$PREV_APACHE_ROOT_D/htdocs" "$PREV_HTTPD_VHOSTS_D/default" >> "$product_log" 2>&1 || die $inten
	else
		mkdir -p "$PREV_HTTPD_VHOSTS_D/default/htdocs" >> "$product_log" 2>&1 || die $inten
	fi

	if [ -d "$PREV_APACHE_ROOT_D/httpsdocs" ]; then
		if [ -d "$PREV_HTTPD_VHOSTS_D/default/httpsdocs" ]; then
			rm -rf "$PREV_HTTPD_VHOSTS_D/default/httpsdocs"
		fi
		mv -f "$PREV_APACHE_ROOT_D/httpsdocs" "$PREV_HTTPD_VHOSTS_D/default" >> "$product_log" 2>&1 || die $inten
	else
		mkdir -p "$PREV_HTTPD_VHOSTS_D/default/httpsdocs" >> "$product_log" 2>&1 || die $inten
	fi

	if [ -d "$PREV_APACHE_ROOT_D/cgi-bin" ]; then
		if [ -d "$PREV_HTTPD_VHOSTS_D/default/cgi-bin" ]; then
			rm -rf "$PREV_HTTPD_VHOSTS_D/default/cgi-bin"
		fi
		mv -f "$PREV_APACHE_ROOT_D/cgi-bin" "$PREV_HTTPD_VHOSTS_D/default" >> "$product_log" 2>&1 || die $inten
	else
		mkdir -p "$PREV_HTTPD_VHOSTS_D/default/cgi-bin" >> "$product_log" 2>&1 || die $inten
	fi

	# change default page logo if it is not changed
	local logo_file_size

	PREV_HTTP_LOGO="$PREV_HTTPD_VHOSTS_D/default/htdocs/logo.gif"
	NEW_HTTP_LOGO="$HTTPD_VHOSTS_D/default/htdocs/logo.gif"

	if [ -f "$PREV_HTTP_LOGO" ]; then
		# logo.gif exists - check the size
		logo_file_size=`ls -l "$PREV_HTTP_LOGO" | awk '{print $5}'`
		if [ "X$logo_file_size" = "X2776" ]; then
			# logo not changed, replace it
			mv "$NEW_HTTP_LOGO" "$PREV_HTTP_LOGO"
		fi
	fi


	PREV_HTTPS_LOGO="$PREV_HTTPD_VHOSTS_D/default/httpsdocs/logo.gif"
	NEW_HTTPS_LOGO="$HTTPD_VHOSTS_D/default/httpsdocs/logo.gif"

	if [ -f "$PREV_HTTPS_LOGO" ]; then
		# logo.gif exists - check the size
		logo_file_size=`ls -l "$PREV_HTTPS_LOGO" | awk '{print $5}'`
		if [ "X$logo_file_size" = "X2776" ]; then
			# logo not changed, replace it
			mv "$NEW_HTTPS_LOGO" "$PREV_HTTPS_LOGO"
		fi
	fi

	rm -rf "$HTTPD_VHOSTS_D/default"

	suc
}

upgrade_vhosts_131()
{

	# for each domain with hosting
	inten="upgrade domains with hosting accounts"
	echo_try "$inten"

	query="select name from domains where htype='vrt_hst'"
	for dom_name in `echo $query | $mysql`; do

		local dom_dir
		dom_dir="$PREV_HTTPD_VHOSTS_D/$dom_name"

		# define system user for domain
		query1="select h.login from hosting h, domains d where d.id=h.dom_id and d.name='$dom_name'";
		dom_user=`echo $query1 | $mysql`


		# mkdir & set_ac for webstat directory
		if [ ! -d "$dom_dir/httpdocs/webstat" ]; then
			cp -pr "$PREV_HTTPD_VHOSTS_D/.skel/httpdocs/webstat" "$dom_dir/httpdocs/" >> "$product_log" 2>&1
		fi

		if [ -d "$dom_dir/httpdocs/webstat" ]; then
			set_ac $dom_user $clients_group 755 "$dom_dir/httpdocs/webstat"
			set_ac $dom_user $clients_group 755 `get_ls full "$dom_dir/httpdocs/webstat"`
		fi


		# rename webusers directory
		if [ -d "$dom_dir/webusers" ]; then
		    mv -f "$dom_dir/webusers" "$dom_dir/web_users"  >> "$product_log" 2>&1
		fi

		if [ ! -e "$dom_dir/conf" ]; then
		    mkdir "$dom_dir/conf" >> "$product_log" 2>&1
		fi

		# rename vhosts certificates
		if [ -f "$dom_dir/cert/httpsd.pem" ]; then
		    mv -f "$dom_dir/cert/httpsd.pem" "$dom_dir/cert/httpd.pem" >> "$product_log" 2>&1
		fi

		# change filename for protected directory
		cd "$dom_dir/pd" || die
		for pd_file in `get_ls brief "$dom_dir/pd"` ; do
			new_pd_file="d`echo "$pd_file" | sed -e 's/-/\.\./g'`"
			mv -f -- "$pd_file" "$new_pd_file" >> "$product_log" 2>&1 || die $inten
		done

		# create directory for error documents
		if [ ! -d "$dom_dir/error_docs" ]; then
			mkdir "$dom_dir/error_docs" >> "$product_log" 2>&1 || die $inten
		fi
		set_ac root 0 755 "$dom_dir/error_docs"

		# copy default error documents
		cp -rp `get_ls full "$PREV_HTTPD_VHOSTS_D/.skel/error_docs"` "$dom_dir/error_docs"
		set_ac "$dom_user" "$clients_group" 755 `get_ls full "$dom_dir/error_docs"`


		# create dirs anon_ftp, anon_ftp/pub, anon_ftp/incoming and chmod 755 on cgi_bin
		local anon_ftp_d
		anon_ftp_d="$dom_dir/anon_ftp"

		if [ ! -d "$anon_ftp_d" ]; then
			mkdir "$anon_ftp_d" >> "$product_log" 2>&1 || die $inten
		fi
		set_ac $dom_user $clients_group 755 "$anon_ftp_d" 

		if [ ! -d "$anon_ftp_d/pub" ]; then
			mkdir "$anon_ftp_d/pub" >> "$product_log" 2>&1 || die $inten
		fi
		set_ac $dom_user $clients_group 755 "$anon_ftp_d/pub"

		if [ ! -d "$anon_ftp_d/incoming" ]; then
			mkdir "$anon_ftp_d/incoming" >> "$product_log" 2>&1 || die $inten
		fi
		set_ac $dom_user $clients_group 777 "$anon_ftp_d/incoming"

	done && suc || die "$inten"
}



update_vhosts_conf_131()
{
	# sed $prod_conf_t on HTTPD_VHOSTS_D
	inten="update $PRODNAME configuration"
	echo_try "$inten"
	sed -e "s|HTTPD_VHOSTS_D.*|HTTPD_VHOSTS_D		$PREV_HTTPD_VHOSTS_D|g" \
		< "$prod_conf_t" > "$prod_conf_t.tmp" && \
		mv -f "$prod_conf_t.tmp" "$prod_conf_t" && suc || die "$inten"

	# restart apache
	p_echo
	inten="reconfigure and restart apache"
	echo_try "$inten"
	$UTILS_DIR/websrvmng >> "$product_log" 2>&1 && suc || die $inten
}

rebuild_protected_directories_500()
{
	local dom_id dom_name pd_config_path pd_path directory_type

	inten="rebuild protected directories"
	echo_try "$inten"

	# erase current protected directories config files
	query="select id from domains, hosting where domains.id=hosting.dom_id"
	for dom_id in `echo $query | $mysql`; do

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

		pd_config_path="${HTTPD_VHOSTS_D}/${dom_name}/pd"

		rm -f "${pd_config_path}"/*

		# select all protected directories for current domain
		query="select id from protected_dirs where dom_id='${dom_id}'"
		pd_list=`echo $query | $mysql`

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

			for pd_id in ${pd_list}; do

				query="select dom_id from protected_dirs where id='${pd_id}'";
				dom_id=`echo $query | $mysql`

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

				query="select path from protected_dirs where id='${pd_id}'";
				dir_path=`echo $query | $mysql`

				query="select ssl from protected_dirs where id='${pd_id}'";
				dir_ssl=`echo $query | $mysql`

				if [ "X${dir_ssl}" = "Xtrue" ]; then
					directory_type="https"
				else
					directory_type="http"
				fi

				query="select sys_users.login from hosting, sys_users, protected_dirs
					 where hosting.sys_user_id=sys_users.id and
					 protected_dirs.dom_id=hosting.dom_id and
					 protected_dirs.id='${pd_id}'"
				hosting_user=`echo $query | $mysql`

				"$PRODUCT_ROOT_D/admin/sbin/pdmng" --add-protection \
						"--user-name=$hosting_user" \
						"--vhost-name=${dom_name}" \
						"--type=${directory_type}" \
						"--directory=${dir_path}" \
					|| die "generate new config of protected directory ${full_pd_path}"

				query="select id from pd_users where pd_id='${pd_id}'"

				for pduser_id in `echo $query | $mysql`; do

					query="select login from pd_users where id='${pduser_id}'"
					pd_user_login=`echo $query | $mysql`

					query="select passwd from pd_users where id='${pduser_id}'"
					pd_user_passwd=`echo $query | $mysql`


					PSA_PASSWORD="${pd_user_passwd}" "$PRODUCT_ROOT_D/admin/sbin/pdmng" --add-user \
							"--vhost-name=${dom_name}" \
							"--directory=${dir_path}" \
							"--user-name=${pd_user_login}" \
						|| die "add ${pd_user_login} to protected directory ${full_pd_path}"
				done

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

}

add_mod_python_directive_500()
{
	local have_loadmodule have_addmodule include_directive

	# search mod_python directive in config file
	have_loadmodule=`cat ${apache_httpd_conf} | grep -E '^LoadModule.*python_module.*mod_python.so$'`
	have_addmodule=`cat ${apache_httpd_conf} | grep -E '^AddModule.*mod_python.c$'`

	if [ "X${have_loadmodule}" = "X" -o "X${have_addmodule}" = "X" ]; then
		# one or two directives are absent, need to insert them into config file

		# include directive must be last directive in config file
		include_directive=`cat ${apache_httpd_conf} | grep -E '^Include.*httpd.include$'`
		cat ${apache_httpd_conf} | grep -v -E '^Include.*httpd.include$' > ${apache_httpd_conf}.parsed
		mv -f ${apache_httpd_conf}.parsed ${apache_httpd_conf}

		if [ "X${have_loadmodule}" = "X" ]; then
			case "$machine" in
				BSD*)
					echo "LoadModule python_module      libexec/mod_python.so" >> ${apache_httpd_conf}
					;;
				*)
					echo "LoadModule python_module      modules/mod_python.so" >> ${apache_httpd_conf}
					;;
			esac
		fi

		if [ "X${have_addmodule}" = "X" ]; then
			echo "AddModule mod_python.c" >> ${apache_httpd_conf}
		fi

		echo "" >> ${apache_httpd_conf}
		echo "${include_directive}" >> ${apache_httpd_conf}
	fi
}
upgrade_apache_600()
{
	# for red hat linux, it is required for apache to have 48 GID
	if [ "X${machine}" = "Xlinux" -a "X${linux_distr}" = "Xredhat" ]; then

		# get apache group id
		existing_apache_group=`cat /etc/group | grep "^apache" | cut -d ":" -f 3`
		if [ "X${existing_apache_group}" != "X" ]; then

			# for mailman, it is required for apache to have 40 GID
			if [ 0${existing_apache_group} -ne 48 ]; then
				groupmod -g 48 apache
				usermod -g 48 apache
				find "${PRODUCT_ROOT_D}" -group ${existing_apache_group} -exec chgrp apache {} \;
			fi
		fi
	fi
}

upgrade_apache_800()
{

	if [ "X$machine" = "XDarwin" ]; then
		p_echo " Changing user and group for Apache server..."
		mk_backup $apache_httpd_conf cp f
		sed -e "s|^User[[:space:]]*apache$|User $apache_user|g" \
			-e "s|^Group[[:space:]]apache|Group $apache_group|g" -i "" $apache_httpd_conf

		find $HTTPD_VHOSTS_D/ -group 80 -exec chown :$apache_group {} \;
		find $HTTPD_VHOSTS_D/ -user apache -exec chown $apache_user: {} \;

		suc


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

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
}

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
}

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 acconts"
	warn "register $prg in chrooted environment"
}

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

	case "`uname -s`" in
	Darwin|Rhapsody) return;;
	esac

	filetype=`file -ib "$prg"`

	case "$filetype" in
	application/x-executable*statically' 'linked*)
		;;
	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

	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"
	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"
	
	if test -d "$CHROOT_ROOT_D/etc"; then
		"$PRODUCT_ROOT_D/admin/sbin/chrootmng" \
				--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
		fail
		echo "Warning: sftp-server binary not found" >> "$product_log"
		echo "+ sftp connections will not be available for shrooted accounts" >> "$product_log"
	fi

	suc
	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
	install_chroot_program "$CHROOT_ROOT_D$sftp_path" "$libdir" "$libdir64"
	
	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
		;;
	*) die "unknown system $os" ;;
	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
	
	"$PRODUCT_ROOT_D/admin/sbin/chrootmng" \
			--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
}
fix_networking_debian()
{
        interfaces_file="/etc/network/interfaces"
		
        [ -f "$interfaces_file" ] && sed -e "s|allow-hotplug|auto|g" \
                "$interfaces_file" > "$interfaces_file.tmp" \
        && mv -f "$interfaces_file.tmp" "$interfaces_file" \
        && chmod 644 "$interfaces_file"
}
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
}



upgrade_after_131()
{
 
	p_echo
	p_echo
	p_echo "===> Post Upgrading"
	
	# create sendmail links
	ln -fs "$QMAIL_ROOT_D/bin/sendmail" "$sendmail" || die "ln -fs $QMAIL_ROOT_D/bin/sendmail $sendmail"
	ln -fs "$QMAIL_ROOT_D/bin/sendmail" "/usr/lib/sendmail" || die "ln -fs $QMAIL_ROOT_D/bin/sendmail /usr/lib/sendmail"
	
	# remove startup script
	remove_prev_startup_scripts_131

	# remove old files
	remove_prev_version_131

	upgrade_reconfig_131

	ntpdate_fix_131
}


ntpdate_fix_131()
{
	if [ "X$machine" != "Xlinux" ]; then
		return 0
	fi

	ntpdate_bin="/usr/sbin/ntpdate"
	
	# only linux
	if [ -f "$ntpdate_bin" ]; then
		if [ ! -x "$ntpdate_bin" ]; then
			inten="fix ntpdate pemission problem"
			echo_try "$inten"
			chmod +x "$ntpdate_bin" >> "$product_log" 2>&1 && suc || die "$inten"
		fi
	fi

	return 0
}


remove_prev_startup_scripts_131()
{
#	cd "$PRODUCT_ROOT_D" >> $product_log 2>&1

	case "$machine" in
		BSD)
			rm -f "/usr/local/etc/rc.d/${prev_product}.sh" >> "$product_log" 2>&1
#			rsr_backup /etc/rc.conf cp f
			;;
#		BSDI)
#			if [ -f /etc/rc.local.${prev_product} ]; then
#				cp -p  /etc/rc.local.${prev_product} /etc/rc.local >> $product_log 2>&1
#			fi
#			;;
		linux)
		    case "$linux_distr" in
			redhat)
#				chkconfig --del ${prev_product}
				rm -f /etc/rc.d/init.d/${prev_product} >> $product_log 2>&1
				rm -f /etc/rc.d/rc0.d/K15${prev_product} >> $product_log 2>&1
				rm -f /etc/rc.d/rc1.d/K15${prev_product} >> $product_log 2>&1
				rm -f /etc/rc.d/rc2.d/K15${prev_product} >> $product_log 2>&1
				rm -f /etc/rc.d/rc3.d/S77${prev_product} >> $product_log 2>&1
				rm -f /etc/rc.d/rc4.d/S77${prev_product} >> $product_log 2>&1
				rm -f /etc/rc.d/rc5.d/S77${prev_product} >> $product_log 2>&1
				rm -f /etc/rc.d/rc6.d/K15${prev_product} >> $product_log 2>&1
				;;
#			slackware)
#			    if [ -f /etc/rc.d/rc.local.${prev_product} ]; then
#				cp -p  /etc/rc.d/rc.local.${prev_product} /etc/rc.d/rc.local >> $product_log 2>&1
#			    fi
#				;;
		    esac
		    ;;
#		solaris)
#			rm -f  /etc/init.d/${prev_product} >> $product_log 2>&1
#			if [ -f /etc/rc0.d/K01${prev_product} ]; then
#				rm -f /etc/rc0.d/K01${prev_product} >> $product_log 2>&1
#			fi
#			
#			if [ -f /etc/rc1.d/K01${prev_product} ]; then
#				rm -f /etc/rc1.d/K01${prev_product} >> $product_log 2>&1
#			fi
#
#			if [ -f /etc/rc2.d/S77${prev_product} ]; then
#				rm -f /etc/rc2.d/S77${prev_product} >> $product_log 2>&1
#			fi
#			;;
	esac
}

remove_prev_version_131()
{
	# remove plesk root exept /usr/local/plesk/apache/vhosts
	cd "$PREV_PRODUCT_ROOT_D" >> "$product_log" 2>&1 || die "cd $PREV_PRODUCT_ROOT_D"
	
	rm -rf admin frontpage mysql plesk.sh qmail stunnel ftpd namedb plesk_license.txt reconfigurator.sh version bin >> "$product_log" 2>&1

	cd "$PREV_PRODUCT_ROOT_D/apache" >> "$product_log" 2>&1 || die "cd $PREV_PRODUCT_ROOT_D/apache"
	
	rm -rf LICENSE.apache bin conf httpsdocs include libexec man skel LICENSE.php cgi-bin htdocs icons lib logs proxy >> "$product_log" 2>&1


	# remove xinetd *.plesk files
	if [ "X$xinetd_dir" != "X" -a "X$xinetd_dir" != "X/" ]; then
		rm -f ${xinetd_dir}/*.${prev_product} >> "$product_log" 2>&1
	fi

	pleskrc superserver restart
}

upgrade_reconfig_131()
{
	inten="finish cofiguration"
	echo_try "$inten"
	"$UTILS_DIR/reconfig" "$host" "$domain" >> "$product_log" 2>&1 && suc || die "$inten"
}
    

upgrade_common_131()
{
	p_echo
	p_echo "===> Upgrading Common"
	
	# chmod shadow
	case "$machine" in
    	linux)
        	chmod 400 /etc/shadow   >> $product_log 2>&1
        	;;
	esac

	# move password file
	inten="move password file"
	echo_try "$inten"
	cp -f "$prev_mysql_passwd_file" "$mysql_passwd_file" >> "$product_log" 2>&1 && suc || die $inten
	chown $admin_user:$admin_group $mysql_passwd_file || die
	chmod 600 $mysql_passwd_file || die

	# change clients group
	change_clients_group_131

}

change_clients_group_131()
{
	# check exists source group
	grp_res=`egrep "^$prev_clients_group:" /etc/group`
	if [ "X$grp_res" = "X" ]; then
#		p_echo " Group '$prev_clients_group' not exists"
#		p_echo " It is necessary to add source group '$prev_clients_group'"
		chgrp -R $clients_group $PREV_PRODUCT_ROOT_D/apache/vhosts/*.*/httpdocs >> $product_log 2>&1
		chgrp -R $clients_group $PREV_PRODUCT_ROOT_D/apache/vhosts/*.*/httpsdocs >> $product_log 2>&1
		chgrp -R $clients_group $PREV_PRODUCT_ROOT_D/apache/vhosts/*.*/cgi-bin  >> $product_log 2>&1
	else
		delete_group $clients_group
		group_mod $prev_clients_group $clients_group
	fi
}
upgrade_dumpd_500()
{
	local dom_list dom_name domain_dump_d

	inten="setup domains for new backup feature"

	conf_setval "${prod_conf_t}" DUMP_D "${DEFAULT_DUMP_D}"
	DUMP_D="${DEFAULT_DUMP_D}"

	chown ${admin_user}:${admin_group} "${DUMP_D}"
	chmod 700 "${DUMP_D}"

	query="SELECT id FROM domains"

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

	for dom_id in ${dom_list}; do

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

		domain_dump_d=${DUMP_D}/${dom_name}

		if [ -e ${domain_dump_d} ]; then
		    if [ ! -d ${domain_dump_d} ]; then
			# there is a some file exist in dumps directory
			# rename file and create required directory
			# it is very rare situation, i suppose.
			mv -f ${domain_dump_d} ${domain_dump_d}.saved_by_psa_upgrader || die "backup ${domain_dump_d} file for replacing it by domain backup directory"
			mkdir "${domain_dump_d}" || die ${inten}
		    fi

		    # directory already exists, do nothing.
		else
		    mkdir "${domain_dump_d}" || die ${inten}
		fi

		chown ${admin_user}:${admin_group} "${domain_dump_d}"
		chmod 700 "${domain_dump_d}"

	done
}

remove_reconfigurator_500()
{
	rm -f ${PRODUCT_ROOT_D}/bin/reconfigurator.sh
}
upgrade_test_backup_600()
{
	test -x "$PRODUCT_ROOT_D/bin/psadump" && \
	    "$PRODUCT_ROOT_D/bin/psadump" --version 2>&1 | grep -q '^Back.* for [[:alpha:]]\+ v6\.0'
}

upgrade_remove_utils_600()
{
	rm -f ${UTILS_DIR}/ntp
	rm -f ${UTILS_DIR}/set_sys_time
	rm -f ${UTILS_DIR}/fp_wrapper

	if upgrade_test_backup_600; then
		rm -f "$PRODUCT_ROOT_D/bin/psadump" "$PRODUCT_ROOT_D/bin/psadumpctl" \
			"$PRODUCT_ROOT_D/bin/psarestore"  \
			"$ADMIN_ROOT/bin/domain_bu" "$ADMIN_ROOT/sbin/domain_bu"
	fi
}


remove_old_creation_utilities_700()
{
	old_cu_files="client.pl client_pref.pl domain.pl domain_pref.pl mail.pl cu_lib.pl"
	for i in $old_cu_files; do
		rm -f $PRODUCT_ROOT_D/bin/$i > /dev/null 2>&1
	done
}
upgrade_users_710()
{
    ch_user_home psaadm /
}

upgrade_common_752()
{
	if [ "X$machine" = "XBSD" ]; then
		fix_dumpdir_perms_752
	fi
}

fix_dumpdir_perms_752()
{
	### fix permissions for dump dirs

	if [ -z "$DUMP_D" ]; then
		return;
	fi

	find $DUMP_D -type d -mindepth 1 -maxdepth 1 | while read dom_dir; do
		chown -h psaadm:psaadm $dom_dir
		chown -h root:psaadm $dom_dir/*
	done
}
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_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
}
update_components_table()
{
	if [ "X${do_upgrade}" != "X1" ]; then
		return
	fi

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

	db_do --inten "$inten" "DELETE FROM Components"
	suc

	packagemng_set_dirty_flag
}

install_key_d()
{
	mkdir_ex 0 0 755 "$product_etc/key.d"
}


#courier-imap

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

	courier_service="courier-imap"
}

install_cron_somely()
{
    install_cron_somely_perform
}

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


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

install_cron_somely_entry()
{
	run_parts="$PRODUCT_ROOT_D/bin/run-parts.sh"
	add_to_crontab "$1 $run_parts $CRON_SOMELY_DIR_PREFIX.$2" \
		"$run_parts" "$CRON_SOMELY_DIR_PREFIX.$2" "root" "add $2 task"
}

install_cron_backup()
{
	minutes=`get_random_number 15`

	add_to_crontab "$minutes,`expr $minutes + 15`,`expr $minutes + 30`,`expr $minutes + 45`	*	*	*	*	$PRODUCT_ROOT_D/admin/sbin/backupmng >/dev/null 2>&1" "$PRODUCT_ROOT_D/admin/sbin/backupmng" "" "root" "install Backup Manager task"
}

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
}

# upgrade_crontab.sh

upgrade_crontab_131()
{	
	p_echo
	p_echo "===> Upgrading Crontab"
	 
	inten="fetch crontab"
	echo_try "$inten"
	$crontab -l > "/tmp/crontab.${product}" 2>>"$product_log" && suc || die "$inten"

	inten="remove old crontab records"
	echo_try "$inten"
	sed -e "s|^.*/${prev_product}/admin/utils/statistics.*||g" \
 		-e "s|^.*/${prev_product}/bin/mysqldump.sh.*||g" \
		< "/tmp/crontab.${product}" > "/tmp/crontab.${product}.new" 2>>"$product_log" && suc || die "$inten"

	inten="install updated crontab"
	echo_try "$inten"
	$crontab "/tmp/crontab.${product}.new"  >> "$product_log" 2>&1 && suc || die "$inten"

	inten="remove temporary files"
	echo_try "$inten"
	rm -f "/tmp/crontab.${product}"* >> "$product_log" 2>&1 && suc || warn "$inten"
}
crontab_710_fix_wday()
{
    local cron_file inten
    cron_file=`mktemp /tmp/cronXXXXXX`
    inten="fix Crontab"

    $crontab -l | \
     sed 's|^[[:space:]]*\([-0-9/,\*]\{1,\}\)[[:space:]]*\([-0-9/,\*]\{1,\}\)[[:space:]]*\([-0-9/,\*]\{1,\}\)[[:space:]]*\([-0-9/,\*]\{1,\}\)[[:space:]]*7[[:space:]]*\(\('"$PRODUCT_ROOT_D"'/mysqldump\.sh\|'"$PRODUCT_ROOT_D"'/admin/sbin/statistics\|/usr/sbin/ntpdate\).*\)$|\1\t\2\t\3\t\4\t*\t\5|' >$cron_file || die "$inten"
    $crontab $cron_file || die "$inten"
}

upgrade_crontab_710()
{
    pnnl_echo "Upgrading crontab"
    crontab_710_fix_wday
    suc
}

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
}

rebuild_ip_pool()
{
	if [ "X${do_upgrade}" != "X1" ]; then
		inten="reread IP addresses from network interfaces"
		echo_try $inten

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

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_ETC_D/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_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_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_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\""
}

# workaround for old Plesks
db_mysql_check_upgrade_prepare_old()
{
	if db_test "SHOW TABLES" '/^sa_list$/'; then
		db_select "SHOW INDEX FROM sa_list"
		for idx in `echo "$db_select_output" | awk -F '\t' '{print $3}' | sort -u`
		do
			db_do 'ALTER TABLE sa_list DROP KEY `'"$idx"'`'
		done
	fi
}

db_mysql_check_upgrade()
{
	if $PRODUCT_ROOT_D/admin/bin/php </dev/null 2>>"$product_log"; then
		$PRODUCT_ROOT_D/bin/mysql41upgrade --upgrade -report $product_log 2>>"$product_log"
		$PRODUCT_ROOT_D/admin/bin/php -r '
			define("PRODUCT_VERSION", "psa-'"$product_version"'-'"$product_build"'");
			define("LMSG_DEBUG_ON", FALSE);
			require_once("MySQL5FixBinaryColumns.php");
			MySQL5FixBinaryColumns::run();
		' 2>>"$product_log"
	else
		echo "Skip MySQL upgrade adaptations as the interpreter is not configured yet" >>"$product_log"
	fi
	mysql41_init
}

db_create_default_templates()
{
	$PRODUCT_ROOT_D/bin/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()
{
	$PRODUCT_ROOT_D/bin/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 manyally"
}

# upgrade product database

upgrade_db_131()
{
	p_echo
	p_echo
	p_echo "===> Upgrading MySQL Database"

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

	pleskrc mysql stop

	restore_db_131

	pleskrc mysql start

	add_changes_131

	move_data_131

	remove_old_131

	insert_fullhost_131
}

restore_db_131()
{
	inten="move MySQL databases to a new location"
	echo_try "$inten"
	rm -rf `get_ls full "$mysql_dbdir"`
	mv -f `get_ls full "${PREV_PRODUCT_ROOT_D}/mysql/var/"` "$mysql_dbdir" >> "$product_log" 2>&1 && suc || die $inten

	inten="rename 'plesk' database to '$product'"
	echo_try "$inten"
	mv -f "$mysql_dbdir/plesk" "$mysql_dbdir/$PRODNAME" >> "$product_log" 2>&1 && suc || die $inten

	inten="change files modes"
	echo_try "$inten"
	chmod -R 700 "$mysql_dbdir" >> "$product_log" 2>&1 && suc || die $inten

	inten="change files owners"
	echo_try "$inten"
	chown -R $mysql_user:$mysql_group "$mysql_dbdir" >> "$product_log" 2>&1 && suc || die $inten
}

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

move_data_131()
{
	move_sizes_131
	move_databases_131
	move_clients_rights_131
	move_ntp_131
}

move_sizes_131()
{
	# move sizes from hosting to domains
	inten="move size limits to domain level"
	echo_try "$inten"

	# 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 size from hosting where dom_id='$dom_id'";
		size=`echo $query1 | $mysql`;

		query1="select real_size from hosting where dom_id='$dom_id'";
		real_size=`echo $query1 | $mysql`;

		query1="update domains set size='$size', real_size='$real_size' where id='$dom_id'";
		echo $query1 | $mysql;

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

move_databases_131()
{
	# move mysql databases and users names
	inten="applay changes in MySQL databases management"
	echo_try "$inten"

	query="select d.id from domains d, hosting h where d.id=h.dom_id and h.mysql='true'";

	for dom_id in `echo $query | $mysql`; do

		query1="select login from hosting where dom_id='$dom_id'";
		login=`echo $query1 | $mysql`;

		query1="select passwd from hosting where dom_id='$dom_id'";
		passwd=`echo $query1 | $mysql`;

		query1="insert into data_bases (name, type, dom_id) values('$login', 'mysql', '$dom_id')"
		query2="select LAST_INSERT_ID()"
		db_id=`echo "$query1;$query2" | $mysql`

		query1="select passwd from hosting where dom_id='$dom_id'";
		passwd=`echo $query1 | $mysql`;


		query1="insert into db_users (login, passwd, db_id) values('$login', '$passwd', '$db_id')";
		echo $query1 | $mysql >> "$product_log" 2>&1 || die "$inten";

	done >> "$product_log" 2>&1 && suc || die "$inten"

}

move_clients_rights_131()
{
	# update clients rights
	inten="update clients rights"
	echo_try "$inten"


	query="select id from clients";
	for cl_id in `echo $query | $mysql`; do

		# if client has no domains do not allow to manage DNS and log rotation
		query1="select COUNT(*) from domains where cl_id='$cl_id'";
		dom_num=`echo $query1 | $mysql`
		if [ "X$dom_num" = "X0" ]; then
			continue;
		fi

		cl_manage_dns="true"
		cl_manage_log="true"

		query1="select id from domains where cl_id='$cl_id'";
		for dom_id in `echo $query1 | $mysql`; do
			
			query2="select val from dom_param where param='cl_manage_dns' and dom_id='$dom_id'";
			manage_dns=`echo $query2 | $mysql`;
			if [ "X$manage_dns" != "X1" ]; then
				cl_manage_dns="false";
			fi

			query2="select val from dom_param where param='cl_manage_log' and dom_id='$dom_id'";
			manage_log=`echo $query2 | $mysql`;
			if [ "X$manage_log" != "X1" ]; then
				cl_manage_log="false";
			fi

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

		if [ "X$cl_manage_dns" = "Xtrue" ]; then
			query1="replace cl_param (cl_id, param, val) values('$cl_id', 'manage_dns', 'true')"
			echo $query1 | $mysql >> "$product_log" 2>&1 || die "$inten";
		fi

		if [ "X$cl_manage_log" = "Xtrue" ]; then
			query1="replace cl_param (cl_id, param, val) values('$cl_id', 'manage_log', 'true')"
			echo $query1 | $mysql >> "$product_log" 2>&1 || die "$inten";
		fi
		

	done >> "$product_log" 2>&1 && suc || die "$inten"

}

move_ntp_131()
{
	# in PSA 1.3.1 there was one param in misc:
	# 'ntp' - IP address
	# in PSA after 2.0.0 two params:
	# 'ntp_enabled' - flag
	# 'ntp_server' - hostname or IP address

	query="select val from misc where param='ntp'";
	ntp=`echo $query | $mysql`;

	chk_ip "$ntp"

	if [ "X$common_var" != "X0" ]; then
		query="delete from misc where param='ntp'";
		echo $query | $mysql >> "$product_log" 2>&1
		return;
	fi

	query="update misc set param='ntp_server' where param='ntp'";
	echo $query | $mysql >> "$product_log" 2>&1

	query="replace into misc (param, val) values('ntp_enabled', 'true')";
	echo $query | $mysql >> "$product_log" 2>&1
}

remove_old_131()
{
	inten="remove old columns"
	echo_try "$inten"

	query="
		ALTER TABLE hosting 
			DROP COLUMN size
		,	DROP COLUMN real_size
		,	DROP COLUMN mysql
		;
		
		DELETE from dom_param where param='cl_manage_dns' or param='cl_manage_log';
		DELETE from misc where param='locale';
		";

	echo $query | $mysql && suc || die "$inten"

}

insert_fullhost_131()
{
	insert_fullhostname
}
# it's used in upgrade_db_500.sh
get_free_id()
{
	query="SELECT max(id) FROM $1;"
	common_var=`echo ${query} | $mysql`
	if [ $? -ne 0 ]; then
		die "get last identifier from table $1"
	fi

	if [ "X${common_var}" = "XNULL" ]; then
		common_var=0
	fi

	common_var=`expr ${common_var} + 1`
}

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()
{
	if [ "X${do_upgrade}" != "X1" ]; then

		inten="import default certificate"

		default_certificate=${certificate_file}

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

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

upgrade_locale_600()
{
	inten=" change locales to default values."
	pnnl_echo " Setting up locales... "
	$mysql <<-EOF && suc || die "$inten"
		replace into misc(param,val) values('def_locale','$default_locale');
	    	update clients set locale='$default_locale';
		delete from misc where param = 'admin_locale';
	    	delete from dom_param where param = 'user_locale';
	    	delete from mn_param where param = 'locale';
		delete from locales where id <> '$default_locale';
EOF
}

upgrade_db_600()
{
	p_echo
	p_echo
	p_echo "===> Upgrading MySQL Database from version 6.0 to 7.0"

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

	# primary database upgrade
	add_changes_600
	
	upgrade_locale_600
}


fix_catch_all_domain_preferences()
{
	local  mysql_exec_query dom_id dom_params_id query res row

	### select old "catch-all" preferences
	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")
			echo "DELETE FROM Parameters WHERE id='$dom_params_id' AND parameter IN ('nonexist_mail', 'bounce_mess', 'catch_addr')" | $mysql || warn "ERROR removing old parameters(from Parameters table) for domain with dom_id='$dom_id';"
		else
			### copy old "catch-all" preferences (from "domains" to "DomainServices")
			ds_params_id=`echo "INSERT INTO Parameters(parameter, value) VALUES('fake', 'fake'); select LAST_INSERT_ID();" | $mysql`
			echo "DELETE FROM Parameters WHERE parameter='fake';" | $mysql
			if [ "0$ds_params_id" -gt "0" ]; then
				### set id of parameters for DomainServices
				res=`echo "UPDATE DomainServices set parameters_id=$ds_params_id WHERE type='mail' AND dom_id=$dom_id;" | $mysql; echo $?`

				if [ "0$res" -eq "0" ]; then
					### move old "catch-all" preferences from "domains" to "DomainServices"
					query="UPDATE Parameters SET id=$ds_params_id WHERE id=$dom_params_id AND parameter IN ('nonexist_mail', 'bounce_mess', 'catch_addr');"
		 			res=`echo "$query" | $mysql; echo $?`
					if [ "0$res" -ne "0" ]; then
						echo "ERROR: unable to move catch-all preferences from \"domains\" tp \"DomainServices\" table for domain with dom_id=$dom_id"
						continue;
					fi
				else
					echo "ERROR: unable to update DomainServices table for domain with dom_id=$dom_id"
					continue;
				fi
			else
				echo "ERROR: unable to insert into Parameters (dom_id=$dom_id, dom_params_id=$dom_params_id)"
				continue;
			fi
		fi
	done
}

fix_site_app_dbresources()
{
	local  query dom_id db_id

	query="SELECT sd.dom_id, db.id from subdomains sd, data_bases db, SiteApps sa, SiteAppResources sar WHERE sd.id=sa.dom_id AND sa.dom_type=\"subdomain\" AND sa.id=sar.app_id AND sar.type=\"database\" AND sar.res_id=db.id AND db.dom_id!=sd.dom_id;"
	for i in `echo "$query" | $mysql | awk '{print $1","$2}'`; do
		dom_id=`echo $i | sed -e 's/^\([0-9][0-9]*\),.*$/\1/'`
		db_id=`echo $i | sed -e 's/^[^,]*,\([0-9][0-9]*\)$/\1/'`
		query="UPDATE data_bases SET dom_id='$dom_id' WHERE id='$db_id';"
		echo "$query" | $mysql || warn "ERROR: unable to fix site app database (dom_id=$dom_id, db_id=$db_id)"
	done
}

siteapps_syncdb()
{
	### sync db and cgitory dir
	siteapps_syncdb_script="$PRODUCT_ROOT_D/admin/plib/cu/siteapps_syncdb.php"
	if [ -f "$siteapps_syncdb_script" ]; then
		$PRODUCT_ROOT_D/admin/bin/php $siteapps_syncdb_script >> "$product_log" 2>&1
	fi
}

add_fixes_700()
{
	db_fix_del_column SiteAppPackages requires_id
	db_fix_del_column SiteAppPackages params_id

	add_db_changes --fix 700
}

add_changes_700()
{
    local inten upgrade_db_sql
	inten="upgrade SQL database"
	upgrade_db_sql="$PRODUCT_ETC_D/db/${PRODNAME}_db_upgrade_700.sql"
	echo_try "$inten"
	rm -f /tmp/pd_users.dmp
	$mysql < $upgrade_db_sql >> "$product_log" 2>&1 && suc || die "$inten"
}

cleanup_certificates_700()
{
	local inten query
	inten="clean Repository table"
	echo_try "$inten"
	query="SELECT r.rep_id, r.component_id
		FROM Repository r
			LEFT JOIN misc m ON r.rep_id=m.val
					and (m.param='cert_rep_id'
					    or m.param='cl_tmpl_list_id'
					    or m.param='dom_tmpl_list_id')
			LEFT JOIN certificates cr ON r.component_id=cr.id
			LEFT JOIN Templates t ON r.component_id=t.id
			LEFT JOIN IP_Addresses i ON r.component_id=i.id
			LEFT JOIN clients c ON r.rep_id=c.tmpl_id or r.rep_id=c.pool_id
			LEFT JOIN domains d ON r.rep_id=d.cert_rep_id
		WHERE t.id is null and cr.id is null and i.id is null"
	echo "$query" | $mysql_raw | while read rep comp; do
		echo "delete from Repository where rep_id = $rep and component_id = $comp;"
	done | $mysql && suc || die "$inten"
}

select_700_dlu_perms()
{
    $mysql_raw 2>>$product_log <<-EOF
    select d.id as dom_id, p.permission, p.value, dp.val
		from clients c, Permissions p, domains d,
			dom_level_usrs du left join dom_param dp on dp.dom_id = du.dom_id and dp.param = 'perm_id'
		where c.perm_id = p.id and d.cl_id = c.id
			and du.dom_id = d.id
			and p.permission in ('manage_anonftp', 'manage_webapps', 'manage_quota',
								'manage_log', 'manage_maillists', 'manage_subdomains',
								'manage_phosting', 'manage_sh_access', 'manage_dns')
		order by dom_id;
	EOF
}

set_700_dlu_perms()
{
	local dom_id_prev query perm_id dom_id permission value val inten
	inten="set permissions of domain level users"
	dom_id_prev=
	select_700_dlu_perms | while read dom_id permission value val; do
		# inset only if domein don't have its own perms
		if test "$val" = NULL -a "$dom_id" != "$dom_id_prev"; then
			dom_id_prev="$dom_id"
			query="replace into Permissions(permission,value) values('$permission','$value'); select last_insert_id();"
			perm_id=`echo "$query" | $mysql_raw 2>>$product_log`
			$mysql >>$product_log 2>&1 <<-EOF || die "$inten"
				replace into dom_param(dom_id, param, val) values($dom_id, 'perm_id', $perm_id);
			EOF
		else
			if test "$val" != NULL; then
				perm_id="$val"
			fi
			$mysql >>$product_log 2>&1 <<-EOF || die "$inten"
				replace into Permissions(id,permission,value) values($perm_id,'$permission','$value');
			EOF
		fi
	done
}

upgrade_db_700()
{
	# fix 7.0.0 things
	fix_catch_all_domain_preferences
	fix_site_app_dbresources

	# main stuff
	p_echo
	p_echo
	p_echo "===> Upgrading MySQL Database from version 7.0 to 7.1"
	add_fixes_700
	add_changes_700

	inten="translate names to utf-8"
	pnnl_echo "  Translating names..."
	"$PRODUCT_ROOT_D/admin/sbin/upgrade_710_encoding" --recode-all >>"$product_log" 2>&1 && suc || die "$inten"

	cleanup_certificates_700
	set_700_dlu_perms
}

upgrade_db_700_newkey()
{
	siteapps_syncdb
}

db_check_700()
{
	db_check_foreign_key domains cl_id clients id
	db_check_foreign_key domains cert_rep_id Repository rep_id
}

add_skin_into_db(){
#$1 - skin.name, $2 - skin_place
skins_dir="${PRODUCT_ROOT_D}/admin/htdocs/skins"
query="select * from Skins where place='$2';"
res=`echo "$query" | $mysql`
if [ -z "$res" ]; then
        if [ -d $skins_dir/$2 ]; then
		pnnl_echo "Add $1 to database... "
		inten=" add $1 into database."
		$mysql <<-EOF || die "$inten"
                	INSERT INTO Skins (name,place) VALUES ('$1','$2');
		EOF
	fi
fi
}

add_fixes_710()
{
	db_fix_add_column key_history name "VARCHAR(255) BINARY AFTER plesk_key_id"
	db_fix_add_column key_history filename "VARCHAR(255) BINARY AFTER name"
	db_fix_add_column key_history options "VARCHAR(255) BINARY AFTER update_disabled"

	db_fix_add_key clients sapp_pool_id
	db_fix_add_key domains cert_rep_id
	db_fix_add_key pd_users account_id
	db_fix_add_unique_key subdomains dom_id displayName

	add_db_changes --fix 710
	db_fix_add_column clients account_id "INT UNSIGNED AFTER login"
	db_fix_add_column dom_level_usrs account_id "INT UNSIGNED AFTER state"
	db_fix_add_column dom_level_usrs perm_id "INT UNSIGNED AFTER card_id"

	upgrade_db_710_accounts clients
	upgrade_db_710_accounts dom_level_usrs
	upgrade_db_710_dom_perms
}

upgrade_db_710_dom_perms()
{
	local query id ids perm_id

	ids=`$mysql_raw -e "SELECT dom_id FROM dom_level_usrs"`
	if test $? -ne 0; then
		p_echo "" "$ids"
		die "upgrade permissions for domain $id"
	fi
	for id in $ids; do
		query="SELECT val FROM dom_param
					WHERE dom_id='$id' AND param='perm_id'
					  AND val IS NOT NULL AND val <> '0'"
		perm_id=`$mysql_raw -e "$query"`
		if test $? -ne 0; then
			p_echo "" "$perm_id"
			die "upgrade permissions for domain $id"
		fi
		if test -n "$perm_id"; then
			$mysql -e "UPDATE dom_level_usrs SET perm_id='$perm_id' WHERE dom_id='$id'" \
					>>"$product_log" 2>&1 \
					|| die "upgrade permissions for domain $id"
		fi
		$mysql -e "DELETE FROM dom_param WHERE param='perm_id' AND dom_id='$id'" \
				>>"$product_log" 2>&1 \
				|| die "upgrade permissions for domain $id"
	done
}

upgrade_db_710_accounts()
{
	local table id_name id ids
	table=$1
	if ! $mysql -e "SELECT passwd FROM $table WHERE 1 = 0" >/dev/null 2>&1; then
		return
	fi

	case "$table" in
		clients)
						id_name="id"
						;;
		dom_level_usrs)
						id_name="dom_id"
						;;
		*)
						die "upgrade_db_710_accounts() function error: unknown table '$table'"
						;;
	esac

	ids=`$mysql_raw -e "SELECT $id_name FROM $table"`
	for id in $ids; do
		insert_account_id $table $id_name $id
	done
	db_fix_del_column "$table" passwd
}

insert_account_id()
{
	local table id_name id
	table=$1
	id_name=$2
	id=$3
	$mysql <<-EOF >>"$product_log" 2>&1 || die "set passwords for $table with id = $id"
		INSERT INTO accounts (type, password) SELECT 'plain', passwd FROM $table WHERE $id_name = $id;
		UPDATE $table SET account_id = LAST_INSERT_ID() WHERE $id_name = $id
	EOF
}

upgrade_db_710()
{
	echo_try "upgrade database"
#	add two new .compact skins into db
	add_skin_into_db "Aqua Compact" "aqua.compact"
	add_skin_into_db "WinXP Reloaded Compact" "winxp.new.compact"
	translate_event_priorities_710
	add_fixes_710
	add_db_changes 710
	db_fix_drop_table stat

	db_transfer_db_users_710

	db_register_default_locale
	db_change_locales_codes_710
	db_init_updater_state

	suc
}

db_register_default_locale()
{
	$mysql <<-EOF >>"$product_log" 2>&1 || die "register default locale"
		DELETE FROM locales;
		INSERT INTO locales(id) VALUES('$default_locale');
		REPLACE INTO misc(param, val) VALUES('def_locale', '$default_locale');
		REPLACE INTO misc(param, val) VALUES('admin_locale', '$default_locale');
	EOF
}

translate_event_priorities_710()
{
	local query res
	res=`$mysql_raw -e 'SELECT id FROM event_handlers WHERE priority < 0 OR priority > 100'`
	if test $? -ne 0; then die "check event handler priorities"; fi
	if ! test -z "$res"; then
		$mysql -e 'UPDATE event_handlers SET priority = ((priority + 255)*100)/510' \
					>>"$product_log" 2>&1 \
		 || die "translate event handler priorities"
	fi
}

locales_names_load()
{
	TRANSLATE_LOCALES="al>sq-AL ar>ar-SY br>pt-BR ca>ca-ES cn>zh-CN de>de-DE en>en-US es>es-ES fr>fr-FR it>it-IT jp>ja-JP pl>pl-PL pt>pt-PT ro>ro-RO ru>ru-RU nl>nl-NL fi>fi-FI tr>tr-TR el>el-GR ko>ko-KR"
}

db_change_locales_codes_710()
{
	locales_names_load

	echo >>"$product_log"
	echo "  Change locales codes into database... " >>"$product_log"

	for rule in $TRANSLATE_LOCALES; do
		old_locale=`echo $rule | cut -d '>' -f 1`
		new_locale=`echo $rule | cut -d '>' -f 2`

		$mysql <<-EOF || die "replace locale '$old_locale' to '$new_locale' in database"
			UPDATE misc SET val='$new_locale' WHERE val='$old_locale' AND param IN ('def_locale', 'admin_locale');
			UPDATE clients SET locale='$new_locale' WHERE locale='$old_locale';
			UPDATE dom_param SET val='$new_locale' WHERE val='$old_locale' AND param IN ('user_locale','locale');
			UPDATE mn_param SET val='$new_locale' WHERE param='locale' AND val='$old_locale';
		EOF
	done
}

db_transfer_db_users_710()
{
	local inten query id
	inten="transfer db_users accounts in the accounts table"

	db_fix_add_column db_users account_id "INT UNSIGNED REFERENCES accounts(id)"

	query="SELECT id FROM db_users";
	$mysql_raw -e "$query" | while read id; do
		$mysql <<-EOF || die "transfer account data for DB User #$id"
			INSERT INTO accounts(password, type)
				SELECT passwd, IF(LENGTH(passwd) > 14, 'crypt', 'plain')
					FROM db_users WHERE id = $id;
			UPDATE db_users SET account_id = LAST_INSERT_ID()
				WHERE id = $id;
		EOF
	done

	if test $? -ne 0; then
		die "$inten"
	fi

	$mysql -e "ALTER TABLE db_users DROP passwd" || die "$inten"
}


upgrade_db_750()
{
	echo_try "apply $product_version changes to database"

	db_fix_750
	db_init_updater_state_conditionally

	# here are 7.5.* -> 8.0.now upgrades
	db_upgrade75_transfer_dns_zones
	db_upgrade75_mail_permission
	db_fix_drop_table mailer_queries
	db_upgrade75_add_new_permissions

	# Upgrade from 7.5.last to 8.0.last
	add_db_changes 750 
	db_fix_add_column hosting php_safe_mode "ENUM('false','true') NOT NULL DEFAULT 'true'"
# 	This function called later, in upgrade from 8.6.0
#	db_install_dashboard_presets
	db_init_updater_state

	suc
}

db_check_750()
{
	db_fix_check_stage=yes
	db_fix_750
	unset db_fix_check_stage
}

db_fix_750()
{
	if [ "$db_fix_check_stage" != "yes" ]; then
		# Convert all tables to InnoDB
		$mysql_raw -e 'show table status' \
			| awk -F '\t' -- '$2 != "InnoDB" { print "alter table "$1" type=InnoDB;" }' \
			| $mysql >>"$product_log" 2>&1 || die "convert all tables to InnoDB"
	fi

	local db_select_output
	db_select "select name, place from Skins where id > 16"
	if [ -n "$db_select_output" ]; then
		echo '#/bin/sh' > $PRODUCT_ROOT_D/tmp/restore-custom-skins.sh
		echo -n "$db_select_output" | awk -F '\t' "{ print \"$PRODUCT_ROOT_D/admin/bin/skinmng --register --name='\" \$1 \"' --installdir='\" \$2 \"'\" }" >> $PRODUCT_ROOT_D/tmp/restore-custom-skins.sh
		chown root:0 $PRODUCT_ROOT_D/tmp/restore-custom-skins.sh
		chmod 755 $PRODUCT_ROOT_D/tmp/restore-custom-skins.sh
	fi

	add_db_changes --fix 750

	db_fix_drop_table stat

	db_fix_add_column mail_resp content_type \
		"VARCHAR(245) NOT NULL DEFAULT 'text/plain' AFTER reply_to"
	db_fix_add_column mail_resp charset \
		"VARCHAR(245) NOT NULL DEFAULT 'UTF-8' AFTER content_type"

	db_fix_add_column hosting same_ssl \
		"ENUM('false','true') NOT NULL DEFAULT 'false'"

	db_fix_add_column ListsParams page_size \
		"INT NOT NULL DEFAULT 25"

	db_fix_add_column disk_usage configs \
		"BIGINT UNSIGNED DEFAULT 0"
	db_fix_add_column disk_usage chroot \
		"BIGINT UNSIGNED DEFAULT 0"

	db_fix_add_column protected_dirs cgi_bin \
		"ENUM('false','true') NOT NULL DEFAULT 'false'"
	db_fix_add_column subdomains ssl \
		"ENUM('false','true') NOT NULL DEFAULT 'false'"
	db_fix_add_column subdomains same_ssl \
		"ENUM('false','true') NOT NULL DEFAULT 'false'"

	db_fix_add_column --init "CASE type WHEN 'mysql' THEN 1 WHEN 'postgresql' THEN 2 END" \
		data_bases db_server_id \
		"INT UNSIGNED NOT NULL"

	db_fix_add_column data_bases default_user_id \
		"INT UNSIGNED DEFAULT NULL"

	db_fix_del_column Logos showMode

	db_fix_add_primary_key hosting dom_id
	db_fix_add_primary_key forwarding dom_id
	db_fix_add_primary_key upgrade_history upgrade_date
	db_fix_add_primary_key --check-where "component <> 'Unknown'" log_components action_id component
	db_fix_add_unique_key Skins place

	# TODO: move this to upgrade_db_900 when 9.0 development starts.
	# See bug #34654 for details.

	db_fix_add_foreign_key clients account_id accounts id
	db_fix_add_foreign_key clients limits_id Limits id
	db_fix_add_foreign_key clients params_id Parameters id
	db_fix_add_foreign_key clients perm_id Permissions id
	db_fix_add_foreign_key clients pool_id Repository rep_id
	db_fix_add_foreign_key clients logo_id Logos id
	db_fix_add_foreign_key clients tmpl_id Repository rep_id
	db_fix_add_foreign_key clients sapp_pool_id Repository rep_id

	db_fix_add_foreign_key cl_param cl_id clients id

	db_fix_add_foreign_key dom_level_usrs dom_id domains id
	db_fix_add_foreign_key dom_level_usrs account_id accounts id
	db_fix_add_foreign_key dom_level_usrs card_id Cards id
	db_fix_add_foreign_key dom_level_usrs perm_id Permissions id

	db_fix_add_foreign_key domains cl_id clients id
	db_fix_add_foreign_key domains cert_rep_id Repository rep_id
	db_fix_add_foreign_key domains limits_id Limits id
	db_fix_add_foreign_key domains params_id Parameters id

	db_fix_add_foreign_key dom_param dom_id domains id
	db_fix_add_foreign_key subdomains dom_id domains id
	db_fix_add_foreign_key subdomains sys_user_id sys_users id

	db_fix_add_foreign_key DomainServices dom_id domains id
	db_fix_add_foreign_key DomainServices parameters_id Parameters id

	db_fix_add_foreign_key WebApps domain_service_id DomainServices id

	db_fix_add_foreign_key disk_usage dom_id domains id

	db_fix_add_foreign_key hosting dom_id domains id
	db_fix_add_foreign_key hosting sys_user_id sys_users id
	db_fix_add_foreign_key hosting ip_address_id IP_Addresses id

	db_fix_add_foreign_key web_users dom_id domains id
	db_fix_add_foreign_key web_users sys_user_id sys_users id

	db_fix_add_foreign_key protected_dirs dom_id domains id

	db_fix_add_foreign_key pd_users account_id accounts id
	db_fix_add_foreign_key pd_users pd_id protected_dirs id

	db_fix_add_foreign_key forwarding dom_id domains id
	db_fix_add_foreign_key forwarding ip_address_id IP_Addresses id

	db_fix_add_foreign_key anon_ftp dom_id domains id

	db_fix_add_foreign_key DomainsTraffic dom_id domains id

	db_fix_add_foreign_key ClientsTraffic cl_id clients id

	db_fix_add_foreign_key mail account_id accounts id
	db_fix_add_foreign_key mail dom_id domains id

	db_fix_add_foreign_key mail_aliases mn_id mail id

	db_fix_add_foreign_key mail_redir mn_id mail id

	db_fix_add_foreign_key mail_resp mn_id mail id

	db_fix_add_foreign_key resp_freq rn_id mail_resp id

	db_fix_add_foreign_key resp_attach rn_id mail_resp id

	db_fix_add_foreign_key resp_forward rn_id mail_resp id

	db_fix_add_foreign_key mn_param mn_id mail id

	db_fix_add_foreign_key Notifications note_id Notes id

	db_fix_add_foreign_key data_bases dom_id domains id
	db_fix_add_foreign_key data_bases db_server_id DatabaseServers id
	db_fix_drop_unique_key data_bases name type
	db_fix_change_column data_bases name name "CHAR(63) BINARY NOT NULL"
	db_fix_add_unique_key data_bases name db_server_id

	db_fix_add_foreign_key db_users account_id accounts id
	db_fix_add_foreign_key db_users db_id data_bases id

	db_fix_add_foreign_key sys_users account_id accounts id

	db_fix_add_foreign_key Templates note_id Notes id

	db_fix_add_foreign_key TmplData tmpl_id Templates id

	db_fix_add_foreign_key slave_params slave_id slaves id

	db_fix_add_foreign_key IP_Addresses ssl_certificate_id certificates id
	db_fix_add_foreign_key IP_Addresses default_domain_id hosting dom_id "ON DELETE SET NULL"

	db_fix_add_foreign_key log_actions action_id actions id

	db_fix_add_foreign_key log_components action_id log_actions id

	db_fix_add_foreign_key event_handlers action_id actions id

	db_fix_add_foreign_key MailLists dom_id domains id

	db_fix_add_foreign_key report_section report_id report id

	db_fix_add_foreign_key report_auto report_id report id
	db_fix_add_foreign_key report_auto client clients id
	db_fix_add_foreign_key report_auto domain domains id


	if db_test 'SHOW COLUMNS FROM SiteApps' '$1 == "app_id"'
	then
	    db_fix_add_foreign_key SiteApps app_id SiteAppPackages id
	fi
	
	db_fix_add_foreign_key SiteApps params_id Parameters id

	db_fix_add_foreign_key SiteAppResources app_id SiteApps id

	db_fix_add_foreign_key tts_conf def_qu_id tts_queues id
	db_fix_add_foreign_key tts_conf def_pr_id tts_priorities id
	db_fix_add_foreign_key tts_conf def_cat_id tts_cats id

	db_fix_add_foreign_key tts_tickets reporter_id tts_reporters id
	db_fix_add_foreign_key tts_tickets cat_id tts_cats id
	db_fix_add_foreign_key tts_tickets qu_id tts_queues id
	db_fix_add_foreign_key tts_tickets pr_id tts_priorities id

	db_fix_add_foreign_key tts_ticket_events ticket_id tts_tickets id
	db_fix_add_foreign_key tts_ticket_events reporter_id tts_reporters id

	db_fix_add_foreign_key tts_slave_info server_id slaves id

	if db_test_table sa_conf && db_test_table sa_list; then
		db_fix_add_foreign_key sa_list mailname sa_conf mailname
	fi

	db_fix_add_foreign_key key_history_params key_id key_history id

	db_fix_add_foreign_key webalizer_hidden_referrer dom_id domains id

	db_fix_add_foreign_key webalizer_group_referrer dom_id domains id

	db_do_if_not \
		"SELECT * FROM Permissions WHERE permission = 'manage_ftp_password' LIMIT 1" 1 \
		"INSERT INTO Permissions(id, permission, value)
			SELECT perm_id, 'manage_ftp_password', 'true' FROM dom_level_usrs WHERE perm_id IS NOT NULL"
	db_do_if_not \
		"SELECT * FROM misc WHERE param = 'size_count_type'" 1 \
		"REPLACE INTO misc (param, val) VALUES ('size_count_type', 'byte')"
	db_do_if_not \
		"SELECT * FROM actions WHERE name = 'client_siteapp_added'" 1 \
		"REPLACE INTO actions (name, descr, enabled)
			VALUES ('client_siteapp_added', 'Site Application Package added to Client Pool', 'true')"
	db_do_if_not \
		"SELECT * FROM actions WHERE name = 'client_siteapp_removed'" 1 \
		"REPLACE INTO actions (name, descr, enabled)
			VALUES ('client_siteapp_removed', 'Site Application Package removed from Client Pool', 'true')"
	db_do_if_not \
		"SELECT * FROM actions WHERE name = 'license_expired'" 1 \
		"REPLACE INTO actions (name, descr, enabled)
			VALUES ('license_expired', 'License expired', 'true')"
	db_do_if_not \
		"SELECT * FROM actions WHERE name = 'domain_owner_change'" 1 \
		"REPLACE INTO actions (name, descr, enabled)
			VALUES ('domain_owner_change', 'Change Domain Owner', 'true')"

	if [ "$db_fix_check_stage" != "yes" ] && ! db_test "SELECT * FROM DatabaseServers" 1; then
		local db_select_output pg_admin_login pg_admin_passwd pg_last_error
		db_select "SELECT val FROM misc WHERE param = 'postgresql_admin_login'"
		pg_login="`echo \"$db_select_output\" | sed -e \"s/'/''/g\"`"
		db_select "SELECT val FROM misc WHERE param = 'postgresql_admin_passwd'"
		pg_passwd="`echo \"$db_select_output\" | sed -e \"s/'/''/g\"`"
		if [ -n "$pg_login" ] && [ -n "$pg_passwd" ]; then
			pg_last_error=no_error
		else
			pg_last_error=credentials_not_set
		fi
		db_do "REPLACE INTO DatabaseServers (id, host, port, type, admin_login, admin_password, last_error)
			VALUES (1, 'localhost', 3306, 'mysql', 'admin', '********', 'no_error')"
		db_do "REPLACE INTO DatabaseServers (id, host, port, type, admin_login, admin_password, last_error)
			VALUES (2, 'localhost', 5432, 'postgresql',	'$pg_login', '$pg_passwd', '$pg_last_error')"
		db_do "DELETE FROM misc WHERE param IN ('postgresql_admin_login', 'postgresql_admin_passwd')"
		db_do "REPLACE INTO misc (param, val) VALUES ('default_server_mysql', '1')"
		db_do "REPLACE INTO misc (param, val) VALUES ('default_server_postgresql', '2')"
	fi

	if [ "$db_fix_check_stage" != "yes" ]; then
		"$PRODUCT_ROOT_D/admin/sbin/sappmng" --register-application-files 2>>"$product_log" || warn "register siteapps files"
	fi

	db_fix_init_cp_access par_table=Permissions par_id=id par_name=permission \
						  obj_table=clients obj_ref=perm_id
	db_fix_init_cp_access par_table=TmplData par_id=tmpl_id par_name=element \
						  obj_table=Templates obj_ref=id

	# Delete 'cp_acces' elements from all domain templates. bug 68506
	db_fix_del_cp_access_from_dom_templates

	db_fix75_control_visibility
}

db_fix75_control_visibility()
{
	### this subroutine converts the data from ControlVisibility table to two new table itmpl and itmpl_data
	if [ "$db_fix_check_stage" = "yes" ]; then
		### do nothing if "check" stage is in process
		return
	fi

	### check the itmpl records existing
	### before 7.5.5 no such records exist because it is a new table
	db_test "SELECT * FROM itmpl LIMIT 1" 1
	if [ $? -ne 0 ]; then
		### create a new record in itmpl
		db_do "INSERT INTO itmpl (id, name) values(1, 'Interface customization template')";

		### for safety delete all the existing records from itmpl_data
		db_do "DELETE FROM itmpl_data"

		if db_test_table ControlVisibility; then
			### copy all the data from old table (ControlVisibility) to new table (itmpl_data)
			db_do "INSERT INTO itmpl_data(itmpl_id, page, control, state, control_type) \
					SELECT 1, page, control, state, control_type FROM ControlVisibility"
			db_fix_drop_table ControlVisibility
		fi
	fi

	### at this stage:
	### 1) the table itmp & itmpl_data exist
	### 2) all data in these tables and references between these tables are ok

	### register def_itmpl_id in misc
	db_do_if_not \
		"SELECT * FROM misc WHERE param = 'def_itmpl_id'" 1 \
		"INSERT INTO misc(param, val) VALUES('def_itmpl_id', '1')"

	### register admin_itmpl_id in misc
	db_do_if_not \
		"SELECT * FROM misc WHERE param = 'admin_itmpl_id'" 1 \
		"INSERT INTO misc(param, val) VALUES('admin_itmpl_id', '1')"
}

db_fix_init_cp_access()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	local par_table par_id par_name obj_table obj_ref select id
	while test $# -gt 0; do
		eval "$1"
		shift
	done
	db_select "SELECT c.$obj_ref AS $par_id \
		FROM $obj_table c LEFT JOIN $par_table p \
			ON c.$obj_ref = p.$par_id AND p.$par_name = 'cp_access' \
		WHERE c.$obj_ref IS NOT NULL AND p.$par_name IS NULL"
	if test -z "$db_select_output"; then
	    return
	fi
	echo "$db_select_output" | while read id; do
		db_do "INSERT INTO $par_table($par_id, $par_name, value) VALUES($id, 'cp_access', 'true')"
	done
}

db_fix_del_cp_access_from_dom_templates()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi
	# Clients dom. templates
	db_select "SELECT r.component_id AS tmpl_id \
		FROM clients c LEFT JOIN Repository  r \
			ON c.tmpl_id=r.rep_id LEFT JOIN Templates t \
			ON r.component_id=t.id WHERE tmpl_id IS NOT NULL"
	if test -z "$db_select_output"; then
	    return
	fi
	echo "$db_select_output" | while read id; do
		db_do "DELETE FROM TmplData WHERE element='cp_access' AND tmpl_id=$id"
	done

	# Admins dom. templates
	db_select "SELECT r.component_id FROM Repository r, misc \
		WHERE misc.param='dom_tmpl_list_id' and r.rep_id=misc.val"
	if test -z "$db_select_output"; then
	    return
	fi
	echo "$db_select_output" | while read id; do
		db_do "DELETE FROM TmplData WHERE element='cp_access' AND tmpl_id=$id"
	done
}

db_upgrade75_add_new_permissions()
{
	local user_level
	local permission
	local value
	local desc

	for desc in 2:stdgui:true 2:dashboard:true 2:manage_dashboard:true 1:manage_domain_aliases:false; do
		user_level=`echo $desc | awk -F ':' '{print $1}'`
		permission=`echo $desc | awk -F ':' '{print $2}'`
		value=`echo $desc | awk -F ':' '{print $3}'`

		if [ 0$user_level -ge 1 ]; then
			### client has user_level=1
			db_do_if_not \
				"SELECT * FROM Permissions p, clients c WHERE c.perm_id=p.id AND p.permission='$permission' LIMIT 1" 1 \
				"INSERT INTO Permissions(id, permission, value)
					SELECT perm_id, '$permission', '$value' FROM clients WHERE perm_id IS NOT NULL";
		fi

		if [ 0$user_level -ge 2 ]; then
			### domain level user has user_level=2
			db_do_if_not \
				"SELECT * FROM Permissions p, dom_level_usrs dlu  WHERE dlu.perm_id=p.id AND p.permission='$permission' LIMIT 1" 1 \
				"INSERT INTO Permissions(id, permission, value)
					SELECT perm_id, '$permission', '$value' FROM dom_level_usrs WHERE perm_id IS NOT NULL";
		fi
	done
}

db_upgrade75_transfer_dns_zones()
{
	if [ "$db_fix_check_stage" = "yes" ]; then
		return
	fi

	db_fix_add_column domains dns_zone_id "INT UNSIGNED DEFAULT NULL"
	db_fix_add_column dns_recs dns_zone_id "INT UNSIGNED NOT NULL"

	if db_test 'SHOW COLUMNS FROM domains' '$1 == "dns_zone"' \
		&& db_test 'SHOW COLUMNS FROM domains' '$1 == "dns_type"' \
		&& db_test 'SHOW COLUMNS FROM dns_recs' '$1 == "dom_id"' \
		&& db_test 'SHOW TABLES' '$1 == "dns_masters"' \
		&& ! db_test 'SELECT * FROM dns_zone' '1'
	then
		for id in `mysql_raw -e "SELECT id FROM domains"`; do
			db_upgrade75_make_dns_zone "$id" "
				INSERT INTO dns_zone(name, displayName, status, email, type)
					SELECT d.name, (BINARY d.displayName),
							CASE d.dns_zone WHEN 'true' THEN 0 ELSE 1 END,
							CASE
								WHEN c.email IS NOT NULL AND c.email <> '' THEN c.email
								ELSE m_email.val
							END,
							d.dns_type
						FROM domains d, clients c, misc m_email
							WHERE d.id = $id
							AND d.cl_id = c.id
							AND m_email.param = 'admin_email';
				SET @new_zone_id = last_insert_id();
				UPDATE domains SET dns_zone_id = @new_zone_id WHERE id = $id;
			"
		done
		hostname=`mysql_raw -e "SELECT val FROM misc WHERE param='FullHostName'"`
		if [ $? -ne 0 ]; then
			die "get registered hostname: $hostname"
		fi
		db_upgrade75_make_dns_zone 0 "
			INSERT INTO dns_zone(name, displayName, status, type)
				VALUES('$hostname', '$hostname', 0, 'master');
			SET @new_zone_id = last_insert_id();
			REPLACE INTO misc(param, val) VALUES('def_dns_zone_id', @new_zone_id);
		"
	fi

	db_fix_del_column domains dns_zone
	db_fix_del_column domains dns_type
	db_fix_del_column dns_recs dom_id
	db_fix_drop_table dns_masters

	# dns_recs
	for table in dns_recs dns_recs_t; do
		for column in displayHost displayVal; do
			db_fix_add_column "$table" "$column" "VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL"
		done
	done
	$PRODUCT_ROOT_D/admin/sbin/dnsmng --upgrade-dns-recs-755
	for table in dns_recs dns_recs_t; do
		db_do "
			ALTER TABLE $table
				MODIFY host VARCHAR(255)
					CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL
				, MODIFY val VARCHAR(255)
					CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL
		"
	done
}

db_upgrade75_make_dns_zone()
{
	local domain_number="$1"
	local query_make_zone="$2"
	local domain_cond=""
	if [ "$domain_number" -eq 0 ]; then
		domain_cond=" dom_id IS NULL OR dom_id = $domain_number "
	else
		domain_cond=" dom_id = $domain_number "
	fi

	db_do --inten "transfer dns records" "
		$query_make_zone
		UPDATE dns_recs SET dns_zone_id = @new_zone_id WHERE $domain_cond;
		INSERT INTO dns_recs(dom_id, dns_zone_id, type, host)
			SELECT $domain_number, @new_zone_id, 'master', ip_address
				FROM dns_masters WHERE $domain_cond;
	"
}

db_upgrade75_mail_permission()
{
	db_fix_add_column mail perm_id "INT UNSIGNED NOT NULL"
	if db_test 'SHOW COLUMNS FROM mail' '$1 == "cp_access"'
	then
		for id in `mysql_raw -e "SELECT id FROM mail"`; do
			db_do --inten "transfer mailname permissions" "
				INSERT INTO Permissions(permission, value)
					SELECT 'cp_access', CASE cp_access WHEN 'true' THEN 'true' ELSE 'false' END
						FROM mail WHERE id = $id;
				SET @new_perm_id = last_insert_id();
				UPDATE mail SET perm_id = @new_perm_id WHERE id = $id;
			"
		done
	fi
	db_fix_del_column mail cp_access
}


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
    $PRODUCT_ROOT_D/bin/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_ETC_D/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_select "SELECT id FROM dns_zone"
	local ids="$db_select_output"
	for id in $ids; do
		db_select "SELECT time_stamp from dns_recs WHERE dns_zone_id=$id LIMIT 1"
		db_do "UPDATE dns_zone SET serial=UNIX_TIMESTAMP('$db_select_output') WHERE id=$id"
	done
}

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_ROOT_D/admin/plib/scripts/move_admin_into_clients_86.php"
	$PRODUCT_ROOT_D/bin/sw-engine-pleskrun $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()
{
    if [ -x "$PRODUCT_ROOT_D/bin/sw-engine-pleskrun" -a -s "$PRODUCT_ROOT_D/admin/plib/scripts/update_dashboard_presets_9_5_1.php" ]; then
	$PRODUCT_ROOT_D/bin/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"
    fi
}

db_update_exp_event()
{
	db_test_table "exp_events" || 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"
}

#proftpd

set_ftpd_params()
{
	anonftp_user="${product}ftp"
	anonftp_group="${product}ftp"

	PROFTPD_ROOT="$PRODUCT_ROOT_D/ftpd"
	PROFTPD_ETC_D="$PROFTPD_ROOT/etc"
}

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"
}
upgrade_proftpd_600()
{
	# get path of proftpd scoreboard path
	if [ -f "${FTPD_CONF}" ]; then
		ScoreboardFile=`cat ${FTPD_CONF} | awk '{ if ($1 == "ScoreboardFile") SCOREBOARDFILE=$2 } END { print SCOREBOARDFILE }'`
	fi

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

		rm -f "${ScoreboardFile}"

	else

		if [ "X${service_failures_ignoring}" != "X1" ]; then
			die $inten
		else
			warn "${inten}. Unable to define ScoreboardFile directive value."			
			minor_problem=1
		fi
	fi

#	already done in mv_quota_2_subdir_600 (upgrade_vhosts_600.sh)
#	move_ftp_quota_files_600
}
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
}
set_horde_params()
{
	horde_datadir="/usr/local/psa/psa-horde"
	horde_confdir="/usr/local/etc/psa-webmail/horde"
	horde_sysconfd="$horde_confdir/horde"
	horde_logdir="/usr/local/psa/var/log"
	horde_passwd_file="/usr/local/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"
}
upgrade_horde_754()
{
#   Fix up creating passwordless user, bug 41358, bug 
	db_do "DELETE FROM mysql.user WHERE user='horde' and host='%';"
	db_do "DELETE FROM mysql.tables_priv WHERE user='horde' and host='%';"
	db_do "FLUSH PRIVILEGES;"
}

tomcat_reconfigure_server()
{
	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'" 			|| die "get tomcat parameter from the database"
		if [ -n "$db_select_output" ]; then
			ports="--${name}-connector-port $db_select_output"
		fi
	done
	"$UTILS_DIR/tomcatmng" --install-psa --replace-if-exists $ports 		|| die "configure PSA service"

	db_select "SELECT d.name
				FROM domains d, DomainServices ds
				WHERE d.id = ds.dom_id
					AND type='tomcat'
					AND ds.status = 0" 		|| die "get active tomcat domains"
	local domains="$db_select_output"
	for domain_name in $domains; do
		local var manager_login manager_passwd
		for var in manager_login manager_passwd; do
			db_select "SELECT p.value
						FROM Parameters p, DomainServices ds, domains d
						WHERE name = '$domain_name'
							AND d.id = ds.dom_id
							AND ds.parameters_id = p.id
							AND p.parameter = '$var'" 						|| die "get $var for $domain_name"
			eval "$var=\"\$db_select_output\""
		done

		local aliases=
		if
			db_test "SELECT 1
						FROM dns_recs dr, domains d
						WHERE dr.host = 'www.${domain_name}.'
							AND dr.dns_zone_id = d.dns_zone_id
							AND d.name = '$domain_name'" '1'
		then
			aliases="--alias www.$domain_name"
		fi

		"$UTILS_DIR/tomcatmng" --install-vhost --vhost-name $domain_name $aliases
		env PSA_PASSWORD="$manager_passwd" 			"$UTILS_DIR/tomcatmng" --install-service --vhost-name $domain_name --manager-login "$manager_login"

		aliases=
		db_select "select da.name
					from domains d, domainaliases da
					where d.id = da.dom_id
						and tomcat='true'
						and d.name='$domain_name'"
		aliases="$db_select_output"
		for alias_name in $aliases; do
			"$UTILS_DIR/tomcatmng" --add-alias --vhost-name=$domain_name --alias=$alias_name
		done

	done

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

set_swkey_params()
{
	SWKEY_REPOSITORY="/usr/local/etc/sw/keys"
	KEYUPGRADE_PATH="/usr/local/libexec/plesk-9.0/key-upgrade"
}

key_upgrade_cmd()
{
	# set to run key upgrade script
	p_echo "Starting Plesk Key upgrade task"
	nohup /bin/sh -c "$KEYUPGRADE_PATH 2>&1 | logger -p daemon.err -t plesk-key-upgrader" 	 >/dev/null 2>&1 &
}

key_upgrade_86_install_additional_key()
{
	key_path="$1"
	echo_try "install key $key_path"

	$PRODUCT_ROOT_D/bin/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()
{
	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_upgrade_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
	local wflag

	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 "Empty service name for $service_name"

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

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

	if [ "$action" = "exists" ]; then 
		[ -n "$service_script" ] && return 0 || return 1
	else
		[ -z "$service_script" ] && die "Unable to handle $service"

		if [ -n "$wflag" ]; then
			SR_WARNING="$service: script is not executable"
			service_restart_warning
			return 0
		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 $@
			;;
		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

	ret="$?"
	if [ "$action" != "status" ]; then
		[ "$ret" -eq 0 ] && suc || warn $inten
	fi

	return $ret
}

is_function()
{
	local type_output="`LANG=C LC_ALL=C LC_MESSAGES=C type \"$1\" 2>/dev/null | head -n 1`"
	case "$type_output" in
		*function)
			return 0
		;;
		*)
			return 1
		;;
	esac
}
form_undotted_version()
{
    echo $1 | awk -F. '{ print $1 $2 }'
}

get_prev_version()
{
	# Debian package system reports previous version as script argument
	if [ "X${prev_version}" = "X" ]; then

		# version file must exists in product directory
		if [ -f $1/version ]; then
		    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 [ ! -e "$PRODUCT_ROOT_D/version" ]; then
		p_echo "not found."
	else
		p_echo "found."
		get_prev_version ${PRODUCT_ROOT_D}
		do_upgrade=1
	fi
}

check_localtime_file()
{
	[ -f /etc/localtime ] && return 0
	echo "There is no /etc/localtime file in system."
	echo "Run tzsetup as root to set up your timezone"
	return 1
}

preinstall_checks()
{
	check_localtime_file || exit 1
}

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

	p_echo
	if [ "X${minor_problem}" != "X1" ]; then
		p_echo "                             Congratulations!"
	else
		p_echo
	fi
	p_echo "        All stages of the upgrade were successful."
	p_echo "        ${PRODUCT_NAME} is now running on your system."
	p_echo "        To complete the system configuration process, please proceed to URL:"
	p_echo "        https://${fullhost}:8443/ or"
	p_echo "        https://${print_address}:8443/"
	p_echo "        Use 'admin' and '$passwd' as login name and password."
	p_echo
	p_echo "        Further, use the following commands to start and stop the system:"
	p_echo "        $START_SH start and"
	p_echo "        $START_SH stop respectively."
	p_echo

	if [ "X${minor_problem}" = "X1" ]; then
		p_echo " *****************************************************************************"
		p_echo " *                                                                           *"
		p_echo " *   WARNING:    Some problems occured during upgrade. You need to           *"
		p_echo " *            check log file                                                 *"
		p_echo " *            ${product_log}       *"
		p_echo " *            to fix these problems.                                         *"
		p_echo " *                                                                           *"
		p_echo " *****************************************************************************"
		p_echo
	fi

	if test -n "$upgrade_default_key_installed"; then

		p_echo "*****************************************************************************"
		p_echo
		p_echo " WARNING:    Automatic license upgrade was not performed during"
		p_echo "             the upgrade process. The product is currently running"
		p_echo "             on the default license with limited functionality"
		p_echo "             until such time that an appropriate license is installed."
		p_echo
		p_echo "*****************************************************************************"

	fi
else

	p_echo "                             Congratulations!"
	p_echo "        Plesk has been successfully installed on your server."
	p_echo "        To complete the system configuration, please proceed to URL:"
	p_echo "        https://${fullhost}:8443/ or"
	p_echo "        https://${print_address}:8443/"
	p_echo "        Use the login name 'admin' and password '$passwd'."
	p_echo
	p_echo "        Further, use the following commands to start and stop Plesk:"
	p_echo "        \"$START_SH start\" and"
	p_echo "        \"$START_SH stop\" respectively."
	p_echo
	p_echo "        All Plesk control panel documentation is available at"
	p_echo "        http://www.parallels.com/en/products/plesk/docs"
	p_echo
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		p_echo
	else
		p_echo " *****************************************************************************"
		p_echo " *                                                                           *"
		p_echo " *      NOTE:   You have a default key file with limited functionality       *"
		p_echo " *              currently installed for ${PRODUCT_NAME}, which allows                  *"
		p_echo " *              creating one client account, one domain, one mail name and   *"
		p_echo " *              one web user.                                                *"
		p_echo " *              To extend the limits of your license key and enable          *"
		p_echo " *              additional features, please contact the Parallels sales      *"
		p_echo " *              department: ${sales_email}                              *"
		p_echo " *                                                                           *"
		p_echo " *      Thank you for choosing our products!                                 *"
		p_echo " *****************************************************************************"
	fi
fi
}

p_echo()
{
[ -z "$product_log" ] || echo "$@" >> "$product_log" 2>&1
echo "$@"
}

pnnl_echo()
{
    echo -n "$*" >> "$product_log" 2>&1
    echo -n "$*" 
}

die()
{
	PACKAGE_SCRIPT_FAILED="$*"

	if [ "X$trigger_uninstall" != "X1" ]; then
		printf "\a\a"
		p_echo
		p_echo "ERROR while trying to $*"
		echo "Check the error reason(see log file: ${product_log}), fix and try again"
		p_echo
		if [ "X$do_patch" != "X1" -a "X$do_reconfigure" != "X1" ]; then
			p_echo "Aborting..."
			p_echo
		fi
	fi

	smart_undo_install

	selinux_close

	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 "During the $inten found some problems"
echo "(see log file: ${product_log})"
p_echo
p_echo "Continue..."
p_echo

}

report_problem()
{
	p_echo "***** $process problem report *****"
	echo "***** $process problem report *****" >> "$product_problems_log" 2>&1

	p_echo "$1"
	echo "$1" >> "$product_problems_log" 2>&1

	p_echo "$2"
	echo "$2" >> "$product_problems_log" 2>&1

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

  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)."

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

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

  comm_err
}

echo_try()
{
	msg="$*"
	pnnl_echo " Trying to $msg... "
}

suc()
{
	p_echo "done"
}

update_history()
{
	inten="insert upgrade info into history table"

	upgrade_date=`date +%Y-%m-%d:%H:%M:%S`;
	prev_version_info=`cat ${PRODUCT_ROOT_D}/version`;

	query="INSERT INTO upgrade_history (upgrade_date, version_info, db_version)
			 VALUES ('${upgrade_date}','${prev_version_info}',
			 '${prev_db_version}')"
	echo ${query} | $mysql || die $inten
}

create_version_file()
{
	echo ${product_version} ${conceived_os_vendor} ${conceived_os_version} ${product_build} > ${PRODUCT_ROOT_D}/version
}
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
}

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

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

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
		$START_SH start
	fi
}

start_product_now_final()
{
	unset PLESK_KEYUPDATE_DISABLED
	start_product_now
}

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
}

set_default_locale()
{
	p_echo 'Setting the default locale'
	default_locale_file="$PRODUCT_ROOT_D/admin/htdocs/locales/default"
	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/'`"
	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
}

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_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;
	' "$@"
}

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
}

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
}

true superserver_reconfig

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
		    ;;
	    disable)
			[ -f "$superserver_dir/${service}_psa" ] && mv -f "$superserver_dir/${service}_psa" "$superserver_dir/${service}.psa"
		    ;;
	esac

	return 0
}

true superserver_status_linux_debian
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
}

package_script_begin_pkg()
{
	package_script_begin
}

package_script_end_pkg()
{
	package_script_end
}

package_script_begin()
{
	local title

	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

	product_log="/tmp/${PACKAGE_NAME}_${PACKAGE_VERSION}_${PACKAGE_RELEASE}_${process}.`date +%y%m%d.%H.%M`.log"
	product_problems_log="/tmp/${PACKAGE_NAME}_${PACKAGE_VERSION}_${PACKAGE_RELEASE}_problems.`date +%y%m%d.%H.%M`.log"
	title="`package_script_log_title`"
	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
	}
	problems_occured=0

	product_default_conf
	initial_conf
	set_common_params
	read_conf
}

package_script_end()
{
	local title
	title="`package_script_log_title`"

	packagemng_set_dirty_flag

	echo "STOP $title" >>"$product_log"
	echo "STOP $title" >>"$product_problems_log"
}

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

# <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
		;;
	ok) PACKAGE_SCRIPT_FAILED=
		;;
	esac

	trap - EXIT

	package_script_end_this_system
}


package_script_begin_this_system()
{
    package_script_begin_pkg
}

package_script_end_this_system()
{
    package_script_end_pkg
}

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
}

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
    case "$machine" in
       Darwin)
         common_var=`nireport / /groups name gid| grep "$1"| awk '{print $2}'`
       ;;
	   *)
         common_var=`cat /etc/group | awk -F':' '$1 == "'$1'" {print $3}'` 
       ;;
    esac

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

	case "$machine" in
		BSD)
			echo "y" | pw userdel $rm_user>> $product_log 2>&1 && suc 
			pwd_mkdb /etc/master.passwd >> $product_log 2>&1
		;;
		linux|solaris)
			userdel  $rm_user>> $product_log 2>&1 && suc || die "$inten"
		;;
		Darwin)
			niutil -destroy / /users/"$rm_user" >> $product_log 2>&1 && suc || die "$inten"
			reload_darwin_netinfo
		;;
	esac
}

delete_group()
{
	local rm_group

	rm_group="$1"

	inten="remove group $rm_group"
	echo_try "$inten"

	case "$machine" in
		BSD)
			pw groupdel $rm_group>> $product_log 2>&1
			pwd_mkdb /etc/master.passwd >> $product_log 2>&1
		;;
		linux|solaris)
			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
		;;
		Darwin)
			niutil -destroy / /groups/"$rm_group" >> $product_log 2>&1 && suc || die "$inten"
			reload_darwin_netinfo
		;;
	esac
	suc
}

ch_user_home()
{
	local user new_home

	user="$1"
	new_home="$2"

	inten="change home directory for user $user"
	echo_try "$inten"

	case "$machine" in

		BSD)
			pw usermod "$user" -d "$new_home" 2>>"$product_log" && suc || die "$inten"
			;;

		linux)
			usermod -d "$new_home" "$user" 2>>"$product_log" && suc || die "$inten"
			;;

		Darwin)
			niutil -createprop / /users/"$user" home "$new_home" && suc || die "$inten"
			reload_darwin_netinfo
			;;
		*)
			die "unknown platform"
			;;

	esac

}

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

	case "$machine" in
		BSD)
			grp_res=`pw groupshow "$group" 1>/dev/null 2>&1 ; echo $?`
			;;
		linux)
			grp_res=`groupmod "$group" 1>/dev/null 2>&1 ; echo $?`
			;;
		Darwin)
			grp_res=`nireport / /groups name gid | grep "$group" | awk '{print $2}' 2>&1`
			[ ! -z "$grp_res" ] && grp_res="0" || grep_res="1" 
			;;
		*)
			die "unsupported OS"
			;;
	esac

	echo "$grp_res"
}

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

	case "$machine" in
	BSD)
		pw usermod "$user" -G "$newlist" 2>>"$product_log" && suc || die "$inten"
		;;
	linux)
		usermod -G "$newlist" "$user" 2>>"$product_log" && suc || die "$inten"
		;;
	Darwin)
		niutil -appendprop / /groups/"$group" users "$user" 2>>"$product_log" && suc || die "$inten" 	
		reload_darwin_netinfo
		;;
	*)
		die "unknown platform"
		;;
	esac
}

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' ... "
			case "$machine" in
				BSD)
					#pw groupadd "$group" -g "$gid" >> $product_log 2>&1 && suc ||
					pw groupmod  "$group" -l "$group_new" >> $product_log 2>&1
					what_done=1
					;;
				linux)
					groupmod -n "$group_new" "$group" >> $product_log 2>&1 && suc ||
					die $inten
					what_done=1
					;;
				Darwin) 
					niutil -createprop / /groups/"$group" name "$group_new" >> $product_log 2>&1 && suc ||
					reload_darwin_netinfo
					die $inten
					what_done=1
					;;
			esac
			;;
		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
				    Darwin)
					etc_grp_res=`nireport / /groups name gid | grep "$group"`
					echo "$etc_grp_res"|grep "$gid" && p_echo "Group '$group' already exists" || group_err "$group" "$gid"
					
					;;
				    *)
					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"
							case "$machine" in
								BSD)
									pw groupadd "$group" -g "$gid" >> $product_log 2>&1 && suc ||
									die $inten
									what_done=1
									;;
								linux|solaris)
									groupadd -g "$gid" "$group" >> $product_log 2>&1 && suc ||
									die $inten
									what_done=1
									;;
								Darwin)
									niutil -create / /groups/"$group" >> $product_log 2>&1 || die $inten
									niutil -createprop / /groups/"$group" gid "$gid" >> $product_log 2>&1 && suc || die $inten
									niutil -createprop / /groups/"$group" passwd '*' >> $product_log 2>&1 && suc || die $inten
									niutil -createprop / /groups/"$group" users >> $product_log 2>&1 && suc || die $inten
									reload_darwin_netinfo
									what_done=1
									;;
							esac
							;;
					esac
					;;
			esac
			;;
		false)
			case "$grp_res" in
				0)
					p_echo " Group '$group' already exists"
					;;
				*)
					echo_try "$inten"
					case "$machine" in
						BSD)
							#pw groupadd "$group" -g "$gid" >> $product_log 2>&1 && suc ||
							pw groupadd "$group" >> $product_log 2>&1 && suc ||
							die $inten
							what_done=1
							;;
						linux|solaris)
							groupadd "$group" >> $product_log 2>&1 && suc ||
							die $inten
							what_done=1
							;;
						Darwin)
							niutil -create / /groups/"$group" >> $product_log 2>&1 || die $inten
							niutil -createprop / /groups/"$group" gid "$gid" >> $product_log 2>&1 && suc || die $inten
							niutil -createprop / /groups/"$group" passwd '*' >> $product_log 2>&1 && suc || die $inten
							niutil -createprop / /groups/"$group" users >> $product_log 2>&1 && suc || die $inten
							reload_darwin_netinfo
							what_done=1
							;;
					esac
			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'... "
							case "$machine" in
								BSD)
									pw useradd -n "$user" -u "$uid" -g "$group" -c "$u_desc" -d "$u_home" -s "$u_shell" >> $product_log 2>&1 &&
									suc || die $inten
									what_done=1
									;;
								linux|solaris)
									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
									;;
								Darwin)
									niutil -create / /users/"$user" >> $product_log 2>&1 || die "add user '$user'"
									niutil -createprop / /users/"$user" gid "$gid" 2>&1 || die "add user '$user'"
									niutil -createprop / /users/"$user" uid "$uid" 2>&1 || die "add user '$user'"
									niutil -createprop / /users/"$user" home "$u_home" 2>&1 || die "add user '$user'"
									niutil -createprop / /users/"$user" shell "$u_shell" 2>&1 || die "add user '$user'"
									niutil -createprop / /users/"$user" realname "$u_desc" 2>&1 && suc || die "add user '$user'" 

									# account is locked by default
									niutil -createprop / /users/"$user" passwd "*" 2>&1 && suc || die "add user '$user'" 
									reload_darwin_netinfo
									what_done=1
								;;
							esac
							;;
					esac
					;;
			esac
			;;
		false)
			case "$id_res" in
				0)
					p_echo " User '$user' already exists"
					;;
				*)
					pnnl_echo " Trying to add user '$user'... "
					case "$machine" in
						BSD)
							pw useradd "$user" -g "$group" -c "$u_desc" -d "$u_home" -s "$u_shell" >> $product_log 2>&1 &&
							suc || die $inten
							what_done=1
							;;
						linux|solaris)
							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
							;;
						Darwin)
							niutil -create / /users/"$user" >> $product_log 2>&1 || die "add user '$user'"
							niutil -createprop / /users/"$user" gid "$gid" 2>&1 || die "add user '$user'"
							niutil -createprop / /users/"$user" uid "$uid" 2>&1 || die "add user '$user'"
							niutil -createprop / /users/"$user" home "$u_home" 2>&1 || die "add user '$user'"
							niutil -createprop / /users/"$user" realname "$u_desc" 2>&1 || die "add user '$user'"
							niutil -createprop / /users/"$user" shell "$u_shell" 2>&1 && suc || die "add user '$user'"

							# account is locked by default
							niutil -createprop / /users/"$user" passwd "*" 2>&1 && suc || die "add user '$user'" 
							reload_darwin_netinfo
							what_done=1
								;;
					esac
					;;
			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 

    case "$machine" in
         Darwin)
            nums=`nireport / /"$type" $src_name |grep -v '#NoValue#' | xargs echo -n`
         ;;
         *)
            nums=`cat $src | awk -F: '{print $3}' - | xargs echo -n " "` 
         ;;
    esac

    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
}

reload_darwin_netinfo()
{
    if [ -f /var/run/memberd.pid ]; then
	kill -HUP `cat /var/run/memberd.pid`
    else
	SystemStarter start memberd
    fi

    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
}
initial_conf()
{
	DEMO_VERSION="no"
	PRODNAME="psa"
	PRODUCT_NAME="Plesk"
	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"

	MYSQL_VERS="4.1.18"
	POSTGRESQL_VERS="7.4.11"
	EXTERNAL_PACKAGES="localedata"
	EXTERNAL_PACKAGES_DIR="tmp/packages"

	BUILDER_UID="10007"

	PERL5LIB=/usr/local/psa/lib/perl5/site_perl/5.8.8:/usr/local/psa/lib/perl5/site_perl/5.8.8/mach
	export PERL5LIB

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

	product_version="9.5.4"
	product_db_version="0954"
	product_build="95101209.08"
	conceived_os_vendor=FreeBSD
	conceived_os_version="6.1"
	osrels="fr6.1"

	# This variable contains all versions, which is supported by
	# cumulative upgrade
	known_product_versions="71 75 80 81 82 83 84 86 90 92 93 95"

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

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

        services_group="${product}serv"
        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="/tmp/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
}

# 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()
{
	VARVALUE=`conf_getvar $1 $2`
	if [ "X$VARVALUE" = "X$3" ]; then
		return 0
	elif [ ! -z "X$VARIABLE" ]; then
		conf_rmvar $1 $2
   	fi
	echo "$2	$3" >> $1
	return 0
}

 #default values

product_default_conf()
{

PRODUCT_ROOT_D=/usr/local/psa
PRODUCT_RC_D=/usr/local/etc/rc.d
PRODUCT_ETC_D=/usr/local/etc/psa
PLESK_LIBEXEC_DIR=/usr/local/libexec/plesk-9.0
HTTPD_VHOSTS_D=/usr/local/www/vhosts
HTTPD_CONF_D=dynamic
HTTPD_INCLUDE_D=dynamic
HTTPD_BIN_D=/usr/local/sbin
HTTPD_LOG_D=/var/log
HTTPD_SERVICE=dynamic
QMAIL_ROOT_D=/usr/local/psa/qmail
PLESK_MAILNAMES_D=/usr/local/psa/qmail/mailnames
RBLSMTPD=/usr/local/psa/qmail/bin/rblsmtpd
COURIER_IMAP_ROOT_D=/usr/local/psa/courier-imap
FTPD_CONF=/usr/local/psa/ftpd/etc/proftpd.conf
FTPD_CONF_INC=/usr/local/psa/ftpd/etc/proftpd.include
FTPD_BIN_D=/usr/local/psa/ftpd/bin
FTPD_VAR_D=/usr/local/psa/ftpd/var
FTPD_SCOREBOARD=/usr/local/psa/ftpd/var/scoreboard
NAMED_RUN_ROOT_D=/var/named
NAMED_OPTIONS_CONF=/etc/namedb/named.conf.include.plesk-options
NAMED_ZONES_CONF=/etc/namedb/named.conf.include.plesk-zones
WEB_STAT=/usr/local/psa/webalizer/bin/webalizer
LOGROTATE=/usr/local/psa/logrotate/sbin/logrotate
MYSQL_VAR_D=/var/db/mysql
MYSQL_BIN_D=/usr/local/bin
PGSQL_DATA_D=/usr/local/pgsql/data
PGSQL_BIN_D=/usr/local/bin
DUMP_D=/usr/local/psa/var/dumps
DUMP_TMP_D=/tmp
MAILMAN_ROOT_D=/usr/local/mailman
MAILMAN_VAR_D=/usr/local/mailman
PYTHON_BIN=/usr/local/bin/python2.5
CATALINA_HOME=/usr/local/tomcat5.5
DRWEB_ROOT_D=/usr/local/drweb
DRWEB_ETC_D=/usr/local/etc/drweb
GPG_BIN=/usr/local/bin/gpg
TAR_BIN=/usr/bin/tar
AWSTATS_ETC_D=/usr/local/etc/awstats
AWSTATS_BIN_D=/usr/local/psa/awstats/wwwroot/cgi-bin
AWSTATS_TOOLS_D=/usr/local/psa/awstats/tools
AWSTATS_DOC_D=/usr/local/psa/awstats/wwwroot
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
CGI_PHP_BIN=/usr/local/www/cgi-bin/cgi_wrapper/cgi_wrapper

}

#-*- vim:syntax=sh

register_service(){

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


	rc_service "$1" "enable" "YES" "yes"

	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_relabel_dir()
{
	if ! command -v restorecon >/dev/null 2>&1; then
		return
	fi
	if [ "$1" = "-F" ]; then
		selinux_set_force_arg
		shift
	else
		SELINUX_FORGE_ARG=
	fi
	
	if [ "$1" = "-e" ]; then
		selinux_set_exclude_arg "$2"
		shift 2
	else
		SELINUX_EXCLUDE_ARG=
	fi

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


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


necessary_system_accounts()
{
	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
	add_user_to_group sw-cp-server "$admin_group"

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


#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"
	[ -f "/etc/rsyslog.conf" ] && syslog_conf="/etc/rsyslog.conf" || syslog_conf="/etc/syslog.conf"
	syslog_conf_ng="/etc/syslog-ng/syslog-ng.conf"
	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/rc.d
	PLESK_LIBEXEC_DIR="/usr/local/libexec/plesk-9.0"
	PLESK_DB_DIR="/var/db/plesk"
	POSTFIX_LIBEXEC_DIR="/usr/local/libexec/postfix"

	set_common_params_freebsd 

	detect_vz
}

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_horde_params set_logrotate_params set_mysqld_params set_openssl_params set_qmail_params set_syslog_params set_webalizer_params ; do
		$i
		local res="$?"
		if [ "0$res" -gt 0 ]; then
			return "$res"
		fi
	done
}


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

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
}
upgrade_logrotate_500()
{
    local domains_list dom_id dom_name logrot_id period_type period max_files compress_flag email

	inten="upgrade logrotate config file"
	echo_try ${inten}

	conf_setval "${prod_conf_t}" LOGROTATE "${DEFAULT_LOGROTATE}"
	LOGROTATE="${DEFAULT_LOGROTATE}"

	if [ ! -f ${logrotate_conf} ]; then

		install_logrotate

	else
		sed -e "s|@@PRODUCT_ROOT_D@@|${PRODUCT_ROOT_D}|g" \
			-e "s|@@APACHE_ROOT@@|${APACHE_ROOT}|g" \
			< ${PRODUCT_ROOT_D}/etc/logrotate.conf-upgrade.in \
			>> /etc/${PRODNAME}/logrotate.conf || die "$inten"

		rm -f ${PRODUCT_ROOT_D}/etc/logrotate.conf-upgrade.in || die "$inten"
		rm -f ${PRODUCT_ROOT_D}/etc/logrotate.conf.in || die "$inten"
	fi

	suc

    inten="rebuild domains logrotation configs"
	echo_try ${inten}

    # fetch list of domains with logrotation turned on
    query="SELECT dom_param.dom_id FROM dom_param, log_rotation
		WHERE dom_param.val=log_rotation.id
		    AND dom_param.param='logrotation_id'
		    AND log_rotation.turned_on='true'"

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

    for dom_id in ${domains_list}; do

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

		query="SELECT val FROM dom_param WHERE dom_id='${dom_id}' AND
			    param='logrotation_id'"
		logrot_id=`echo ${query} | ${mysql}`

		query="SELECT period_type FROM log_rotation WHERE id='${logrot_id}'"
		period_type=`echo ${query} | ${mysql}`

		query="SELECT period FROM log_rotation WHERE id='${logrot_id}'"
		period=`echo ${query} | ${mysql}`

		query="SELECT max_number_of_logfiles FROM log_rotation WHERE id='${logrot_id}'"
		max_files=`echo ${query} | ${mysql}`

		query="SELECT compress_enable FROM log_rotation WHERE id='${logrot_id}'"
		compress_flag=`echo ${query} | ${mysql}`

		query="SELECT email FROM log_rotation WHERE id='${logrot_id}'"
		email=`echo ${query} | ${mysql}`

		${PRODUCT_ROOT_D}/admin/sbin/logrot_mng "${dom_name}" off || die
		${PRODUCT_ROOT_D}/admin/sbin/logrot_mng "${dom_name}" on "${period_type}" "${period}" "${max_files}" "${compress_flag}" "${email}" || die

	done  >> "$product_log" 2>&1
	
	suc
}

fix_logrotate_config_600()
{
    logrotate_config="/etc/${PRODNAME}/logrotate.conf"

    xferlog_present=`cat $logrotate_config | grep "^${PRODUCT_ROOT_D}/var/log/xferlog\.processed"`
    maillog_present=`cat $logrotate_config | grep "^${PRODUCT_ROOT_D}/var/log/maillog\.processed"`

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

cat << EOF >> ${logrotate_config}

${PRODUCT_ROOT_D}/var/log/xferlog.processed {
    missingok
    rotate 3
    size    10M
    compress
    nocreate
}
EOF

    fi    

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

cat << EOF >> ${logrotate_config}

${PRODUCT_ROOT_D}/var/log/maillog.processed {
    missingok
    rotate 3
    size    10M
    compress
    nocreate
}
EOF
    fi    

    return 0
}


fix_logrotate_config_710()
{	### national chars in config #39267
	local query args_str

	rm -f "$PRODUCT_ETC_D/etc/logrotate.d/*" >/dev/null 2>&1
	rm -f "$PRODUCT_ETC_D/etc/logrotate.d/*.*" >/dev/null 2>&1

	query="SELECT CONCAT(d.name,',on,',l.period_type,',',l.period,',',l.max_number_of_logfiles,',',l.compress_enable,',',l.email) FROM domains d LEFT JOIN dom_param dp ON (d.id=dp.dom_id AND dp.param='logrotation_id'), log_rotation l WHERE dp.val=l.id AND turned_on='true';"

	for args_str in `echo "$query" | $mysql`; do
		args=`echo "$args_str" | sed -e 's/,/ /g'`
		$UTILS_DIR/logrot_mng $args
	done
}

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
}

upgrade_mailman_600()
{
	local mail_lists mail_list_name i redhat_version path_list path

	if [ "X${machine}" = "Xlinux" ]; then

		if [ "X${linux_distr}" = "Xredhat" ]; then

			redhat_version=`cat /etc/redhat-release | sed -e 's/[^0-9.]*\([0-9.]*\).*/\1/g'`
			if [ "X${redhat_version}" = "X9" ]; then

				inten="fix qmail aliases for mailman mail lists"
				echo_try ${inten}

				query="SELECT id FROM MailLists"
				mail_lists=`echo ${query} | ${mysql}`

				for i in ${mail_lists}; do

					query="SELECT name FROM MailLists WHERE id='${i}'"
					mail_list_name=`echo ${query} | ${mysql}`

					query="select domains.name from domains, MailLists where domains.id=MailLists.dom_id and MailLists.id='${i}'"
					mail_list_domain=`echo ${query} | ${mysql}`

					${UTILS_DIR}/listmng turn "${mail_list_name}" "${mail_list_domain}" off
					rm -f "${PLESK_MAILNAMES_D}/${mail_list_domain}"/qmail-owner-${mail_list_name}
					${UTILS_DIR}/listmng turn "${mail_list_name}" "${mail_list_domain}" on

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

				suc

				if test "`$UTILS_DIR/listmng checkpresence mailman|tail -2|tr '\n' n`" = 0n0n; then
					pnnl_echo " Setting mailman to autostart... "
					/sbin/chkconfig mailman on >>"$product_log" 2>&1
					if test "$?" = 0; then
						p_echo "done"
					else
						echo " /sbin/chkconfig mailman oh failed" >>"$product_log"
						echo " probably mailman will not run at bootup" >>"$product_log"
						echo " you should start it manually" >>"$product_log"
						p_echo "failed. check installation log."
					fi
				fi

			fi
		fi
	fi

	path_list="/usr/lib /var/lib /var ${PRODUCT_ROOT_D}"
	for path in $path_list; do
		if test -x "$path/mailman/bin/newlist"; then
			conf_setval /etc/psa/psa.conf MAILMAN_ROOT_D "$path/mailman"
		fi
		if test -d "$path/mailman/archives"; then
			conf_setval /etc/psa/psa.conf MAILMAN_VAR_D "$path/mailman"
		fi
	done
}
upgrade_mailman_deb_750()
{
#This upgrade work for Debian only. 
	if [ "X${linux_distr}" != "Xdebian" ]; then
		return 
	fi

	local mail_lists mail_list_name i redhat_version path_list path

	inten="fix qmail aliases for mailman mail lists"
	echo_try ${inten}

	query="SELECT id FROM MailLists"
	mail_lists=`echo ${query} | ${mysql}`

	for i in ${mail_lists}; do

		query="SELECT name FROM MailLists WHERE id='${i}'"
		mail_list_name=`echo ${query} | ${mysql}`

		query="select domains.name from domains, MailLists where domains.id=MailLists.dom_id and MailLists.id='${i}'"
		mail_list_domain=`echo ${query} | ${mysql}`

		${UTILS_DIR}/listmng turn "${mail_list_name}" "${mail_list_domain}" off
		rm -f "${PLESK_MAILNAMES_D}/${mail_list_domain}"/qmail-owner-${mail_list_name}
		${UTILS_DIR}/listmng turn "${mail_list_name}" "${mail_list_domain}" on

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

	suc

	if test "`$UTILS_DIR/listmng checkpresence mailman|tail -2|tr '\n' n`" = 0n0n; then
		pnnl_echo " Setting mailman to autostart... "
		/usr/sbin/invoke-rc.d mailman start >>"$product_log" 2>&1

		if test "$?" = 1; then
			p_echo "done"
		else
			echo " /usr/sbin/invoke-rc.d mailman start failed" >>"$product_log"
			echo " probably mailman will not run at bootup" >>"$product_log"
			echo " you should start it manually" >>"$product_log"
			p_echo "failed. check installation log."
		fi
	fi

	path_list="/usr/lib /var/lib /var ${PRODUCT_ROOT_D}"

	for path in $path_list; do
		if test -x "$path/mailman/bin/newlist"; then
			conf_setval /etc/psa/psa.conf MAILMAN_ROOT_D "$path/mailman"
		fi
		if test -d "$path/mailman/archives"; then
			conf_setval /etc/psa/psa.conf MAILMAN_VAR_D "$path/mailman"
		fi
	done
}
upgrade_mailman_86()
{
	if [ "X$machine" = "XBSD" -a "$do_upgrade" = "1" ]; then
		conf_setvar "$prod_conf_t" "MAILMAN_ROOT_D" "/usr/local/mailman" 
		conf_setvar "$prod_conf_t" "MAILMAN_VAR_D" "/usr/local/mailman" 
	fi
}

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
}


# mysql

set_mysqld_params()
{
	mysql_user="mysql"
	mysql_UID=3306
	mysql_group="mysql"
	mysql_GID=3306

	product_db_sql="$PRODUCT_ETC_D/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-server" ]; then
	    mysql_service="mysql-server"
	elif [ -x "${PRODUCT_RC_D}/mysql-server.sh" ]; then
	    mysql_service="mysql-server.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
}

true mysql_start mysql_stop mysql_status

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
			unset IFS
			if mysql_test_connection; then
				IFS=$IFS_OLD
				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
	IFS=$IFS_OLD
	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
}

# 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

	mysql_test_connection 60 || die "$inten"
	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="$PRODUCT_DEFAULT_PASSWORD"
}

#Invoke mysql
mysql()
{
	mysql_anydb -D$mysql_db_name "$@"
}

mysql_anydb()
{
	if test -z "$DB_IS_MYSQL41_COMPATIBLE"; then
		mysql41_init
	fi

	if [ "$DB_IS_MYSQL41_COMPATIBLE" != "compatible" -a "X$machine" != "XBSD" ]; then
		mysql41_exec_wrapper $mysql_client $mysql_user $mysql_passwd $mysql_args "$@" 2>>"$product_log"
	else
		$mysql_client $mysql_user $mysql_passwd $mysql_args "$@" 2>>"$product_log"
	fi

	local status=$?
	if [ $status -gt 0 ]; then
		$mysql_client $mysql_user $mysql_passwd $mysql_args -D$mysql_db_name $mysql_args_raw -e "show innodb status" >>"$product_log" 2>&1
	fi
	return $status
}

# the function removes the "character set xxx" and "collate xxx" construction
# from -e * arguments, if there are any.
# otherwise, it removes the same things from standard input
mysql41_exec_wrapper()
{
	perl -e '$has_command = 0;
		$program = $ARGV[0];
		splice (@ARGV, 0, 1);
		sub remove_charsets($)
		{
			$refStr = shift;
			$$refStr =~ s/\b(medium|long|tiny)?text\s+character\s+set\s+binary(\s+collate\s+[\w]+)?\b/ $1blob /ig;
            $$refStr =~ s/\b(medium|long|tiny)?text\s+character\s+set\s+[\w]+\s+collate\s+[\w]+_bin\b/ $1blob /ig;
			$$refStr =~ s/(\bcharacter\s+set\s+binary(\s+collate\s+[\w]+)?\b)/ binary /ig;
			$$refStr =~ s/(\bcharacter\s+set\s+[\w]+\s+collate\s+[\w]+_bin\b)/ binary /ig;
			$$refStr =~ s/(\b(character\s+set|collate)\s+[\w]+\b)//ig;
		}
		foreach $n (0 .. $#ARGV) {
			if ($ARGV[$n] eq "-e") {
				$has_command = 1;
				remove_charsets \($ARGV[$n + 1]);
			}
		}
		if ($has_command) {
			exec $program, @ARGV or die "Cannot execute mysql";
		} else {
			open out_command, "|-", $program, @ARGV or die "Cannot start mysql";
			while (<STDIN>) {
				remove_charsets \($_);
				print out_command $_;
			}
			close out_command or die($! ? "Mysql returned an error: $!" : "Mysql exited with non-zero 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 "$@"
}

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
}

mysql41_init()
{
	# not_installed is the default state
	# we must init it to avoid endless cycle
	DB_IS_MYSQL41_COMPATIBLE=not_installed
	if ! mysql_anydb </dev/null >>"$product_log" 2>&1; then
		return
	fi

	if db_test --any-db "SHOW VARIABLES LIKE 'version'" '$2 !~ /^(3|4\.0)\./'; then
		# if database is not yet initiailized, assume it compatible
		# otherwise, check the flag
		if
			db_test --any-db "SHOW DATABASES" '/^psa$/' 			&& db_test "SHOW TABLES" '/^misc$/' 			&& ! db_test "SELECT val FROM misc WHERE param = 'mysql41_compatible'" '/true/'
		then
			DB_IS_MYSQL41_COMPATIBLE='not_compatible'
		else
			DB_IS_MYSQL41_COMPATIBLE='compatible'
		fi
	fi
}

mysql41_before_db_install()
{
	[ -n "$DB_IS_MYSQL41_COMPATIBLE" ] || mysql41_init

	if [ "$DB_IS_MYSQL41_COMPATIBLE" != not_installed ]; then
		DB_IS_MYSQL41_COMPATIBLE=compatible
	fi
}

###	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 -9 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"
		mysql41_init
		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=`echo ${prev_db_version} | awk '{ print substr($0, 1, 3); }'`

    if [ "X${prev_db_short_version}" != "X0${prev_short_version}" -a 		 "X${product_db_version}" != "X${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"
	mysql41_before_db_install
	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
	if [ "$DB_IS_MYSQL41_COMPATIBLE" = compatible ]; then
		db_do "REPLACE INTO misc(param, val) VALUES('mysql41_compatible', 'true')"
	fi
}

db_install_dashboard_presets()
{
	local inten
	inten="install initial Desktop presets"
	mysql < "$PRODUCT_ETC_D/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

	#bug #101745
	sys="${machine}_${linux_distr}_${conceived_os_version}"
	case "$sys" in
	    linux_redhat_el3|linux_redhat_3*|linux_fedora_3|linux_fedora_2|linux_fedora_1)
		return 0
	    ;;
	    *)
	    ;;
	esac

	if ! (test -f $my_cnf && grep -q '^\[mysqld\]' "$my_cnf"); then
		echo "[mysqld]" >> $my_cnf
		echo "set-variable=local-infile=0" >> $my_cnf
		return
	fi

	awk_script='/^\[mysqld\]$/{print; print "set-variable=local-infile=0"; next;} {print}'
	if ! grep -q '^set-variable=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
}

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"


	product_install_db
	update_mysql4_permissions
	mysql_fix_remove_empty_users
	if test "x${PLESK_VZ}" = "x1"; then
		(tune_vz_mysql "$my_cnf")
	fi
	if [ "$linux_distr" = "debian" -o "$linux_distr" = "ubuntu" ]; then
# Bug 129316
		pleskrc mysql restart
	fi
}

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 $*
}
#!/bin/sh

__tune_vz_mysql_sig_handler() {
    local rc=$?
    trap - EXIT
    rm -f -- "$1"
    exit $rc
}

tune_vz_mysql()
{
    # check if we in VZ environment
    test "x$PLESK_VZ" = "x1" || return 0;
    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;
}

function doOptimization()
{
  if (have_bdb && 0 == skipbdb) {
    printf("skip-bdb\n\n");
    changed=1;
  }
  if (have_innodb && 0 == ibp_size) {
    print "set-variable = innodb_buffer_pool_size=2M"
    changed=1;
  }
  if (have_innodb && 0 == iamp_size) {
    print "set-variable = innodb_additional_mem_pool_size=500K"
    changed=1;
  }
  if (have_innodb && 0 == ilb_size) {
    print "set-variable = innodb_log_buffer_size=500K"
    changed=1;
  }
  if (have_innodb && 0 == thread_conc_set) {
    print "set-variable = innodb_thread_concurrency=2"
    changed=1;
  }
}

function adjustSetting(varstr, varname, minsize, sizestr)
{
  if (match(varstr,"^[[:space:]]*" varname "[[:space:]]*=[[:space:]]*")) {
    if (have_innodb) {
      size = getsize(substr(varstr, RSTART+RLENGTH));
      if (minsize < size) {
        changed = 1;
        print "#", $0;
        print "set-variable = ", varname "=" sizestr;
      }
    } else {
      # we do not have innodb so we need to disable this setting
      print "#", $0;
      changed = 1;
    }
    return 1;
  }
  return 0;
}

BEGIN {
  insect=0;    # within one of server sections
  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
  changed=0;   # already changed smth
  have_bdb = (tolower(have_bdb) == "yes") ;
  have_innodb = (tolower(have_innodb) == "yes") ;
}
/^[[:space:]]*\[.+\]/ {
  if (0 != insect) {
# need to close a previous section
    doOptimization();
    # section is ended. Reset variables
    skipbdb   = 0;
    ibp_size  = 0;
    iamp_size = 0;
    ilb_size  = 0;
    thread_conc_set=0;
    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) {
    doOptimization();
  }

  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
}




upgrade_mysql_priveleges_tables()
{
	### THIS FUNCTION ADDS EXTENTED PRIVELEGES FOR SUPPORTING MySQYL 4 
	local mysql mysql_raw mysql_db_name pdefinition

	echo "$MYSQL_VERS" | grep '^4\.' >/dev/null 2>&1
	res=$?
	if [ "x$machine" != "xBSD" -o 0$res -ne 0 ]; then
		return
	fi

	mysql="$MYSQL_BIN_D/mysql -N -uadmin -p$admin_passwd -Dmysql "
	mysql_raw="$MYSQL_BIN_D/mysql -N -B -uadmin -p$admin_passwd -r -Dmysql "
	mysql_db_name="mysql"

	$mysql <<-END_OF_DATA >/dev/null 2>&1 || die "convert privilege tables to MyISAM format"
		ALTER TABLE user type=MyISAM;
		ALTER TABLE db type=MyISAM;
		ALTER TABLE host type=MyISAM;
		ALTER TABLE func type=MyISAM;
		ALTER TABLE columns_priv type=MyISAM;
		ALTER TABLE tables_priv type=MyISAM;
	END_OF_DATA

	db_fix_add_column mysql.user File_priv "enum('N','Y') NOT NULL"

	$mysql <<-END_OF_DATA >>"$product_log" 2>&1 || die "create func table"
	alter table user change password password char(41) NOT NULL;
	CREATE TABLE if not exists func (
	  name char(64) binary DEFAULT '' NOT NULL,
	  ret tinyint(1) DEFAULT '0' NOT NULL,
	  dl char(128) DEFAULT '' NOT NULL,
	  type enum ('function','aggregate') NOT NULL,
	  PRIMARY KEY (name)
	);
	END_OF_DATA

	pdefinition="ENUM('N', 'Y') NOT NULL"
	for table in user host db; do
		db_fix_add_column --init File_priv "mysql.$table" Grant_priv "$pdefinition"
		db_fix_add_column --init Create_priv "mysql.$table" References_priv "$pdefinition"
		db_fix_add_column --init Create_priv "mysql.$table" Alter_priv "$pdefinition"
		db_fix_add_column --init Create_priv "mysql.$table" Index_priv "$pdefinition"
	done

	#
	# The second alter changes ssl_type to new 4.0.2 format
	#

	db_fix_add_column mysql.user ssl_type "ENUM('','ANY','X509', 'SPECIFIED') NOT NULL"
	db_fix_add_column mysql.user ssl_cipher "BLOB NOT NULL"
	db_fix_add_column mysql.user x509_issuer "BLOB NOT NULL"
	db_fix_add_column mysql.user x509_subject "BLOB NOT NULL"

	$mysql <<-END_OF_DATA >>"$product_log" 2>&1 || die "alter user.ssl_type type"
		ALTER TABLE user MODIFY ssl_type enum('','ANY','X509', 'SPECIFIED') NOT NULL;
	END_OF_DATA

	#
	# Create tables_priv and columns_priv if they don't exists
	#

	$mysql <<-END_OF_DATA >>"$product_log" 2>&1 || die "create tables_priv or columns_priv table"
	CREATE TABLE IF NOT EXISTS tables_priv (
	  Host char(60) DEFAULT '' NOT NULL,
	  Db char(60) DEFAULT '' NOT NULL,
	  User char(16) DEFAULT '' NOT NULL,
	  Table_name char(60) DEFAULT '' NOT NULL,
	  Grantor char(77) DEFAULT '' NOT NULL,
	  Timestamp timestamp(14),
	  Table_priv set('Select','Insert','Update','Delete','Create','Drop','Grant','References','Index','Alter') DEFAULT '' NOT NULL,
	  Column_priv set('Select','Insert','Update','References') DEFAULT '' NOT NULL,
	  PRIMARY KEY (Host,Db,User,Table_name)
	);
	CREATE TABLE IF NOT EXISTS columns_priv (
	  Host char(60) DEFAULT '' NOT NULL,
	  Db char(60) DEFAULT '' NOT NULL,
	  User char(16) DEFAULT '' NOT NULL,
	  Table_name char(60) DEFAULT '' NOT NULL,
	  Column_name char(59) DEFAULT '' NOT NULL,
	  Timestamp timestamp(14),
	  Column_priv set('Select','Insert','Update','References') DEFAULT '' NOT NULL,
	  PRIMARY KEY (Host,Db,User,Table_name,Column_name)
	);
	END_OF_DATA

	#
	# Name change of Type -> Column_priv from MySQL 3.22.12
	#

	$mysql <<-END_OF_DATA >>"$product_log" 2>&1 || die "change columns_priv.Type type"
	ALTER TABLE columns_priv change Column_priv Column_priv set('Select','Insert','Update','References') DEFAULT '' NOT NULL;
	END_OF_DATA

	#
	# Add the new 'type' column to the func table.
	#

	db_fix_add_column mysql.func type "ENUM('function','aggregate') NOT NULL"

	#
	# Change the user,db and host tables to MySQL 4.0 format
	#

	prev_cname=alter_priv
	for column in "Show_db_priv=select_priv" "Super_priv=process_priv" \
				  "Execute_priv=process_priv" "Create_tmp_table_priv='Y'" \
				  "Lock_tables_priv='Y'" "Repl_slave_priv=file_priv" \
				  "Repl_client_priv=file_priv"
	do
		cname=`echo "$column"|cut -f1 -d=`
		cval=`echo "$column"|cut -f2 -d=`
		db_fix_add_column --init "$cval WHERE mysql.user<>''" mysql.user $cname \
			"ENUM('N','Y') DEFAULT 'N' NOT NULL AFTER $prev_cname"
		prev_cname=$cname
	done

	# Add fields that can be used to limit number of questions and connections
	# for some users.
	db_fix_add_column mysql.user max_questions "INT(11) NOT NULL AFTER x509_subject"
	db_fix_add_column mysql.user max_updates "INT(11) UNSIGNED NOT NULL AFTER max_questions"
	db_fix_add_column mysql.user max_connections "INT(11) UNSIGNED NOT NULL AFTER max_updates"

	#
	# Add Create_tmp_table_priv and Lock_tables_priv to db and host
	#

	db_fix_add_column mysql.db Create_tmp_table_priv "ENUM('N','Y') DEFAULT 'N' NOT NULL"
	db_fix_add_column mysql.db Lock_tables_priv "ENUM('N','Y') DEFAULT 'N' NOT NULL"
	db_fix_add_column mysql.host Create_tmp_table_priv "ENUM('N','Y') DEFAULT 'N' NOT NULL"
	db_fix_add_column mysql.host Lock_tables_priv "ENUM('N','Y') DEFAULT 'N' NOT NULL"

	#
	# Fix the new bugs discovered by new tests (for Bug #2874 Grant table bugs ) 
	#

	$mysql <<-END_OF_DATA >>"$product_log" 2>&1 || die "change column types"
	alter table db change Db Db char(64) binary DEFAULT '' NOT NULL;
	alter table host change Db Db char(64) binary DEFAULT '' NOT NULL;
	alter table user change password Password char(41) binary NOT NULL, change max_questions max_questions int(11) unsigned DEFAULT 0  NOT NULL;
	alter table tables_priv change Db Db char(64) binary DEFAULT '' NOT NULL, change Host Host char(60) binary DEFAULT '' NOT NULL, change User User char(16) binary DEFAULT '' NOT NULL, change Table_name Table_name char(64) binary DEFAULT '' NOT NULL;
	alter table columns_priv change Db Db char(64) binary DEFAULT '' NOT NULL, change Host Host char(60) binary DEFAULT '' NOT NULL, change User User char(16) binary DEFAULT '' NOT NULL, change Table_name Table_name char(64) binary DEFAULT '' NOT NULL, change Column_name Column_name char(64) binary DEFAULT '' NOT NULL;

	alter table db comment='Database privileges';
	alter table host comment='Host privileges;  Merged with database privileges';
	alter table user comment='Users and global privileges';
	alter table func comment='User defined functions';
	alter table tables_priv comment='Table privileges';
	alter table columns_priv comment='Column privileges';
	END_OF_DATA
	db_fix_add_key tables_priv Grantor
}

set_new_permissions_for_db_users()
{
	local query

	### checking for existing of extended permissions
	query='SELECT Show_db_priv FROM mysql.user'
	echo "$query" | $mysql >/dev/null 2>&1
	if [ 0$? -ne 0 ]; then
		return
	fi

	### set new permissions for plesk db users
	query="SELECT login FROM db_users"
	for login in `echo "$query" | $mysql`; do
		query="UPDATE mysql.user SET Show_db_priv='N', Super_priv='N', Create_tmp_table_priv='N', Lock_tables_priv='N', Execute_priv='N', Repl_slave_priv='N', Repl_client_priv='N' WHERE User='$login'"
		echo "$query" | $mysql >>"$product_log" 2>&1
	done

	### set new datasbases access permissions for plesk db users
	query="SELECT CONCAT(db.name,',',dbu.login) FROM data_bases db, db_users dbu WHERE db.id=dbu.db_id"
	for row in `echo "$query" | $mysql`; do
		db_name=`echo $row | awk -F ',' '{print $1}'`
		login=`echo $row | awk -F ',' '{print $2}'`
		query="UPDATE mysql.db SET Create_tmp_table_priv='Y', Lock_tables_priv='Y' WHERE Db='$db_name' AND User='$login'"
		echo "$query" | $mysql >>"$product_log" 2>&1
	done
}

upgrade_mysql_710()
{
	upgrade_mysql_priveleges_tables
	set_new_permissions_for_db_users
}

set_named_params()
{
	# set up default values
	bind_UID=53
	bind_GID=53
	bind_user="bind";
	bind_group="bind";

	# 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/namedb/named.conf"
	rndc_conf="/etc/namedb/rndc.conf"
	rndc_namedb_conf="/etc/namedb/rndc.conf"
	rndc_bind_conf="/etc/bind/rndc.conf"
}

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()
{
        case "$machine$os_version" in
	    linux*)
		# sysconfig_named not needed for SuSE
		if [ "X${linux_distr}" = "Xsuse" ]; then
			return 0
		fi

		if [ "X${linux_distr}" = "Xdebian" ]; then
			sysconfig_named_debian
		else
			sysconfig_named_redhat
		fi		
	    ;;
	    BSD*)       
		echo_try 'add named configurations to rc.conf'
		register_service "named" 
		rc_service "named" "flags" "-u $bind_user -c $named_conf"
		rc_service "named" "pidfile" "default"

		suc

		#bug 107233
		#Change symlink to config dir.
		pleskrc named restart
		pleskrc named stop

		#bug 109648
		#Remove listen-on string if listen only to loopback.
		if [ -f $named_conf ]; then
			sed -e 's|^[[:space:]]*listen-on[[:space:]]*{[[:space:]]*127.*};||g' 				< $named_conf >$named_conf.bak
			mv -f $named_conf.bak $named_conf
		fi

		echo_try "generate local zone files"
		
		#Generate local zone files.
		if [ -f /etc/namedb/make-localhost ]; then
		    chmod 744 /etc/namedb/make-localhost
		    sh -c "cd /etc/namedb && ./make-localhost"
		fi
		suc

		if [ "X$std_to_pkg" = "X1" ]; then
			conf_setvar ${prod_conf_t} NAMED_RUN_ROOT_D /var/named
		fi

		needed_to_restart_syslog="yes"
	    ;;
	    *)
	    ;;
	esac

	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

	pleskrc named start
}

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
	if [ "$linux_distr" = "suse" ]; then
		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"
	fi

	suc
}

named_conf_add_includes()
{
	touch "$NAMED_ZONES_CONF"
	touch "${NAMED_RUN_ROOT_D}/${NAMED_ZONES_CONF}"
	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
}

install_named()
{
	install_named_native
}

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
}

true named_status_linux_debian
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
}

create_all_zones()
{
        get_pid named false
        old_named_pid=$common_var
        if [ $old_named_pid -lt 2 ]; then
		pleskrc named start
	fi

# generate all direct zones
        query="select name from domains;"
        for dom_name in `echo $query | $mysql`          ; do
                 $UTILS_DIR/dnsmng update $dom_name without-reverse >> $product_log 2>&1
        done
# generate all reverse zones
	query="select DISTINCT d.name from domains d, dns_recs r where d.id=r.dom_id and r.type='PTR' \
	    group by elt( r.opt/8, substring(host,1,locate('.',host,1)), \
	    substring(host,1,locate('.',host,locate('.',host,1)+1)), \
	    substring(host,1,locate('.',host,locate('.',host,locate('.',host,1)+1)+1)) );"
        for dom_name in `echo $query | $mysql`          ; do
                 $UTILS_DIR/dnsmng update $dom_name >> $product_log 2>&1
        done

	pleskrc named stop
}

upgrade_named_131()
{

        p_echo
        p_echo
        p_echo "===> Upgrading Named Server"

	create_all_zones
}

upgrade_named_500()
{

        p_echo
        p_echo
        p_echo "===> Upgrading Named Server"

	copy_named_localtime
}

# Function for rebuild zones with upper and mixed case characters.
zonefiles_tolower_conversion(){
	inten='convert DNS zones to lower case'
	echo_try ${inten}

	### store named.conf file to named.conf.upgrader_saved
	[ -f ${NAMED_RUN_ROOT_D}/etc/named.conf.upgrader_saved ] \
	|| mv -f ${NAMED_RUN_ROOT_D}/etc/named.conf ${NAMED_RUN_ROOT_D}/etc/named.conf.upgrader_saved

	### recreate named.conf file
	[ -f ${NAMED_RUN_ROOT_D}/etc/named.conf.default ] \
	&& cp -f ${NAMED_RUN_ROOT_D}/etc/named.conf.default ${NAMED_RUN_ROOT_D}/etc/named.conf \
	|| echo > ${NAMED_RUN_ROOT_D}/etc/named.conf

	### recreate zones for all domains
	dom_query="SELECT name FROM domains;"
	for dom in `echo ${dom_query} | ${mysql}`; do
		rm -f ${NAMED_RUN_ROOT_D}/var/${dom} >/dev/null 2>&1
		rm -f ${NAMED_RUN_ROOT_D}/var/`echo ${dom} | tr 'A-Z' 'a-z'` >/dev/null 2>&1
		$UTILS_DIR/dnsmng update "$dom"
	done
	p_echo "done"	
}

upgrade_named_710(){
	zonefiles_tolower_conversion
}
set_openssl_params()
{
    openssl_psa_sbin=${PRODUCT_ROOT_D}/admin/sbin/openssl;
    openssl_psa_bin=${PRODUCT_ROOT_D}/admin/bin/openssl;
    openssl_std_bin=/usr/bin/openssl;
}

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" ] && mv $i $i.old
	done;
}

pma__configure()
{
	local controluser controlpass pmadb
	local bookmarktable column_info history pdf_pages relation table_coords table_info

	controluser=''

	if [ -f "$PHPMYADMIN_CONFIG.save" ]; then
		# looking for values of following variables in config.inc.php.save
		#    $cfg['Servers'][$i]['controluser']
		#    $cfg['Servers'][$i]['controlpass']
		#    $cfg['Servers'][$i]['pmadb']
		#    $cfg['Servers'][$i]['bookmarktable']
		#    $cfg['Servers'][$i]['relation']
		#    $cfg['Servers'][$i]['table_info']
		#    $cfg['Servers'][$i]['table_coords']
		#    $cfg['Servers'][$i]['pdf_pages']
		#    $cfg['Servers'][$i]['column_info']
		#    $cfg['Servers'][$i]['history']
		pma__set_values_from_config 'controluser' 'controlpass' 'pmadb' 'bookmarktable' 'relation' 'table_info' 'table_coords' 'pdf_pages' 'column_info' 'history'
	fi

	if [ -z "$controluser" ]; then
		pma__set_default_values
		pma__set_random_values
		pma__create_pmadb
	fi

	# write new config.inc.php
	sed -e "`pma__sed_script`" < "$PHPMYADMIN_CONFIG.tpl" > "$PHPMYADMIN_CONFIG"
}

pma__set_values_from_config()
{
	eval `pma__read_values "$@"`
}

pma__read_values()
{
        [ -f $PHPMYADMIN_CONFIG.save ] && /usr/local/psa/bin/sw-engine-pleskrun  -r '
                        try {
                                error_reporting(0);
                                $GLOBALS["db_host"] = "localhost";
                                function in_vzcp_proxy() { return false; };
                                require_once("'$PHPMYADMIN_CONFIG.save'");
                                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"
}

pma__set_random_values()
{
	local pma__random_suffix

	# generate random controluser and pmadb
	while true; do
		pma__random_suffix=`$PRODUCT_ROOT_D/admin/sbin/random_str | awk '{ print substr($1, 0, 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="`$PRODUCT_ROOT_D/admin/sbin/random_str | awk '{ print substr($1, 0, 16) }'`"
}

pma__create_pmadb()
{
	local create_tables_sql
	local inten
	inten="create pmadb"
	echo_try $inten
	# detect MySQL version
	case `mysql -e "SHOW VARIABLES LIKE 'version'" | awk '/^version/ { print $2 }'` in
		3.*.*|4.0.*|4.1.0|4.1.1)
			create_tables_sql="$PHPMYADMIN_D/scripts/create_tables.sql"
			;;
		4.*.*)
			create_tables_sql="$PHPMYADMIN_D/scripts/create_tables_mysql_4_1_2+.sql"
			;;
		*)
			create_tables_sql="$PHPMYADMIN_D/scripts/create_tables.sql"
			;;
	esac
	# 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\
	"
}

poppassd_super_server_config()
{
	local action="$1"

	case "$superserver" in
	    inetd)
		poppassd_rec="poppassd stream tcp nowait/1000 root /usr/libexec/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                   = KEEPALIVE
server                  = $PRODUCT_ROOT_D/admin/sbin/poppassd
}"
		;;
	    *)
		    die "Super server name unknown"
		;;
	esac

	super_server_action "$action" poppassd "$poppassd_rec"
}
set_pgsql_params()
{
    pgsql_user="pgsql"
    pgsql_group="pgsql"
    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/local"
    PGSQL_DATA_D="/usr/local/pgsql/data"
    NEW_PGSQL_VERSION="7.4.11"

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

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
}

upgrade_postgresql_755()
{
	local pg_login pg_passwd

	if ! $PRODUCT_ROOT_D/admin/sbin/pg_manage --check-installed; then
		p_echo "PostgreSQL not installed, skipping upgrade step"
		return 0
	fi

	ps ax | grep postmaster >/dev/null
	if [ 0$? -ne 0 ]; then
	    #wokaround for BSD. bug #103711. rc-scripts was moved into /usr/local/etc/rc.d
	    #but upgrader was started before install psa-postgresql-configurator
	    if [ "X$machine" = "XBSD" ]; then
		local PRODUCT_RC_D="$PRODUCT_ROOT_D/rc.d"
	    fi

		if [ -e ${PRODUCT_RC_D}/postgresql ]; then
			${PRODUCT_RC_D}/postgresql start
		elif [ -e ${PRODUCT_RC_D}/rhdb ]; then
			${PRODUCT_RC_D}/rhdb start
		else
			warn "Unable to locate postgresql rc script"
		fi
		sleep 5
	fi
	
	$PRODUCT_ROOT_D/admin/sbin/pg_manage --start
	sleep 10

	postgres_fix_users
	
	$PRODUCT_ROOT_D/admin/sbin/pg_manage --stop
}

# this functions MUST be idempotent
postgres_fix_users()
{
	inten="upgrade PostgreSQL database user accounts"
	echo_try $inten

	db_select "SELECT admin_login FROM DatabaseServers WHERE id = 2"
	pg_login=$db_select_output
	db_select "SELECT admin_password FROM DatabaseServers WHERE id = 2"
	pg_passwd=$db_select_output
	if [ "X$pg_login" != "X" -a "X$pg_passwd" != "X" ]; then
		PSA_PASSWORD="$pg_passwd" $PRODUCT_ROOT_D/admin/sbin/pg_manage \
			--create-admin-login "$pg_login" || die "create admin account"
	fi
    mysql_raw -e "select name from data_bases where db_server_id = 2" |
        $PRODUCT_ROOT_D/admin/sbin/pg_manage --repair-db-groups \
		|| die "repair user groups"
    mysql_raw -e "select db_users.login, data_bases.name from db_users, data_bases \
        where db_users.db_id = data_bases.id and data_bases.db_server_id = 2" |
        $PRODUCT_ROOT_D/admin/sbin/pg_manage --repair-db-users \
		|| die "repair user accounts"
	suc
}
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_freebsd
}

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

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

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
}


# vim:syntax=sh

mail_restore_all()
{
	# temporary solution to close #143977 and #144076: three keys to turn on
	if [ ! -e "$PRODUCT_ROOT_D/version" ]; then
		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/local/libexec/plesk-9.0/mailsrv_entities_dump" ]; then
		echo "/usr/local/libexec/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/local/libexec/plesk-9.0/mail_restore" ]; then
		echo "/usr/local/libexec/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/local/libexec/plesk-9.0/mail_restore --without-spam
	suc
	# A temporary solution for http://bugs.plesk.ru/show_bug.cgi?id=143786
	"${PRODUCT_ROOT_D}/admin/sbin/mailmng" --restart-service
}

true exim_status_linux_debian
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
}

set_mail_params()
{
	HANDLERS_USER="mhandlers-user"
	MAIL_USERGROUP="popuser"
}
## 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/local/libexec/plesk-9.0/mail_dk_restore
}

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
}

true syslog_status_linux_debian
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
}
#qmail

set_qmail_params()
{
    QMAIL_DIR="/usr/local/psa/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="/usr/local/psa/qmail"
    fi

    mm_mailgroup=110

    qmail_service="qmail"
    qmail_extra_cmd=""
    qmail_log="/var/log/maillog"
}

## @@constructor set_qmail_params

set_syslog_params()
{
	syslog_service="syslogd"
# 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"
	else
		syslog_binary="/sbin/syslogd"
	fi
}
## @@constructor set_syslog_params

qmail_super_server_config()
{
    local action="$1"
    local service="$2"

    case "$superserver" in
	inetd)
		qmail_inetd_templates
		;;
	xinetd)
		qmail_xinetd_templates
		;;
	*)
		die "Super server name unknown"
		;;
    esac

   	eval "template=\$${service}_rec"

    super_server_action "$action" "$service" "$template"
}

qmail_inetd_templates()
{
	maxconn=''
	if [ "$linux_distr" = "debian" ]; then 
	    maxconn='.1000'
	fi

	smtp_rec="smtp stream tcp nowait$maxconn root $QMAIL_DIR/bin/tcp-env tcp-env /usr/bin/env SMTPAUTH=1 END=1 $QMAIL_DIR/bin/relaylock $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $QMAIL_DIR/bin/true $QMAIL_DIR/bin/cmd5checkpw $QMAIL_DIR/bin/true"

	smtps_rec="smtps stream tcp nowait$maxconn root $QMAIL_DIR/bin/tcp-env tcp-env /usr/bin/env SMTPAUTH=1 END=1 $QMAIL_DIR/bin/relaylock $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $QMAIL_DIR/bin/true $QMAIL_DIR/bin/cmd5checkpw $QMAIL_DIR/bin/true"

	submission_rec="submission stream tcp nowait$maxconn qmaild $QMAIL_DIR/bin/tcp-env tcp-env /usr/bin/env SUBMISSION=1 SMTPAUTH=1 END=1 $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $QMAIL_DIR/bin/true $QMAIL_DIR/bin/cmd5checkpw $QMAIL_DIR/bin/true"

}

qmail_xinetd_templates()
{
    local TRUE_BIN
    TRUE_BIN=$QMAIL_DIR/bin/true
smtp_rec="service smtp
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = root
	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
	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
	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_131()
{

	p_echo
	p_echo
	p_echo "===> Upgrading Qmail Server"

	# move mailnames, control, users, aliases

	PREV_QMAIL_ROOT_D="$PREV_PRODUCT_ROOT_D/qmail"
	if [ ! -d "$PREV_QMAIL_ROOT_D" ]; then
		die "Unable to find '$PREV_QMAIL_ROOT_D' directory"
	fi

	for move_dir in alias control users mailnames; do

		if ! empty_dir "$PREV_QMAIL_ROOT_D/$move_dir/"; then
			inten="move $move_dir directory"
			echo_try "$inten"
			mv -f `get_ls full "$PREV_QMAIL_ROOT_D/$move_dir/"` "$QMAIL_ROOT_D/$move_dir/" && suc || die "$inten"
		fi

	done

	# create attachments repository directories: 
	# ... qmail/mailnames/<domain>/<mailname>/@attachments
	# if no

	inten="add attacments repository for autoresponders"
	echo_try "$inten"

	for domname in `get_ls full "$PLESK_MAILNAMES_D"`; do

		if [ ! -d $domname ]; then
			continue;
		fi

		for mailname in `get_ls full "$domname"`; do

			if [ ! -d "$mailname" ]; then
				continue;
			fi

			rep_dir="$mailname/@attachments"

			if [ -d "$rep_dir" ]; then
				continue;
			fi

			mkdir -p "$rep_dir" >> "$product_log" 2>&1 || die "$inten"

			chown $pop_user:$pop_group "$rep_dir" >> "$product_log" 2>&1 || die "$inten"
			chmod 700 "$rep_dir" >> "$product_log" 2>&1 || die "$inten"

		done;

	done && suc || die "$inten"

	qmail_users_homes
}
upgrade_qmail_500()
{
	inten="move stunnel certificate to qmail control directory"

	# stunnel is obsoletted, copy his certificate to qmail control directory
	QMAIL_SERVER_CERT=$QMAIL_ROOT_D/control/servercert.pem
	QMAIL_CLIENT_CERT=$QMAIL_ROOT_D/control/clientcert.pem

	if [ ! -f "${QMAIL_SERVER_CERT}" ]; then

		# here we must define certificate location
		# old certificate of stunnel is now belongs to qmail
		if [ -f "${PRODUCT_ROOT_D}/stunnel/stunnel.pem" ]; then
			mv -f "${PRODUCT_ROOT_D}/stunnel/stunnel.pem" "${QMAIL_SERVER_CERT}" || die $inten
		else

			if [ -f "${PRODUCT_ROOT_D}/stunnel.std_sav/stunnel.pem" ]; then
				mv -f "${PRODUCT_ROOT_D}/stunnel.std_sav/stunnel.pem" "${QMAIL_SERVER_CERT}" || die $inten
			else
				cp -f "${PRODUCT_ROOT_D}/admin/conf/httpsd.pem" "${QMAIL_SERVER_CERT}" || die $inten
			fi

		fi

		ln -s "${QMAIL_SERVER_CERT}" "${QMAIL_CLIENT_CERT}" || exit 1
		chown 640 "${QMAIL_SERVER_CERT}" || exit 1
		chown qmaild:qmail "${QMAIL_SERVER_CERT}" || exit 1

	fi

	# enable smtps service in super server
	if [ -f ${RBLSMTPD} ]; then

		query="select val from misc where param='rbl'";
		rbl_state=`echo ${query} | $mysql`

		if [ "X${rbl_state}" = "Xtrue" ]; then

			query="select val from misc where param='rbl_server'";
			rbl_server=`echo ${query} | $mysql`

			if [ "X$rbl_server" != "X" ]; then
			    	qmail_super_server_config register smtp on "$rbl_server"
			    	qmail_super_server_config register smtps on "$rbl_server"
			else
			    	qmail_super_server_config register smtps
			fi

		else
			qmail_super_server_config register smtps
		fi

	else
		qmail_super_server_config smtps
	fi
}

#!/bin/sh

upgrade_qmail_600()
{
	QMAIL_BADMAILFROM_FILE=$QMAIL_ROOT_D/control/badmailfrom

	if [ ! -f "${QMAIL_BADMAILFROM_FILE}" ]; then
		return 0
	fi

	cat "${QMAIL_BADMAILFROM_FILE}" | awk '{
		first_character = substr($1, 1, 1);
		if (first_character != "#") {

			if ((first_character == "@") || (first_character == ".")) {
				entry_length = length($0);
				entry = substr($0, 2, entry_length - 1);
			} else {
				entry = $1;
			};

			query = "REPLACE INTO badmailfrom (domain) VALUES (\047" entry "\047);"
			print query
		};
	}' | $mysql

	return 0
}

upgrade_qmail_752()
{
	if [ "X$machine" = "XBSD" ]; then
		set_mail_params
		fix_qmail_perms_752
	fi
}

fix_qmail_perms_752()
{
	### fix permissions for mailnames dirs
	chown -Rh $MAIL_USERGROUP:$MAIL_USERGROUP $PRODUCT_ROOT_D/qmail/mailnames/
	chown root:qmail $PRODUCT_ROOT_D/qmail/mailnames
	chmod 755 $PRODUCT_ROOT_D/qmail/mailnames
}
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()
{
	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
}
install_quota()
{
	if [ "X$DEMO_VERSION" = "Xyes" ]; then 
		return 0;
	fi
	
	if [ "X$PLESK_VZ" = "X1" ]; then        # we are in virtuozzo
		p_echo "Quotacheck not needed for Virtuozzo"
		return 0;
	fi
	p_echo
	p_echo "===> Installing Quotas"

	# get filesystem for HTTPD_VHOSTS_D
	vhosts_fs=`"$UTILS_DIR/get_fs" "$HTTPD_VHOSTS_D"`
	if [ $? -ne 0 ]; then
		p_echo "Unable to get filesystem for $HTTPD_VHOSTS_D"
		return 0
	fi
	
	inten="change quota limits"
	echo_try "$inten"

	case "$machine" in
		linux)
			dep_usrquota="usrquota"
			
			# mtab
			awk "/^\/dev.*[[:space:]].*[[:space:]](ext3|ext2|xfs)[[:space:]].*/ \
				{ if ( (\$4 ~ /$dep_usrquota/) || (( \$2 != \"$vhosts_fs\" ) && ( \$2 != \"$vhosts_fs/\" )) ) \
				{ print } else { printf \"%s\t$vhosts_fs\t%s\t%s,$dep_usrquota\t%s\t%s\n\", \$1,\$3,\$4,\$5,\$6 }; next }
				{print}
				" <$mtab >$mtab.tmp  &&
			mv -f $mtab.tmp $mtab || die "$inten" >> $product_log 2>&1
			;;
		BSD)
			dep_usrquota="userquota"

			# add enable_quotas to rc.conf
			p_echo 'Add enable_quotas="YES" into rc.conf'

			rc_service "enable" "quotas" "YES"
			;;
		Darwin)
			touch "$vhosts_fs/.quota.ops.user"
			touch "$vhosts_fs/.quota.ops.group"
			quotacheck -a >> $product_log 2>&1
			quotaon -a    >> $product_log 2>&1
			;;
		     *) 
			die "Unsupported OS"
			;;
	esac

	# fstab
	case "$machine" in
		Darwin)
			;;
		*)
			# backup fstab to restore it in case of quota is not supported
			cp -f $fstab $fstab.psa_saved
			awk "/^(\/dev|LABEL=|UUID=).*[[:space:]].*[[:space:]](ufs|ext3|ext2|xfs)[[:space:]].*/ \
					{ if ( (\$4 ~ /$dep_usrquota/) || (( \$2 != \"$vhosts_fs\" ) && ( \$2 != \"$vhosts_fs/\" )) ) \
					{ print } else { printf \"%s\t$vhosts_fs\t%s\t%s,$dep_usrquota\t%d\t%s\n\", \$1,\$3,\$4,\$5,\$6 }; next }
					{print}
					" <$fstab >$fstab.tmp  &&
			mv -f $fstab.tmp $fstab && suc || die "$inten" >> $product_log 2>&1
			;;
	esac

	# check on xfs filesystem
	#vhosts_type=`mount | awk '{ if ( $3 == "'$vhosts_fs'" ) { print $5 } }'`
	case "$machine" in
		Darwin)
			;;
		*)
			vhosts_type=`awk '{ if ( $2 == "'$vhosts_fs'" ) { print $3 } }' < $fstab`
			if [ "X$vhosts_type" = "Xxfs" ]; then

				# on xfs it's needed to remount $vhosts_fs (for other fs no differences)
				inten="remount $vhosts_fs"
				mount -o remount $vhosts_fs >> $product_log 2>&1
				if [ $? -ne 0 ]; then
					[ "X$vhosts_fs" != "X/" ] && ( umount $vhosts_fs; mount $vhosts_fs )
					if [ $? -ne 0 ]; then
						minor_problem=1
						p_echo "Quota will support on your system after reboot."
						warn "${inten}"
					fi
				fi

				p_echo "$vhosts_fs has a $vhosts_type type. The quotacheck is not needed."
				return 0
			fi
			;;
	esac

	if [ -z "$PLESK_QUOTACHECK_OFF" ]; then
		# Check quota and then turn quota on.
		p_echo "Run quotacheck. This may take some time."
		case "$machine" in
			linux)
				if [ -f $vhosts_fs/aquota.user ]; then
					quotacheck "$vhosts_fs" -vunfm >> "$product_log" 2>&1
				else
					quotacheck "$vhosts_fs" -vunfmc >> "$product_log" 2>&1
				fi
				;;
			BSD)
				quotacheck -vu "$vhosts_fs" >> "$product_log" 2>&1
				;;
			Darwin)
				quotacheck -vu "$vhosts_fs" >> "$product_log" 2>&1
				;;
		esac

		if [ $? != 0 ]; then 
			p_echo "Errors occured during quotacheck run."
		fi
	else
		p_echo "'PLESK_QUOTACHECK_OFF' enviroment variable is set to '$PLESK_QUOTACHECK_OFF' that is why quotacheck is skipped."
	fi

	inten="check for quota support"
	echo_try "$inten"
	
	support_quota=`"$UTILS_DIR/usermng" --isquotable 2>>"$product_log"`

	if [ "X$support_quota" != "X0" ]; then
		# restore fstab
		mv -f $fstab.psa_saved $fstab
		
		minor_problem=1
		p_echo "Quota is not supported by your operating system."
		p_echo "Probably kernel has not compiled in quota support."
		warn "${inten}"
	else
		rm -f $fstab.psa_saved
		suc "Supported"
	fi

}

upgrade_quota_500()
{
	install_quota

	#set quota for those users who have non-zero value in corresponded column
	
	"$PRODUCT_ROOT_D/admin/sbin/usermng" --isquotable >> "$product_log" 2>&1
	if [ $? -eq 0 ]; then
		# get sysusers with non-zero quota
		query_nz_quota="SELECT id FROM sys_users WHERE quota!=0;"
		sys_users_list=`echo "$query_nz_quota" | $mysql`
		
		#get sysuser info & set quota
		for sys_user_id in $sys_users_list; do
			query_login="SELECT login FROM sys_users WHERE id='$sys_user_id'"
			query_quota="SELECT quota FROM sys_users WHERE id='$sys_user_id'"

			login=`echo "$query_login" | $mysql`
			quota=`echo "$query_quota" | $mysql`
			
			"$PRODUCT_ROOT_D/admin/sbin/usermng" quota "$login" "$quota" >> "$product_log" 2>&1
		done
		
	fi
}


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 functions list constructors --------------------
PREPARE_FUNCTIONS_20()
{
    backup_old_root_200
}
## @@preupgraders PREPARE_FUNCTIONS_20

PREPARE_FUNCTIONS_25()
{
    backup_old_root_250
}
## @@preupgraders PREPARE_FUNCTIONS_25

PREPARE_FUNCTIONS_50()
{
    backup_old_root_500
    clean_old_skins_500
}
## @@preupgraders PREPARE_FUNCTIONS_50

PREPARE_FUNCTIONS_60()
{
	return
}
## @@preupgraders PREPARE_FUNCTIONS_60

PREPARE_FUNCTIONS_70()
{
    db_check_700
	if [ "x$machine" = "xBSD" ]; then
		backup_db_with_old_pgsql
	fi
}
## @@preupgraders PREPARE_FUNCTIONS_70

PREPARE_FUNCTIONS_71()
{
    if test "_$KEYUPDATE_71_STANDARD_BUILD" = "_yes"; then
		keyupdate_main_710_std
    fi
}
## @@preupgraders PREPARE_FUNCTIONS_71

PREPARE_FUNCTIONS_75()
{
    db_check_750
}
## @@preupgraders PREPARE_FUNCTIONS_75

PREPARE_FUNCTIONS_80()
{
	return
}
## @@preupgraders PREPARE_FUNCTIONS_80

PREPARE_FUNCTIONS_81()
{
    return
}
## @@preupgraders PREPARE_FUNCTIONS_81

PREPARE_FUNCTIONS_82()
{
    return
}
## @@preupgraders PREPARE_FUNCTIONS_82

PREPARE_FUNCTIONS_83()
{
    return
}
## @@preupgraders PREPARE_FUNCTIONS_83

PREPARE_FUNCTIONS_84()
{
    return
}
## @@preupgraders PREPARE_FUNCTIONS_84

PREPARE_FUNCTIONS_86()
{
	return
}
## @@preupgraders PREPARE_FUNCTIONS_86

PREPARE_FUNCTIONS_90()
{
	return
}
## @@preupgraders PREPARE_FUNCTIONS_90

PREPARE_FUNCTIONS_92()
{
	return
}
## @@preupgraders PREPARE_FUNCTIONS_92

PREPARE_FUNCTIONS_93()
{
	return
}
## @@preupgraders PREPARE_FUNCTIONS_93

PREPARE_FUNCTIONS_95()
{
	return
}
## @@preupgraders PREPARE_FUNCTIONS_95

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=''

	# line to prevent preupgrade functions from being optimized out
	true PREPARE_FUNCTIONS_20 PREPARE_FUNCTIONS_25 PREPARE_FUNCTIONS_50 PREPARE_FUNCTIONS_60 PREPARE_FUNCTIONS_70 PREPARE_FUNCTIONS_71 PREPARE_FUNCTIONS_75 PREPARE_FUNCTIONS_80 PREPARE_FUNCTIONS_81 PREPARE_FUNCTIONS_82 PREPARE_FUNCTIONS_83 PREPARE_FUNCTIONS_84 PREPARE_FUNCTIONS_86 PREPARE_FUNCTIONS_90 PREPARE_FUNCTIONS_92 PREPARE_FUNCTIONS_93 PREPARE_FUNCTIONS_95 

	"PREPARE_FUNCTIONS_${INSTALLED_VERSION}"

	stop_before_upgrade

	phpmyadmin_config_backup
}

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()
{
    dfile="$DUMP_D/mysql.preupgrade.dump.gz"
    if test -f $dfile; then
	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"
}
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 --------------------
UPGRADE_FUNCTIONS_13()
{
	upgrade_db_131
	upgrade_common_131
	upgrade_named_131
	upgrade_admin_131
	upgrade_apache_131
	upgrade_qmail_131
	upgrade_crontab_131
	upgrade_after_131
}
## @@upgraders UPGRADE_FUNCTIONS_13

UPGRADE_FUNCTIONS_20()
{
	:
}
## @@upgraders UPGRADE_FUNCTIONS_20

UPGRADE_FUNCTIONS_50()
{
	upgrade_named_500
	rebuild_protected_directories_500
	add_mod_python_directive_500
	upgrade_db_500
	upgrade_vhosts_500
	move_sys_skel_500
	make_sessions_dir_500
	upgrade_quota_500
	remove_old_semaphores_500
	upgrade_logrotate_500
	upgrade_qmail_500
	move_logo_files_500
	check_rootchain_cert_500
	upgrade_dumpd_500
	remove_reconfigurator_500
}
## @@upgraders UPGRADE_FUNCTIONS_50

UPGRADE_FUNCTIONS_60()
{
	fix_logrotate_config_600
	upgrade_vhosts_600
	upgrade_apache_600
	upgrade_db_600
	upgrade_mailman_600
	upgrade_proftpd_600
	upgrade_remove_utils_600
	upgrade_qmail_600
	upgrade_webalizer_rpm_600
	create_all_zones
}
## @@upgraders UPGRADE_FUNCTIONS_60

UPGRADE_FUNCTIONS_70()
{
	upgrade_vhosts_700
	upgrade_db_700
	register_old_keys
	install_key_d
	upgrade_db_700_newkey
	upgrade_vhosts_700_newkey
	create_all_zones
	remove_old_creation_utilities_700
	move_logo_files_700
	upgrade_proftpd_600
}
## @@upgraders UPGRADE_FUNCTIONS_70

UPGRADE_FUNCTIONS_71()
{
	upgrade_vhosts_710
	upgrade_db_710
	upgrade_crontab_710
	upgrade_users_710
	upgrade_named_710
	upgrade_mysql_710
	fix_logrotate_config_710
	move_locales_files_710
}
## @@upgraders UPGRADE_FUNCTIONS_71

UPGRADE_FUNCTIONS_75()
{
	db_mysql_check_upgrade_prepare_old
	db_mysql_check_upgrade
	upgrade_db_750
	upgrade_qmail_752
	upgrade_common_752
	upgrade_vhosts_752
	upgrade_admin_750
	upgrade_conf_754
	upgrade_mailman_deb_750
	upgrade_vhosts_754
	upgrade_postgresql_755
	upgrade_horde_754
	upgrade_proftpd_754
}
## @@upgraders UPGRADE_FUNCTIONS_75


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
	upgrade_apache_800
}
## @@upgraders UPGRADE_FUNCTIONS_80

UPGRADE_FUNCTIONS_81()
{
	fix_crontab_810
	db_fix_81
	# 8.1 -> 8.2
	upgrade_db_81
}
## @@upgraders UPGRADE_FUNCTIONS_81

UPGRADE_FUNCTIONS_82()
{
	upgrade_proftpd_820
	db_fix_82
	#upgrade 8.2 -> 8.3
	upgrade_awstats_82
	upgrade_db_82
}
## @@upgraders UPGRADE_FUNCTIONS_82

UPGRADE_FUNCTIONS_83()
{
	upgrade_cf_83
	db_fix_83
	pbm_create_certificate	
}
## @@upgraders UPGRADE_FUNCTIONS_83

UPGRADE_FUNCTIONS_84()
{
	db_fix_84
	upgrade_awstats_84
}
## @@upgraders UPGRADE_FUNCTIONS_84

UPGRADE_FUNCTIONS_86()
{
	key_upgrade_86
	db_fix_86
	db_create_default_templates
	db_update_notifications
	db_generate_guids_82

	set_mail_params
	upgrade_dk_86
	upgrade_mailman_86
}
## @@upgraders UPGRADE_FUNCTIONS_86

UPGRADE_FUNCTIONS_90()
{
	db_pmm_dashboard_90
	db_fix_90
}
## @@upgraders UPGRADE_FUNCTIONS_90

UPGRADE_FUNCTIONS_92()
{
	add_db_changes 920
	upgrade_mailman_86
}
## @@upgraders UPGRADE_FUNCTIONS_92

UPGRADE_FUNCTIONS_93()
{
	:
}
## @@upgraders UPGRADE_FUNCTIONS_93

UPGRADE_FUNCTIONS_95()
{
	set_swkey_params
	key_upgrade_cmd
	db_update_dashboard_951

	# TP ~32790 clear garbage from exp_event table 
	db_update_exp_event
}

## @@upgraders UPGRADE_FUNCTIONS_95

# DO NOT RUN BEFORE UPGRADE!!!
cumulative_upgrade()
{
    local UPGRADE_STARTED

    # Flag for skipping already upgraded versions
    UPGRADE_STARTED="0"
    INSTALLED_VERSION=`form_undotted_version ${prev_version}`

	# line to prevent upgrade functions from being optimized out
	true UPGRADE_FUNCTIONS_13 UPGRADE_FUNCTIONS_20 UPGRADE_FUNCTIONS_50 UPGRADE_FUNCTIONS_60 UPGRADE_FUNCTIONS_70 UPGRADE_FUNCTIONS_71 UPGRADE_FUNCTIONS_75 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_93 UPGRADE_FUNCTIONS_95 

    echo "===> Cumulative upgrade has been started"
    for i in ${known_product_versions}; do

		if [ "X${UPGRADE_STARTED}" = "X0" -a ${INSTALLED_VERSION} -lt ${i} ]; then
			echo "upgrade. 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" ]; then
			"UPGRADE_FUNCTIONS_${i}"
#		else
#			echo "Skipping version ${i}"
		fi

	done;

	if [ "X${UPGRADE_STARTED}" = "X1" ]; then
		license_show_request
		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
}


#vhosts

set_vhosts_params()
{
	SKEL_DIR="$HTTPD_VHOSTS_D/.skel"
#	SKEL_CERT_DIR="$SKEL_DIR/0/cert"
#	SKEL_CERT="$SKEL_CERT_DIR/httpd.pem"
	return 0
}

set_vhosts_perms()
{
	inten="set permissions for default virtual host directory"

	if [ -d "${HTTPD_VHOSTS_D}" ]; then

		chown root:0 "${HTTPD_VHOSTS_D}" || die ${inten}
		chmod 755 "${HTTPD_VHOSTS_D}" || die ${inten}

		if [ -d "${HTTPD_VHOSTS_D}/default" ]; then

			chown root:0 "${HTTPD_VHOSTS_D}/default" || die ${inten}
			chmod 755 "${HTTPD_VHOSTS_D}/default" || die ${inten}

			find "${HTTPD_VHOSTS_D}/default" -type d -exec chown root:0 {} \; -exec chmod 755 {} \;
			find "${HTTPD_VHOSTS_D}/default" -type f -exec chown root:0 {} \; -exec chmod 644 {} \;
			find "${HTTPD_VHOSTS_D}/default/cgi-bin" -type f -exec chown root:0 {} \; -exec chmod 755 {} \;
		else
			p_echo "Warning! Default vhost direcrory not found. Do you have problems of domain creation in the past?"
		fi
	else
		die "${inten}: virtual hosts direcrory not found"
	fi
}

install_vhosts()
{
	p_echo
	p_echo
	cd "$PRODUCT_ROOT_D" || die
	p_echo "===> Installing Virtual Hosts Directory"

	set_vhosts_params

	# extract default skeleton (for install, not for upgrade)
	if [ "X$do_upgrade" = "X0" ]; then
	  if [ ! -d $SKEL_DIR ]; then 
		mkdir $SKEL_DIR
	  else 
		p_echo "Warning! The skeleton\'s directory was not created" 
	  fi 

	  $UTILS_DIR/skelmng --install-default --id 0 >> "$product_log" 2>&1
	fi

	set_vhosts_perms
}

extract_vhosts()
{
	if [ ! -d "$HTTPD_VHOSTS_D" ]; then
		inten="create Virtual Hosts directory"
		echo_try $inten
		mkdir -p "$HTTPD_VHOSTS_D" && suc || die "$inten"
	fi
	inten="untar Virtual Hosts directory structure"
	echo_try $inten

	# use --keep-old-files option to avoid skeleton and default page rewriting if exists
	${tar} xzf "$PRODUCT_ROOT_D/tmp/vhosts.tar.gz" --keep-old-files -C "$HTTPD_VHOSTS_D" 2>/dev/null || [ $? -eq 2 ] || die "$inten"

	# the file must be rewritten at every upgrade
	${tar} xzf "$PRODUCT_ROOT_D/tmp/vhosts.tar.gz" -C "$HTTPD_VHOSTS_D" ./default/htdocs/preview.php 2>/dev/null || [ $? -eq 2 ] || die "$inten"

	suc
}

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
	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" \
			-type d -name error_docs -maxdepth 2 \
	| while read dir; do
		file="$dir/$document"
		if ! test -e "$file"; then
			install -o 0 -g 0 -m 644 "$wrkdir/error_docs/$document" "$file" >>"$product_log" 2>&1 \
			|| die "install document $document in $dir"
		fi
	done
	if test $? -ne 0; then exit 1; fi

	rm -rf "$wrkdir" >> "$product_log" 2>&1

	suc
}
upgrade_vhosts_500()
{
	local dom_name login vhost_dir nfiles query query1 query_wu_sel

    inten="upgrade virtual hosts"
    echo_try ${inten}
	
	# select only domains with virtual hosting
	query="SELECT d.id FROM domains d, hosting h WHERE d.id=h.dom_id AND d.htype='vrt_hst';"

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

		# query for domain name and login
		
		query1="select s.login from hosting h, sys_users s where h.dom_id='$dom_id' and h.sys_user_id=s.id;"
		login=`echo "$query1" | ${mysql}`

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

		vhost_dir="$HTTPD_VHOSTS_D/$dom_name"

		# move directories to new locations
		
		mkdir -p "$vhost_dir/statistics"

		mv -f "$vhost_dir/logs"        "$vhost_dir/statistics"
		
		[ -e "$vhost_dir/ftpstat" ] 	&& \
		mv -f "$vhost_dir/ftpstat"     "$vhost_dir/statistics/anon_ftpstat" #
		[ -e "$vhost_dir/webstat" ] 	&& \
		mv -f "$vhost_dir/webstat"     "$vhost_dir/statistics" #
		[ -e "$vhost_dir/webstat-ssl" ]	&& \
		mv -f "$vhost_dir/webstat-ssl" "$vhost_dir/statistics" #
		
		# set new permissions on vhost dirs (used make_vrt to avoid code duplication)
		
		"$UTILS_DIR/make_vrt" ${dom_name} ${login} force		
		
		# set permissions for files, which weren't affected by make_vrt
		
		# web users
		query_wu_sel="SELECT s.login FROM web_users w, sys_users s WHERE w.dom_id='$dom_id' AND s.id=w.sys_user_id;"
		for wu_name in `echo "$query_wu_sel" | ${mysql}`; do
			chown "$wu_name":"$services_group" "$vhost_dir/web_users/$wu_name"
			chmod 0750 "$vhost_dir/web_users/$wu_name"
		done
		# protected dirs
		nfiles=`ls "$vhost_dir/pd" | wc -l`
		if [ $nfiles -ne 0 ]; then
			chown "$apache_user":"$apache_group" "$vhost_dir/pd/"*
			chmod 0400 "$vhost_dir/pd/"*
		fi

	done >> "$product_log" 2>&1
	
	suc
}
fix_webusers_permissions_600()
{
	local dom_name login vhost_dir nfiles query query1 query_wu_sel

	dom_id=$1
	dom_name=$2
	vhost_dir=$3

	inten="fix web users permissions for domain ${dom_name}"

	query_wu_sel="SELECT s.login FROM web_users w, sys_users s WHERE w.dom_id='$dom_id' AND s.id=w.sys_user_id;"

	for wu_name in `echo "$query_wu_sel" | ${mysql}`; do

		webuser_dir=$vhost_dir/web_users/$wu_name
		if [ -d "${webuser_dir}" ]; then
			chown "$wu_name":"$services_group" "${webuser_dir}" || report_problem "chown $wu_name:$services_group ${webuser_dir} command failed" "it is better to set correct ownership to web user directory, or web user ${wu_name} from ${dom_name} may experience problems"
			chmod 0750 "${webuser_dir}" || report_problem "chmod 0750 ${webuser_dir} command failed" "it is better to set correct permissions to ${webuser_dir}, otherwise security problem may occur"
		else
			report_problem "Web user ${wu_name} from domain ${dom_name} has no home directory ${webuser_dir}" "hint: create directory ($wu_name":"$services_group ownership and 0750 access mask) or delete web user from control panel"
		fi
	done
}

create_subdomains_directories_600()
{
	local dom_name vhost_dir subdomains_directory
	dom_name=$1
	vhost_dir=$2

	inten="create subdomains directory for domain ${dom_name}"
	if [ ! -d "${vhost_dir}" ]; then
		report_problem "domain ${dom_name} has hosting, but host directory ${vhost_dir} does not exist" "will try to creade it"
		mkdir -p "${vhost_dir}" || report_problem "unable to create virtual host directory: mkdir -p ${vhost_dir} comman failed" "hint: create directory ${vhost_dir} and set permissions to root:0 0755" && return 0
		chmod 0755 "${vhost_dir}" || report_problem "chmod 0755 ${vhost_dir} command failed." "hint: set permissions root:0 0755 to ${vhost_dir} directory" && return 0
		chown root:0 "${vhost_dir}" || report_problem "chown root:0 ${vhost_dir} command failed." "set root:0 ownership to ${vhost_dir} directory" && return 0
	fi

	subdomains_directory="${vhost_dir}"/subdomains
	mkdir -p "${subdomains_directory}" || report_problem "mkdir -p ${subdomains_directory} command failed when trying to ${inten}" "hint: create ${subdomains_directory} directory  and set following permissions: root:0 0755" && return 0
	chmod 0755 "${subdomains_directory}" || report_problem "chmod 0755 ${subdomains_directory} command failed when trying to ${inten}" "hint: set root:0 0755 permissions to ${subdomains_directory} directory " && return 0
	chown root:0 "${subdomains_directory}" || report_problem "chown root:0 ${subdomains_directory} command failed when trying to ${inten}" "set root:0 ownership to ${subdomains_directory} directory " && return 0
}

# bugfix 18139
# "Client and Domain user are able to remove the quota file for anon_ftp"
mv_quota_2_subdir_600()
{
	local dom_name quota_dir
	dom_name=$1

	inten="fix .quota file placement"
	quota_dir="$HTTPD_VHOSTS_D/$dom_name/anon_ftp/incoming/quotadir"

	# check that this directory doesn't exist
	if [ -e "$quota_dir" ]; then
		return
	fi

	# create root-owned incoming/quotadir/.undeletable
	mkdir -p -m 0755 "$quota_dir" || warn $inten
	chown "root":"$services_group" "$quota_dir" || warn $inten
	touch "$quota_dir/.undeletable" || warn $inten
	chown "root":"0" "$quota_dir/.undeletable" || warn $inten
	chmod 0644 "$quota_dir/.undeletable" || warn $inten

	# try to move .quota into new location
	if [ -f "$HTTPD_VHOSTS_D/$dom_name/anon_ftp/incoming/.quota" ]; then

		mv "$HTTPD_VHOSTS_D/$dom_name/anon_ftp/incoming/.quota" "$quota_dir" || warn $inten
		chown "$anonftp_user":"$clients_group" "$quota_dir/.quota" || warn $inten
		chmod 0664 "$quota_dir/.quota" || warn $inten
	fi
}

# Creation of the private hosting subdirectory
create_private_dir_600()
{
	local dom_name dom_id private_dir query login
	dom_id=$1
	dom_name=$2

	inten="create private hosting subdirectory for domain $dom_name"
	private_dir="$HTTPD_VHOSTS_D/$dom_name/private"

	# check that this directory doesn't exist
	if [ -e "$private_dir" ]; then
		if [ ! -d "$private_dir" ]; then
			warn "$inten: $private_dir already exists and it's not directory"
			return
		fi
		return
	fi

	# create user-owned private subdirectory
	mkdir -p -m 0700 "$private_dir" || warn "Can't $inten: can't mkdir $private_dir"

# place README file in directory
content=<< EOREADME
Access to this directory is available only to you.
The directory cannot be accessed via any web or system services, so you can
store any private information here.
EOREADME

	echo "$content" > "$private_dir/README.txt" || warn "Can't $inten: can't create $private_dir/README.txt"

	# retrieve system user login
	query="SELECT s.login FROM sys_users AS s, hosting AS h WHERE h.dom_id='$dom_id' AND h.sys_user_id=s.id;"

	login=`echo "$query" | ${mysql}`

	# chowns newly created directory and README file
	chown -R "$login":0 "$private_dir" || warn "Can't $inten: can't chown -R $login:0 $private_dir"
}

create_sitebuilder_directory_600()
{
	local vhost_dir sitebuilder_directory vhost_user
	dom_name=$1
	vhost_dir=$2

	inten="create reserved sitebuilder directory for domain ${dom_name}"

	query="SELECT sys_users.login FROM sys_users, hosting, domains WHERE sys_users.id = hosting.sys_user_id AND hosting.dom_id = domains.id AND domains.name='${dom_name}'"
	vhost_user=`echo "$query" | ${mysql}`

	sitebuilder_directory="${vhost_dir}"/httpdocs/picture_library
	mkdir -p "${sitebuilder_directory}" || (report_problem "mkdir -p ${sitebuilder_directory} command failed when trying to ${inten}" "hint: create ${sitebuilder_directory} directory  and set following permissions: ${vhost_user}:psacln 0755" && return 0)
	chmod 0755 "${sitebuilder_directory}" || (report_problem "chmod 0755 ${sitebuilder_directory} command failed when trying to ${inten}" "hint: set ${vhost_user}:psacln 0755 permissions to ${sitebuilder_directory} directory " && return 0)
	chown ${vhost_user}:psacln "${sitebuilder_directory}" || (report_problem "chown ${vhost_user}:psacln ${sitebuilder_directory} command failed when trying to ${inten}" "set ${vhost_user}:psacln ownership to ${sitebuilder_directory} directory " && return 0)
}

upgrade_vhosts_600()
{
	# common part for domains with physical hosting
	query="SELECT d.id FROM domains d, hosting h WHERE d.id=h.dom_id AND d.htype='vrt_hst';"

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

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

		vhost_dir="$HTTPD_VHOSTS_D/$dom_name"

		mv_quota_2_subdir_600 "${dom_name}"
		fix_webusers_permissions_600 "${dom_id}" "${dom_name}" "${vhost_dir}"
		create_subdomains_directories_600 "${dom_name}" "${vhost_dir}"
		create_private_dir_600 "${dom_id}" "${dom_name}"
		create_sitebuilder_directory_600 "${dom_name}" "${vhost_dir}"
	done
}

upgrade_mambo()
{
	local target_dir query row app_id dom_id dom_type htdocs_directory install_prefix dom_name subdom_name owner file_name dir_name script_name msg
	local old_version old_release new_version new_release
	local ApplicationFullName
	local pkg_id
	local tmp_dir app_cgitory_dir
	local httpdocs_files cgi_bin_files

	old_version="4.5"
	old_release="1.0.4"
	new_version="4.5"
	new_release="1.0.7"

	ApplicationFullName="Mambo-${new_version}-${new_release}"

	query="SELECT id FROM SiteAppPackages WHERE name='Mambo' AND version='${new_version}' AND release='${new_release}';"
	pkg_id=`echo "$query" | $mysql`

	if [ -z "${pkg_id}" ]; then
		echo "Site application package ${ApplicationFullName} is not installed."
		return 0
	fi

	app_cgitory_dir="${PRODUCT_ROOT_D}/var/cgitory/${ApplicationFullName}"

	if [ ! -d ${app_cgitory_dir} ]; then
		echo "Site application package ${ApplicationFullName} does not exist."
		return 0
	fi

	httpdocs_files="${app_cgitory_dir}/apps/httpdocs-files.tar"
	cgi_bin_files="${app_cgitory_dir}/apps/cgi-bin-files.tar"

	[ -r ${httpdocs_files} ] || [ -r ${cgi_bin_files} ] || return 0

	tmp_dir="/tmp/${ApplicationFullName}"

	rm -rf ${tmp_dir}
	mkdir -p ${tmp_dir}/httpdocs
	mkdir -p ${tmp_dir}/cgi-bin

	[ -r ${httpdocs_files} ] && tar -xf ${httpdocs_files} -C ${tmp_dir}/httpdocs
	[ -r ${cgi_bin_files} ] && tar -xf ${cgi_bin_files} -C ${tmp_dir}/cgi-bin

	query="SELECT app.id, app.dom_id, app.dom_type, app.htdocs_directory, app.install_prefix FROM SiteAppPackages pkg, SiteApps app WHERE pkg.id=app.app_id AND pkg.name='Mambo' AND pkg.version='${old_version}' AND pkg.release='${old_release}';"
	for row in `echo "$query" | $mysql | awk '{print $1","$2","$3","$4","$5}'`; do
		app_id=`echo $row | sed -e 's/,/ /g' | awk '{print $1}'`
		dom_id=`echo $row | sed -e 's/,/ /g' | awk '{print $2}'`
		dom_type=`echo $row | sed -e 's/,/ /g' | awk '{print $3}'`
		htdocs_directory=`echo $row | sed -e 's/,/ /g' | awk '{print $4}'`
		install_prefix=`echo $row | sed -e 's/,/ /g' | awk '{print $5}'`
		case $dom_type in
			"domain")
				query="SELECT d.name, su.login FROM domains d, hosting h, sys_users su WHERE d.id=h.dom_id AND h.sys_user_id=su.id AND d.id='${dom_id}' AND d.htype='vrt_hst';"
				row=`echo "$query" | $mysql`
				[ ! -z "${row}" ] || continue
				dom_name=`echo $row | awk '{print $1}'`
				owner=`echo $row | awk '{print $2}'`
				target_dir="${HTTPD_VHOSTS_D}/${dom_name}/"
				msg="domain ${dom_name}"
				;;
			"subdomain")
				query="SELECT d.name, s.name, su.login FROM subdomains s, domains d, sys_users su WHERE s.dom_id=d.id AND s.sys_user_id=su.id AND s.id='${dom_id}' AND d.htype='vrt_hst';"
				row=`echo "$query" | $mysql`
				[ ! -z "${row}" ] || continue
				dom_name=`echo $row | awk '{print $1}'`
				subdom_name=`echo $row | awk '{print $2}'`
				owner=`echo $row | awk '{print $3}'`
				target_dir="${HTTPD_VHOSTS_D}/${dom_name}/subdomains/${subdom_name}"
				msg="subdomain ${subdom_name}.${dom_name}"
				[ ! -z "${subdom_name}" ] || continue
				;;
			*)
				continue
				;;
		esac

		[ ! -z "${dom_name}" ] || continue

		pnnl_echo "Update Mambo for ${msg}... "
		for dir_name in ${target_dir}/vault_scripts/${install_prefix} ${target_dir}/${htdocs_directory}/${install_prefix} ${target_dir}/cgi-bin/${install_prefix}; do
			[ -d ${dir_name} ] || mkdir -p ${dir_name}
		done

		chown -R ${owner}:psacln ${tmp_dir}

		for script_name in reconfigure preuninstall postuninstall; do
			[ -r ${app_cgitory_dir}/scripts/${script_name} ] && \
				cp -f ${app_cgitory_dir}/scripts/${script_name} ${target_dir}/vault_scripts/${install_prefix} && \
					chgrp psacln ${target_dir}/vault_scripts/${install_prefix}/${script_name}
		done

		touch -cm ${target_dir}/${htdocs_directory}/${install_prefix}/*
		cp -rup ${tmp_dir}/httpdocs/* ${target_dir}/${htdocs_directory}/${install_prefix} > /dev/null 2>&1
		cp -rf ${tmp_dir}/httpdocs/* ${target_dir}/${htdocs_directory}/${install_prefix} > /dev/null 2>&1

		touch -cm ${target_dir}/cgi-bin/${install_prefix}/*
		cp -rup ${tmp_dir}/cgi-bin/* ${target_dir}/cgi-bin/${install_prefix} > /dev/null 2>&1
		cp -rf ${tmp_dir}/cgi-bin/* ${target_dir}/cgi-bin/${install_prefix} > /dev/null 2>&1

		query="UPDATE SiteApps SET app_id='${pkg_id}' WHERE id='${app_id}';"
		echo "$query" | $mysql

		echo "done"
	done

	rm -rf ${tmp_dir}

	return 0
}

upgrade_subdomains()
{
	query="SELECT d.name, s.name, su.login FROM subdomains s, domains d, sys_users su WHERE s.dom_id=d.id AND s.sys_user_id=su.id AND d.htype='vrt_hst';"

	for row in `echo "${query}" | $mysql | awk '{print $1","$2}'`; do
		dom_name=`echo $row | sed -e 's/,/ /g' | awk '{print $1}'`
		subdom_name=`echo $row | sed -e 's/,/ /g' | awk '{print $2}'`
		owner=`echo $row | sed -e 's/,/ /g' | awk '{print $3}'`

		[ ! -z "${dom_name}" ] && [ ! -z "${subdom_name}" ] && [ ! -z "${owner}" ] || continue

		dir="${HTTPD_VHOSTS_D}/${dom_name}/subdomains/${subdom_name}/conf"
		[ -d ${dir} ] || mkdir ${dir}
		chmod 750 ${dir}
		chown 0:psaserv ${dir}

		dir="${HTTPD_VHOSTS_D}/${dom_name}/subdomains/${subdom_name}/httpsdocs"
		[ -d ${dir} ] || mkdir ${dir}
		chmod 750 ${dir}
		chown $owner:psaserv ${dir}

	done
}

upgrade_vhosts_700()
{
	# common part for domains with physical hosting
	query="SELECT d.id FROM domains d, hosting h WHERE d.id=h.dom_id AND d.htype='vrt_hst';"

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

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

		# retrieve system user login
		query="SELECT s.login FROM sys_users AS s, hosting AS h WHERE h.dom_id='$dom_id' AND h.sys_user_id=s.id;"
		login=`echo "$query" | ${mysql}`

		inten="set proper permissions on virtual host $dom_name dirs"
		"$UTILS_DIR"/vhostmng --install-vhost --vhost-name=${dom_name} --user-name=${login} \
				>> "$product_log" 2>&1 \
				|| report_problem "$inten" "Probably BD record for domain '$dom_name' is broken"
	done

	upgrade_subdomains
}

upgrade_vhosts_700_newkey()
{
	case "$machine" in
		BSD*)
			;;
		*)
			upgrade_mambo
			;;
	esac
}

upgrade_vhosts_710()
{
	upgrade_protected_directories

	vhosts_install_error_doc unauthorized.html
}
fix_subdomain_permissions()
{
	local query="select concat('$HTTPD_VHOSTS_D/',d.name,'/subdomains/',sd.name) from subdomains sd, domains d where d.id=sd.dom_id"

	$mysql -e "$query" | while read subdom_dir; do
		if [ -d "$subdom_dir" ]; then
			chown root:0 "$subdom_dir" && chmod 755 "$subdom_dir";
			if [ -d "$subdom_dir/conf" ]; then
				chown -Rh root:$services_group "$subdom_dir/conf";
				chmod -R 640 "$subdom_dir/conf";
				find "$subdom_dir/conf" -type d -exec chmod 750 {} \;
			fi
		fi
	done
}


hide_webalizer_refferers()
{
	local query="select d.name from domains d, hosting h where d.htype='vrt_hst' and d.id=h.dom_id"

	$mysql -e "$query" | while read domain_name; do
#		$UTILS_DIR/webalizermng --update --domain-name="$domain_name" >>$product_log 2>&1;
		$UTILS_DIR/webstatmng --set-configs --stat-prog=webalizer --domain-name="$domain_name" >>$product_log 2>&1;
	done
}

remove_horde2()
{
	rm -rf "$HTTPD_VHOSTS_D/webmail"
}

upgrade_vhosts_752()
{
	hide_webalizer_refferers
	fix_subdomain_permissions
	remove_horde2
}
upgrade_protected_directories()
{
	local query row
	local pd_id pd_type directory domain_name sys_user_name
	local type
	local pd_user_name password_type password

	echo_try "upgrade protected directories"
	p_echo

	query="SELECT CONCAT(pd.id, ',', IF(pd.non_ssl = 'true', 1, 0) + IF(pd.ssl = 'true', 2, 0), ',', pd.path, ',', d.name, ',', su.login) FROM protected_dirs pd, domains d, hosting h, sys_users su WHERE pd.dom_id=d.id AND d.id=h.dom_id AND h.sys_user_id=su.id AND d.htype='vrt_hst';"

	for row in `echo "${query}" | $mysql`; do # cycle directories

		pd_id=`echo $row | awk -F ',' '{print $1}'`
		pd_type=`echo $row | awk -F ',' '{print $2}'`
		directory=`echo $row | awk -F ',' '{print $3}'`
		domain_name=`echo $row | awk -F ',' '{print $4}'`
		sys_user_name=`echo $row | awk -F ',' '{print $5}'`

		# remove old "AuthUserFile" file(s)
		rm -f "${HTTPD_VHOSTS_D}/${domain_name}/pd/d..`echo ${directory} | sed -e 's/\//../g'`" # version 7.0 file
		rm -f "${HTTPD_VHOSTS_D}/${domain_name}/pd/d..`echo ${directory} | sed -e 's/\//@/g'`"  # version 7.1 file

		p_echo "  protect ${directory} on  ${domain_name}"
		case $pd_type in
			0)
				continue
				;;
			1)
				directory_wprefix="httpdocs/${directory}"
				$PRODUCT_ROOT_D/admin/bin/pdmng --add-protection --vhost-name="${domain_name}" --directory="${directory_wprefix}" --user-name="${sys_user_name}" || warn "protect directory ${domain_name}/${directory_wprefix}"
				;;
			2)
				directory_wprefix_ssl="httpsdocs/${directory}"
				$PRODUCT_ROOT_D/admin/bin/pdmng --add-protection --vhost-name="${domain_name}" --directory="${directory_wprefix_ssl}" --user-name="${sys_user_name}" || warn "protect directory ${domain_name}/${directory_wprefix_ssl}"				
				;;
			3)
				directory_wprefix="httpdocs/${directory}"
				directory_wprefix_ssl="httpsdocs/${directory}"
				$PRODUCT_ROOT_D/admin/bin/pdmng --add-protection --vhost-name="${domain_name}" --directory="${directory_wprefix}" --user-name="${sys_user_name}" || warn "protect directory ${domain_name}/${directory_wprefix}"
				$PRODUCT_ROOT_D/admin/bin/pdmng --add-protection --vhost-name="${domain_name}" --directory="${directory_wprefix_ssl}" --user-name="${sys_user_name}" || warn "protect directory ${domain_name}/${directory_wprefix_ssl}"				
				;;
			*)
				continue
				;;
		esac


		query="SELECT pdu.id FROM pd_users pdu WHERE  pdu.pd_id='${pd_id}';"
		for pdu_id in `echo "${query}" | $mysql`; do # cycle users

			query1="SELECT pdu.login FROM pd_users pdu WHERE  pdu.id='${pdu_id}';"
			pd_user_name=`echo $query1 | $mysql`;
			query1="SELECT a.password FROM pd_users pdu, accounts a WHERE pdu.account_id=a.id AND pdu.id='${pdu_id}';"
			password=`echo $query1 | $mysql`;
			query1="SELECT a.type FROM pd_users pdu, accounts a WHERE pdu.account_id=a.id AND pdu.id='${pdu_id}';"
			password_type=`echo $query1 | $mysql`;

			case $password_type in
				plain)
					PSA_PASSWORD=$password
					export PSA_PASSWORD
					;;
				crypt)
					PSA_CRYPTED_PASSWORD=$password
					export PSA_CRYPTED_PASSWORD
					;;
				*)
					continue
					;;
			esac

			p_echo "    add user ${pd_user_name}"
			case $pd_type in
				0)
					continue
					;;
				1)
					$PRODUCT_ROOT_D/admin/bin/pdmng --add-user --vhost-name="${domain_name}" --directory="${directory_wprefix}" --user-name="${pd_user_name}" || warn "add ${pd_user_name} user of protected directory ${domain_name}/${directory_wprefix}"
					;;
				2)
					$PRODUCT_ROOT_D/admin/bin/pdmng --add-user --vhost-name="${domain_name}" --directory="${directory_wprefix_ssl}" --user-name="${pd_user_name}" || warn "add ${pd_user_name} user of protected directory ${domain_name}/${directory_wprefix_ssl}"
					;;
				3)
					$PRODUCT_ROOT_D/admin/bin/pdmng --add-user --vhost-name="${domain_name}" --directory="${directory_wprefix}" --user-name="${pd_user_name}" || warn "add ${pd_user_name} user of protected directory ${domain_name}/${directory_wprefix}"
					$PRODUCT_ROOT_D/admin/bin/pdmng --add-user --vhost-name="${domain_name}" --directory="${directory_wprefix_ssl}" --user-name="${pd_user_name}" || warn "add ${pd_user_name} user of protected directory ${domain_name}/${directory_wprefix_ssl}"
					;;
				*)
					continue
					;;
			esac

			unset PSA_PASSWORD PSA_CRYPTED_PASSWORD

		done # cycle users

	done # cycle directories

	suc
}

upgrade_subdomains_ssl()
{

	# create empty httpsdocs for all subdomains
	query="SELECT CONCAT(d.name, ',', sd.name, ',', su.login) FROM domains d, subdomains sd, sys_users su WHERE d.id=sd.dom_id AND sd.sys_user_id=su.id AND d.htype='vrt_hst';"

	for row in `echo "${query}" | $mysql`; do # cycle subdomains

		domain_name=`echo $row | awk -F ',' '{print $1}'`
		subdomain_name=`echo $row | awk -F ',' '{print $2}'`
		sys_user=`echo $row | awk -F ',' '{print $3}'`
		
		[ ! -z "${domain_name}" ] && [ ! -z "${subdomain_name}" ] && [ ! -z "${sys_user}" ] || continue
		
		dir="${HTTPD_VHOSTS_D}/${domain_name}/subdomains/${subdomain_name}/conf"
		[ -d ${dir} ] || mkdir ${dir}
		chmod 750 ${dir}
		chown 0:psaserv ${dir}

		skel_dir="${HTTPD_VHOSTS_D}/.skel/0/httpsdocs"
		dir="${HTTPD_VHOSTS_D}/${domain_name}/subdomains/${subdomain_name}/httpsdocs"
		[ -d ${dir} ] || cp -R $skel_dir $dir
		chmod 750 ${dir}
		chown -R $sys_user:psaserv ${dir}
	
	done	
	
}

set_proper_vhosts_perms()
{
	# common part for domains with physical hosting
	query="SELECT d.id FROM domains d, hosting h WHERE d.id=h.dom_id AND d.htype='vrt_hst';"

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

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

		# retrieve system user login
		query="SELECT s.login FROM sys_users AS s, hosting AS h WHERE h.dom_id='$dom_id' AND h.sys_user_id=s.id;"
		login=`echo "$query" | ${mysql}`

		inten="set proper permissions on virtual host $dom_name dirs"
		"$UTILS_DIR"/vhostmng --install-vhost --vhost-name=${dom_name} --user-name=${login} \
				>> "$product_log" 2>&1 \
				|| report_problem "$inten" "Probably BD record for domain '$dom_name' is broken"
	done

}

upgrade_vhosts_754()
{
	upgrade_protected_directories
	upgrade_subdomains_ssl
	set_proper_vhosts_perms	
}

#webalizer

set_webalizer_params()
{
	WEBALIZER_ROOT_D="$PRODUCT_ROOT_D/webalizer"
}

upgrade_webalizer_rpm_600()
{
	# move the webalizer to its own rpm
	if ! test -x "$PRODUCT_ROOT_D/webalizer/bin/webalizer"; then
		conf_setval "$prod_conf_t" WEB_STAT /usr/bin/webalizer
	fi
}
register_webmail()
{
		local name="$1"
		local inten="register webmail '$1'"

		[ -z "$name" ] && die $inten

		$webmail_tool --install --name="$name" || warn $inten
}

reconfig_webmail()
{
	local name="$1"
	local inten="reconfigure webmail"
	local old_wmail_prefix="/etc/psa/webmail"

	[ -z "$name" ] && warn $inten

	# move passwd file into new place
	if [ -f "$old_wmail_prefix/$name/.${name}.shadow" ]; then
		mv -f $old_wmail_prefix/$name/.${name}.shadow $webmail_conf_d/$name/

		# recreate vhost config
		$webmail_tool --disable --name="$name" >> "$product_log" 2>&1
		$webmail_tool --enable  --name="$name" >> "$product_log" 2>&1
	fi
}
set_webmail_params()
{
	webmail_conf_d="/usr/local/etc/psa-webmail"
	webmail_tool="${PRODUCT_ROOT_D}/admin/bin/webmailmng"
}

true postfix_status
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
}
detect_upgrade()
{
    clean_install
    local ver_with_pkg="810"
    local version_file="$PRODUCT_ROOT_D/version"
    local PKGNAME='psa'

    local isBasePackage="yes"
    local SkipDetect=""

    ## Stage 0. 
    if [ ! -z $SkipDetect ]; then
       return 0
    fi

    #version with epoch  
    local portupgrade_version="`pkg_info -q -O ports-mgmt/portupgrade | awk -F '-' '{print $2}' | \
				awk -F ',' '{print $2$1}' | sed -e 's|\([[:digit:]]*\)\.\([[:digit:]]\).*|\1\2|g'`"

    if [ 0222 -gt 0$portupgrade_version ]; then
        echo ""
        echo "Version portupgrade is incorrect. "
        echo "Make sure that version portupgrade is 2.2 or above."
        echo "Exiting..."
        exit 1
    fi

    ## Upgrade detected in portupgrade
    ## if exists installed port it's already pkg -> pkg upgrade.
    if [ ! -z "$UPGRADE_PORT" ]; then
        upgrade_pkg

        ## Hack for resurect version file for base package.
        if `echo $UPGRADE_PORT | grep -q 'psa-8.1.0'`; then
            echo "8.1.0 `uname -s` `uname -r| awk -F '-' '{print $1}'` ${ver_with_pkg}000000.00" > $version_file
        fi

        return 0
    fi

    ## Upgrade not detected in portupgrade
    ### Clean install
    if [ ! -d $PRODUCT_ROOT_D ]; then
        clean_install
        return 0
    fi

    ### Base packages(no need mysql in depends).
    if [ "X$isBasePackage" = "Xyes" ]; then
	if [ ! -f $version_file ]; then
	    clean_install
            return 0
	fi

	install_ver="`cat $version_file | awk '{print $1}'| sed -e 's|\.||g'`"
	if [ 0$install_ver -lt $ver_with_pkg ]; then
	    upgrade_std
	else
	    upgrade_pkg
	fi
	
	return 0
    fi

    set_mysqld_params
    get_mysql_socket
    pleskrc mysql start 1

    query="SELECT db_version from upgrade_history"
    versions="`echo "$query" | $mysql`"

    if [ "X$versions" = "X" ]; then
	clean_install
	return 0
    else
	local doStdUpgrade=0

	for ver in $versions; do
	    if [ 0$ver_with_pkg -gt 0$ver ]; then 
		doStdUpgrade=1
	    fi
	done 

	if [ 0$doStdUpgrade -ne 0 ]; then 
	    upgrade_std
	else
	    clean_install
	fi
    fi

    return 0
}
    
clean_install()
{
    do_upgrade=0
    std_to_pkg=0
}

upgrade_pkg()
{
    do_upgrade=1
    std_to_pkg=0
}

upgrade_std()
{
    do_upgrade=1
    std_to_pkg=1
}

groupadd_f()
{
    grep -q "^$1:" /etc/group || /usr/sbin/groupadd "$1"
}

maintainer_main_pre()
{
	ignore_miss_conf=1
	interactive_allowed=0
	mysql_unconfigured=1

	# remember some variables for standard -> rpm upgrade
	RPM_RC_D="${PRODUCT_RC_D}"
	RPM_MYSQL_VAR_D="${MYSQL_VAR_D}"
	RPM_MYSQL_BIN_D="${MYSQL_BIN_D}"
	RPM_QMAIL_ROOT_D="${QMAIL_ROOT_D}"
	RPM_QMAIL_MAILNAMES_D="${PLESK_MAILNAMES_D}"
	RPM_RBLSMTPD="${RBLSMTPD}"
	RPM_NAMED_RUN_ROOT_D="${NAMED_RUN_ROOT_D}"
	RPM_HTTPD_CONF_D="${HTTPD_CONF_D}"
	RPM_HTTPD_BIN_D="${HTTPD_BIN_D}"
	RPM_APACHE_CERT="${RPM_HTTPD_CONF_D}/httpd.pem"
	RPM_COURIER_IMAP_ROOT_D="${COURIER_IMAP_ROOT_D}"
	RPM_FTPD_CONF="${FTPD_CONF}"
	RPM_FTPD_CONF_INC="${FTPD_CONF_INC}"
	RPM_OPENSSL="${OPENSSL}"
	RPM_WEB_STAT="${WEB_STAT}"

	set_local_params
	set_ftpd_params

	get_config_parameters

	if [ "X$machine" = "XBSD" ]; then 
	    set_super_server_params
	    register_bsd_compat
	    register_service inetd
	    rc_service "local" "startup" "/usr/local/etc/rc.d"

	    if [ "X$do_upgrade" = "X1" -a "X$std_to_pkg" = "X1" ]; then
 		$PRODUCT_ROOT_D/rc.d/psa stop >>$product_log 2>&1
		$PRODUCT_ROOT_D/rc.d/mailman stop >>$product_log 2>&1

		[ -f $PRODUCT_ROOT_D/rc.d/functions ] && \
		    cp -f $PRODUCT_ROOT_D/rc.d/functions /usr/local/etc/rc.d/
	    fi 
		pleskrc superserver start
	fi


	# debian will try upgrade unconfigured package
	# it is not an upgrade, actually
	if [ "X$do_upgrade" = "X1" ]; then
		if [ ! -f ${PRODUCT_ROOT_D}/version ]; then
			do_upgrade=0
		fi
	fi

	preinstall_checks

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

		set_mysqld_params

		# Check mysqld status for non-debian based distros
		if [ "$linux_distr" != "debian" -a "$linux_distr" != "ubuntu" ]; then
			pleskrc mysql start 1 || die "Unable to start mysql service"
		fi

		if [ -f ${PRODUCT_ROOT_D}/version ]; then
			cp ${PRODUCT_ROOT_D}/version ${PRODUCT_ROOT_D}/version.upg
		fi
	fi

	necessary_system_accounts
	set_apache_accounts

	if [ "X$do_upgrade" = "X1" ]; then
		if [ -f ${PRODUCT_ROOT_D}/version ]; then
			get_prev_version $PRODUCT_ROOT_D
		fi
		set_mysql_auth
		prepare_upgrader
	fi

	groupadd_f psacln
	add_login_shell "$PRODUCT_ROOT_D/bin/chrootsh"
}

register_bsd_compat()
{
    local compat4_script compat5_script

    register_service compat4x
    register_service compat5x

    compat4_script="`find $PRODUCT_RC_D -type f -name "*compat4x*" | head -1`"
    compat5_script="`find $PRODUCT_RC_D -type f -name "*compat5x*" | head -1`"

    if [ -f $PRODUCT_RC_D/$compat4_script -a "X$compat4_script" != "X" ]; then
       $PRODUCT_RC_D/$compat4_script start
    fi
    if [ -f $PRODUCT_RC_D/$compat5_script -a "X$compat5_script" != "X" ]; then
       $PRODUCT_RC_D/$compat5_script start
    fi
}

psa_install_pre()
{
	selinux_init
	maintainer_main_pre

	# cannot use rc.d script because it can be removed
	pidfile="$PRODUCT_ROOT_D/admin/logs/httpsd.pid"
	if test -f "$pidfile"; then
		httpsd_pid=`cat "$pidfile"`
		if test "$httpsd_pid" -gt 0 \
			&& ps -o command -p "$httpsd_pid" | grep -q httpsd
		then
			kill -TERM "$httpsd_pid"
		fi
	fi

	selinux_close
}

psa_upgrade_new_pre()
{
	selinux_init
	maintainer_main_pre
	if [ $? -ne 0 ]; then
		return 1
	fi

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

	define_start_script

	stop_before_upgrade

	selinux_close
}


# mode: shell-script

PRODUCT_ROOT_D=/usr/local/psa
export PRODUCT_ROOT_D

unlink_passwd_file()
{
	local psa_dir="/etc/$PRODNAME"
	local psa_shadow="/etc/$PRODNAME/.${PRODNAME}.shadow"
	local admin_passwd="`cat $psa_shadow`"
	local nlink

	if [ "X$machine" = "XBSD" ]; then
		nlink="`stat -f '%l' $psa_shadow`"
	else
		nlink="`stat -c '%h' $psa_shadow`"
	fi

	if [ 0$nlink -gt 1 ]; then
		echo "$admin_passwd" > ${psa_shadow}_fixed || return
		chown psaadm:psaadm ${psa_shadow}_fixed
		chmod 0600 ${psa_shadow}_fixed

		mv -f $psa_shadow ${psa_shadow}_hacked
		echo "" > ${psa_shadow}_hacked

		mv -f ${psa_shadow}_fixed $psa_shadow
	fi
}

#%if %(vmatch %{osrels} 'suse*|sles*')
#modname=rewrite
#%{suse_apache_add_module}
#%endif
clean_python_modules()
{
	echo_try "clean up compiled python modules"
	cd /usr/local/psa/admin/lib/python && rm -f ./*.pyc
}

set_relay_opts()
{
	local controls="$PRODUCT_ROOT_D/var/root.controls.lock"
	if [ ! -s "$controls" ]; then
		echo "/server/mail.php3:relay_open" > $controls
	fi
}

upgrade_sb_icons()
{
	if [ -d /usr/local/sitebuilder ]; then
		SB_ROOT_D=/usr/local/sitebuilder
	fi

	if [ -d /opt/sitebuilder ]; then
		SB_ROOT_D=/opt/sitebuilder
	fi

	if [ -f ${SB_ROOT_D}/.version ]; then
		sb_version=`cat $SB_ROOT_D/.version | awk '{ print $1 }'`

		case $sb_version in
			4.2.*|4.5.0)
				${tar} xzf "${PRODUCT_ROOT_D}/tmp/sb_unix_icons.tar.gz" -C "$SB_ROOT_D" 2>/dev/null || true
				chmod 755 ${SB_ROOT_D}/htdocs/skins -R || true
			;;
		esac
	fi
}

package_main()
{
	set_super_server_params
	std_to_rpm_upgrade=0
	backup_required=0
	mysql_unconfigured=1
	fp_upgrade_required=0
	interactive_allowed=0

	# enable service failures ignoring
	service_failures_ignoring=1

	fix_etc_hosts

	# this variable values are required for upgrade step from 5.0 to 6.0
	DEFAULT_DUMP_D=${DUMP_D}
	
	set_default_locale
	set_services_info

	if [ "X$machine" = "XBSD" ]; then
 		hash -r >> $product_log 2>&1 || \
		rehash >> $product_log 2>&1

		register_service psa
	      
		[ -e "/usr/local/lib/liblog4cpp_plesk.so.4" ] || \
			ln -s $PRODUCT_ROOT_D/lib/liblog4cpp_plesk.so.4 /usr/local/lib/liblog4cpp_plesk.so.4

		[ -d $PRODUCT_ROOT_D/var/cgitory ] || mkdir -p $PRODUCT_ROOT_D/var/cgitory >> $product_log 2>&1 

		#Apxs can't find the perl
		if [ ! -f /usr/bin/perl ]; then  
			if [ -f /usr/local/bin/perl ]; then 
				ln -s /usr/local/bin/perl /usr/bin/perl
			fi
		fi

		set_apache_params
		add_apache_module perl
           
	   if [ "X$do_upgrade" = "X1" ]; then
	      #Stay the old vhosts directory after upgrade bug #101310.
	      vhosts_d_old="`cat ${product_etc}/${product}.conf | grep HTTPD_VHOSTS_D | awk '{print $2}'`"
	      vhosts_d_new="`cat ${product_etc}/${product}.conf | grep HTTPD_VHOSTS_D | awk '{print $2}'`"

	      mv ${product_etc}/${product}.conf ${product_etc}/${product}.conf.in

	      sed -e 's|'"$vhosts_d_new"'|'"$vhosts_d_old"'|g' \
	             < ${product_etc}/${product}.conf.in > ${product_etc}/${product}.conf || die
	   fi
	fi

	set_local_params

	selinux_init
	selinux_check

	if [ "X$do_upgrade" = "X0" ]; then

		# check for std-to-rpm upgrade situation
		if [ -f ${PRODUCT_ROOT_D}/version.upg ]; then
			mv -f ${PRODUCT_ROOT_D}/version.upg ${PRODUCT_ROOT_D}/version

			# this may be happened durind RPM over Standard installing
			check_product_root

			if [ "X$do_upgrade" = "X1" ]; then
				std_to_rpm_upgrade=1
			fi
		fi
	fi

	# this blocks moving of vhosts directory
	# because RPM has its own way of vhosts processing via extract_vhosts()
	DEFAULT_HTTPD_VHOSTS_D=${HTTPD_VHOSTS_D}

	if [ "X$machine" != "XBSD" ]; then
	    APACHE_ROOT="/etc/httpd";
		mysql_dbdir=`get_my_cnf_param datadir`
	fi

	get_config_parameters

	if [ "X$do_upgrade" = "X1" ]; then
		get_old_domain
		if [ -f ${PRODUCT_ROOT_D}/version.upg ]; then
			mv -f ${PRODUCT_ROOT_D}/version.upg ${PRODUCT_ROOT_D}/version
		fi
		get_prev_version $PRODUCT_ROOT_D
	fi

	install_rbash

	mysql_install_init
	insert_fullhostname

	install_cron_somely
	install_admin
	install_cron_backup
	import_default_certificate
	extract_vhosts
	install_vhosts
	install_apache
	install_quota		# depend from install_vhosts
	install_named
	install_chroot_base
	install_phpmyadmin
	
	if [ "X$machine" != "XBSD" ]; then
	    install_suexec
	fi

	if [ "$linux_distr" = "suse" ]; then
		add_apache_module rewrite
	fi

	if [ "X${linux_distr}" = "Xdebian" ]; then
		add_apache_module include
		add_apache_module rewrite
		add_apache_module userdir
		set_awstats_perms_debian
		fix_networking_debian
	fi

	if [ "X${minimal_changes}" = "X1" ]; then
		/sbin/chkconfig --add ${PRODNAME}
	fi

	# We need to upadate alterntavis one more time during upgrade, see Bug 75469
	if [ "X$do_upgrade" = "X1" ]; then
		db_mysql_check_upgrade
		cumulative_upgrade
		update_history
		named_writeconf
		clean_python_modules
	fi

	packagemng_set_dirty_flag
	set_relay_opts
	rebuild_ip_pool		# depend from import_default_certificate
	update_components_table	# clear Components table and update information

	if [ "XRELEASE" = "XCTP" ]; then
		setup_support_url "http://swdn.swsoft.com/en/feedback/ctp"
	fi
	

	# this routine requires 5.0.0 database version, which always come after upgrader
	chown_webstat

	create_version_file

	if [ "X$do_upgrade" != "X1" ]; then
# require version file
		db_create_default_templates
		db_update_notifications
# create guid for admin
		db_generate_guids_82
	fi	
	vz_tune
	selinux_relabel_dir "$PRODUCT_ROOT_D"
	selinux_relabel_dir /usr/local/libexec/plesk-9.0

	# Re-dump all mail-related entities from Plesk DB to a mailserver DBs and
	# on-disk structures
	mail_restore_all
	upgrade_sb_icons

	# start product and services
	start_product_now_final

	### websrvmng
	pleskrc apache start
	"$UTILS_DIR"/websrvmng -v -a  >> $product_log 2>&1
	fake_latest_apache_restart

	if [ "X$machine" = "XDarwin" ]; then
		set_chrootsh_perms
	fi

	if [ "X$do_upgrade" = "X1" ]; then
		if [ -e "$CATALINA_HOME/conf/server.xml" ]; then
			tomcat_reconfigure_server
        fi
	fi

	service_restart_warning
	selinux_close

	if [ "X$machine" = "XBSD" ]; then
	    chown_builder2root

	    if [ "X$std_to_pkg" = "X1" ]; then
		set_pgsql_params
		postgres_fix_users

		local old_vhosts_dir
		old_vhosts_dir=$PRODUCT_ROOT_D/home

		find $old_vhosts_dir/ -group apache -exec chown :$apache_group {} \;
		find $old_vhosts_dir/ -user apache -exec chown $apache_user: {} \;
	    fi
	fi

	unlink_passwd_file

	set_webmail_params

	register_webmail horde
	reconfig_webmail horde

	register_webmail atmail
	reconfig_webmail atmail

	print_congratulations
}

maintainer_main_post()
{

	if [ "X0" != "X1" ]; then
		package_main &&
		register_service psa defaults defaults

		if [ "X$machine" = "XBSD" -a "X$std_to_pkg" = "X1" ]; then
		   garbage_collector_bsd
		fi
	    if [ "${linux_distr}_${conceived_os_version}" = "fedora_7" ]; then
### on f7 we must register mysqld manually
			register_service mysqld 345 016
        fi
	else

		if [ -d /usr/share/doc/psa ]; then
			RELNOTES_DIR=/usr/share/doc/psa
		elif [ -d /usr/share/doc/psa-9.5.4 ]; then
			RELNOTES_DIR=/usr/share/doc/psa-9.5.4
		fi
		RELNOTES_FILE="release_notes-fr6.1.txt"

		echo "To complete the post-install configuration of Plesk, run the following script"
		echo "${PRODUCT_ROOT_D}/bin/install_post.sh"
		echo "We strongly recommend that you read the release notes"
		if [ "X${RELNOTES_DIR}" = "X" ]; then
			echo ${RELNOTES_FILE}
		else
			echo ${RELNOTES_DIR}/${RELNOTES_FILE}
		fi
	fi
}

upgrade_conf_754()
{
	logrotate_conf=/etc/psa/logrotate.conf
	
	[ -f "${logrotate_conf}" ] && sed -e 's|${PRODUCT_ROOT_D}|/usr/local/psa|g' < ${logrotate_conf} > /tmp/u.tmp \
	    && mv /tmp/u.tmp ${logrotate_conf}

	FILES_BACKUP="ssl.crl ssl.crt ssl.csr ssl.key ssl.prm openssl.cnf"
	
	for i in ${FILES_BACKUP}; do 
	    cp -Rf ${PRODUCT_ROOT_D}/admin/conf/${i}.sav ${PRODUCT_ROOT_D}/admin/conf/${i}  2>/dev/null
	done

	conf_setval ${prod_conf_t} PRODUCT_ROOT_D "/usr/local/psa"
}

#Remove it in psa >= 8.1.0 
garbage_collector_bsd()
{
    local old_root_d rm_list
    old_root_d="/usr/local/psa"
    local script_list="`cd $old_root_d && find ./rc.d -type f -or -type l| grep -v postgresql`"
    local pmm_list="Cgp.* ConfixxX.* EnsimX.* Plesk70.* PleskX.* RaQ*.* Slash.* cPanel9.*"
    local pbm_list="admin/plib/backup/pleskbackup.php"
    local api_list="test_*.py tests.py"
    local asp_list="`cd $old_root_d && find ./lib -name '*ASP*'`"

    rm_list="$script_list apache etc/psa_db*.sql etc/dict.*" 
    admin_files_list="agent_extract agent_runner backupmng bu_flags_cleaner \
                      buildmodule.sh client_mailer deinstall* deployer domain_bu launchpad \
                      openssl spammng ssh-lite unzip vzcp_auth webalizermng"

    for list in $rm_list; do
	rm -rf $old_root_d/$list >> $product_log 2>&1
    done 
    
    if [ -d $PRODUCT_ROOT_D/tmp/packages ]; then
	rm -rf $PRODUCT_ROOT_D/tmp/packages >> $product_log 2>&1
    fi

    remove_bsd_accounts apache named 

    if [ "5" = "5" ]; then
	remove_bsd_accounts tomcat4
    fi

    remove_bsd_files "$old_root_d/admin/bin $old_root_d/admin/sbin" "$admin_files_list"
    remove_bsd_files "$old_root_d/admin/lib/python" "libxml2mod.so"
    remove_bsd_files "$old_root_d/mailman" "mailman"
    remove_bsd_files "$old_root_d/PMM" "$pmm_list"
    remove_bsd_files "$old_root_d" "$pbm_list $asp_list"
    remove_bsd_files "$old_root_d/admin/lib/python" "$api_list"
    remove_bsd_files "$PRODUCT_RC_D" "psa-vpn*"

    case ${os_version} in
		4*)
		    remove_bsd_files "/usr/lib" "libstdc++_plesk*"
		;;
		*)
		    remove_bsd_files "$old_root_d" "named"
		    remove_bsd_files "/etc" "named.conf"
		;;
    esac

	empty_dirs="PMM/archives"

	# Remove only empty directories
	for f in $empty_dirs; do
		rmdir "$PRODUCT_ROOT_D/$f" > /dev/null 2>&1
	done
	# Remove old frontpage link
	rm -fv /usr/local/frontpage 2>/dev/null
}

remove_bsd_files()
{
    local search_paths="$1"
    local search_files="$2"

    if [ "X$search_paths" = "X" -o "X$search_files" = "X" -o "X$std_to_pkg" != "X1" ]; then
	return 0
    fi

    for dir in $search_paths; do
	for file in $search_files; do
	    rm -rf $dir/$file >> $product_log 2>&1
	done
    done

    return 0
}

remove_bsd_accounts()
{
    local home_dir
    local rm_flags

    p_echo "Delete useless accounts"
    p_echo "This operation takes some time, please, wait..."
    p_echo
   
    if [ 0$# -gt 0 ]; then
        for i in $*; do 
            echo -n "Deleting user account $i.."
            home_dir=`grep "^$i" /etc/master.passwd 2>/dev/null | awk -F ':' '{print $9}'`
            if [ "X$home_dir" != "X" -a "X$home_dir" != "X/" ]; then
               rm_flags='-r'
            fi 

            /usr/sbin/pw userdel $rm_flags -n $i >> $product_log 2>&1 &
            pid="$!"

            while(true); do
               ps $pid | awk '{print $1}' | grep $pid >/dev/null || break
               echo -n "."
               sleep 1
            done

            echo " done"
        done
    fi
}

psa_upgrade_new_post()
{
	maintainer_main_post
}

psa_install_post()
{
	maintainer_main_post
}

type="$2"

if [ "X${PLESK_INSTALLER_DEBUG}" = "X1" ]; then
    set -x
fi

package_script_begin
detect_upgrade

case "$type" in
     PRE-INSTALL)
        if [ "$do_upgrade" = "0" ]; then
                 package_script_call_main_function psa_install_pre psa 9.5.4 fr6.1.build95101209.08
        else
	         package_script_call_main_function psa_upgrade_new_pre psa 9.5.4 fr6.1.build95101209.08
        fi
     ;;
     POST-INSTALL)
        if [ "$do_upgrade" = "0" ]; then
	         package_script_call_main_function psa_install_post psa 9.5.4 fr6.1.build95101209.08
        else
                 package_script_call_main_function psa_upgrade_new_post psa 9.5.4 fr6.1.build95101209.08
        fi
     ;;
     *)
          exit 1
     ;;
esac

exit 0


