#!/bin/sh
#
# Copyright (c) 1999-2005 SWsoft Inc.
# 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
}
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_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"
}

remove_tmp_state()
{
	if [ -d "/tmp/.state" ]; then
		rm -Rf "/tmp/.state" >> $product_log 2>&1
	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
}

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

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

	BSD_*)
		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 disabled."
		fi
	;;

	linux_suse_*)
		if sed -r "s/^(APACHE_MODULES=.*)${module_name}(.*)$/\\1\\2/" \
						/etc/sysconfig/apache2 > /etc/sysconfig/apache2.new ; then
			mv -f /etc/sysconfig/apache2.new /etc/sysconfig/apache2
		fi
	;;

	linux_debian_*)
		if [ -x /usr/sbin/a2dismod ]; then
			/usr/sbin/a2dismod $module_name
		else
			warn "a2dismod utilily not found! Module $module_name was NOT disabled."
		fi
		rm -f $HTTPD_CONF_D/mods-enabled/$module_name.load
	;;

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

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

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

set_tomcat_params()
{
    # # set_common_params
    tomcat_distrib="$PRODUCT_ROOT_D/tmp/jakarta-tomcat.tar"
    prod_conf_t="/etc/psa/psa.conf"
    tomcat_version="5"
    CATALINA_HOME="/usr/local/tomcat5.5"
    tomcat_user="www"
    tomcat_group="www"

    #basename directory. May be different. 
    dist_name="tomcat5"
 
    tomcat_conf="$CATALINA_HOME/conf/$dist_name.conf"
    ### This is for linux - on standard builds we don't have 
    ###	tomcat uncompressed in this stage
    if [ "X$machine" = "Xlinux" ]; then
       [ -f $tomcat_conf ] || tomcat_conf="/etc/sysconfig/j2ee"
    fi
}

set_tomcat_perms()
{

	inten="set up Tomcat permissions"
	echo_try $inten

	chown -RL 0:$tomcat_group "$CATALINA_HOME" > /dev/null 2>&1 || chown -R 0:$tomcat_group "$CATALINA_HOME"
	chown -RL $tomcat_user:$tomcat_group "$CATALINA_HOME/logs" > /dev/null 2>&1 || chown -R $tomcat_user:$tomcat_group "$CATALINA_HOME/logs"
	chown -RL $tomcat_user:$tomcat_group "$CATALINA_HOME/work" > /dev/null 2>&1 || chown -R $tomcat_user:$tomcat_group "$CATALINA_HOME/work"
	chmod 775 "$CATALINA_HOME/logs" || die "chmod $dist_name directory logs"
	chmod 775 "$CATALINA_HOME/work" || die "chmod $dist_name directory work"
	chmod 777 "$CATALINA_HOME/temp" || die "chmod $dist_name directory temp"
	chmod 775 "$CATALINA_HOME/conf" || die "chmod $dist_name directory conf"
	chmod 664 "$CATALINA_HOME/conf/jk2.properties" || die "chmod $dist_name file jk2.properties"
	chmod 664 "$CATALINA_HOME/conf/tomcat-users.xml" || die "chmod $dist_name file tomcat-users.xml"

	suc

	return 0
}

set_tomcat_accounts()
{
	# for tomcat
	p_echo " Checking for the system groups and users necessary for Tomcat..."

	group_op "$tomcat_group" "search" false
	user_op "$tomcat_user" "search" "$tomcat_group" "Tomcat" "$CATALINA_HOME" "$bash_shell" false
}

tomcat_uncompress()
{

        cd $PRODUCT_ROOT_D/tmp || die

        $tar xf $tomcat_distrib || die
        rm -f $tomcat_distrib >> $product_log 2>&1

        for dir in jakarta-tomcat-*; do
           if [ -d $dir ]; then
              if [ "X${do_upgrade}" != "X1" ]; then
                  rm -rf "$CATALINA_HOME"
                  mv -f $dir "$CATALINA_HOME"
              else
                  for i in bin common server shared webapps; do
                     cp -rf "$dir/$i" "$CATALINA_HOME"
                  done

                  rm -rf $dir
              fi
           fi
        done

        return 0
}

set_java_home()
{
	[ -f $tomcat_conf ] || return

	echo_try "find JAVA_HOME variable in the $tomcat_conf"

	tomcat_JAVA_HOME=`sed -n -e "/^JAVA_HOME=\([\"']\)\(.*\)\1$/s//\2/p" $tomcat_conf | sed -n -e '$p'`

	java_home_dirs_list="/usr/java/j2sdk* /usr/java/jdk* ${PRODUCT_ROOT_D}/j2sdk* /usr/lib/j2sdk* \
                             /usr/lib*/jvm/java /Library/Java/Home /usr/local/diablo-jdk1.5.0"

	if [ -z $tomcat_JAVA_HOME ]; then

		p_echo
		p_echo " JAVA_HOME variable is not in the ${tomcat_conf}"

		echo_try "find Java home directory in ${java_home_dirs_list}"
		for java_home in $java_home_dirs_list; do
			if [ -d $java_home ] && [ -f "${java_home}/bin/java" -a -f "${java_home}/bin/javac" ]; then
				JAVA_HOME=$java_home
				break
			fi
		done
		[ ! -z $JAVA_HOME ] || die

		p_echo
		echo_try "add JAVA_HOME=\"${JAVA_HOME}\" in the ${tomcat_conf}"
		echo >> $tomcat_conf || die
		echo "JAVA_HOME=\"${JAVA_HOME}\"" >> $tomcat_conf && suc || die

	elif [ ! -f "${tomcat_JAVA_HOME}/bin/java" -o ! -f "${tomcat_JAVA_HOME}/bin/javac" ]; then

		p_echo
		p_echo " Incorrect JAVA_HOME variable value (${tomcat_JAVA_HOME}) in the ${tomcat_conf}"

		echo_try "find Java home directory in ${java_home_dirs_list}"
		for java_home in $java_home_dirs_list; do
			if [ -d $java_home ] && [ -f "${java_home}/bin/java" -a -f "${java_home}/bin/javac" ]; then
				JAVA_HOME=$java_home
				break
			fi
		done
		[ ! -z $JAVA_HOME ] || die

		p_echo
		echo_try "add JAVA_HOME=\"${JAVA_HOME}\" in the ${tomcat_conf}"
		esc_JAVA_HOME=`echo "${JAVA_HOME}" | sed -n -e 's/\//\\\\\//gp'`
		tomcat_conf_old="${tomcat_conf}-old"
		cp -f $tomcat_conf $tomcat_conf_old || die
		sed -e "s/^JAVA_HOME=\([\"']\).*\1$/JAVA_HOME=\"${esc_JAVA_HOME}\"/" $tomcat_conf_old > $tomcat_conf && suc \
		|| (mv -f $tomcat_conf_old $tomcat_conf && die)
		rm -f $tomcat_conf_old
	else
		p_echo
		p_echo " JAVA_HOME variable is already in the $tomcat_conf and has correct value (${tomcat_JAVA_HOME})"
	fi
}

set_tomcat_user()
{
	[ -f $tomcat_conf ] || return

	echo_try "replace TOMCAT_USER variable in the $tomcat_conf"

	sed -e "s|^TOMCAT_USER=.*|TOMCAT_USER=\"$tomcat_user\"|g" < $tomcat_conf > $tomcat_conf.tmp	\
	&& mv -f $tomcat_conf.tmp $tomcat_conf \
	&& chmod 644 $tomcat_conf && suc

}

tomcat_create_server_link()
{
	if [ -e /usr/share/$dist_name/server ]; then
		if [ ! -e $CATALINA_HOME/server ]; then
			ln -s /usr/share/$dist_name/server $CATALINA_HOME/server
		fi
	fi
	for i in psa-users psa-wars psa-webapps; do
		if [ ! -e /usr/share/$dist_name/$i ]; then
			if [ -e $CATALINA_HOME/$i ]; then
				ln -sf $CATALINA_HOME/$i  /usr/share/$dist_name/$i
			fi
		fi
	done
}

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

	p_echo
	p_echo "===> Installing Tomcat"

	if [ -f $tomcat_distrib ]; then
	    if [ ! -d $PRODUCT_ROOT_D/tomcat4 ]; then
		inten="uncompress Tomcat into $CATALINA_HOME"
		echo_try "$inten"
		tomcat_uncompress && suc || die $inten
	    fi
	fi

	if [ ! -f "$CATALINA_HOME/conf/$dist_name.conf" ]; then
		mkdir -p "$CATALINA_HOME/conf"
		mv -f "$PRODUCT_ETC_D/$dist_name.conf" "$CATALINA_HOME/conf/$dist_name.conf" || die "copy $dist_name.conf file"
	fi

	if [ ! -f "$CATALINA_HOME/conf/server.xml" ]; then
		# create new server.xml
		echo "<Server>" > "$CATALINA_HOME/conf/server.xml"
		echo "</Server>" >> "$CATALINA_HOME/conf/server.xml"
	else
		tomcat_reconfigure_server
	fi
}

install_tomcat()
{
    set_tomcat_params 

    conf_setval "${prod_conf_t}" CATALINA_HOME "${CATALINA_HOME}"
    set_tomcat_accounts

    install_tomcat_freebsd

    set_java_home
    set_tomcat_user

    case "$machine$os_version" in
       BSD5*|BSD6*)
       ;;
       *)
          p_echo " Making chown and chmod under JDK stuff"
          set_tomcat_perms
       ;;
    esac
}

install_tomcat_freebsd()
{
	case "$os_version" in
		4*) 
			install_tomcat_compiled
			;;
		*)
			rc_service "tomcat55" "enable" "YES"
			tomcat_script="`ls $PRODUCT_RC_D/tomcat5*`"
			if [ ! -f $PRODUCT_RC_D/tomcat5 -a "X$tomcat_script" != "X" ]; then
				mv $tomcat_script $PRODUCT_RC_D/tomcat5 
			fi
			if [ ! -e "$CATALINA_HOME/conf/server.xml" ]; then
				if [ -e "$CATALINA_HOME/conf/server.xml.sample" ]; then
					cp -p "$CATALINA_HOME/conf/server.xml.sample" "$CATALINA_HOME/conf/server.xml"
				else
					# create new server.xml
					echo "<Server>" > "$CATALINA_HOME/conf/server.xml"
					echo "</Server>" >> "$CATALINA_HOME/conf/server.xml"
				fi
			fi
			tomcat_reconfigure_server
			;;
	esac 
}

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

	suc
}

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

}

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

}

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

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
}

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()
{
	local type_output="`type \"$1\" 2>/dev/null | head -n 1`"
	case "$type_output" in
		*function)
			"$@"
			;;
		*)
			return 0
			;;
	esac
}

sh_get_args()
{
	echo 'while true; do case "$1" in '"$1"'*) break;; esac; shift; done'
}

sequence()
{
	if type seq; then
		seq $*
	elif type jot; then
		jot $*
	else
		die "Unable to find seq or jot command"
	fi
}

comment_service_xinetd()
{
	#comment service records
	local dir file service grep_res
	service=$1

	inten="comment out record for service $service"
	echo_try "$inten"
	for dir in $xinetd_dir; do
	    for file in $dir/*; do
			grep "$service" $file || continue
			awk "/^[[:space:]]*service[[:space:]]+$service($|[[:space:]]+)/,/.*}.*/ \
			   { print \"#\"\$0; next; }
			   {print}
			" <$file >$file.tmp  &&
			mv -f $file.tmp $file || die "$inten" >> $product_log 2>&1
		done
	done
	suc
}

comment_service_inetd()
{
	local grep_res
	service=$1

	inten="comment out record for service $service"
	echo_try "$inten"

	grep_res=`grep "^$service[[:space:]]" $inetd_conf`

	case "$?" in
		0)
		    sed -e "s|^$service|##commented_by_psa $service|g" < "$inetd_conf" > "$inetd_conf.${product}_tmp" \
			&& mv -f "$inetd_conf.${product}_tmp" "$inetd_conf" \
			&& suc || die >> $product_log 2>&1
		;;
		*)
		    p_echo " no record for service $service found in the $inetd_conf"
		;;
	esac
}

comment_service()
{
	local service
	service=$1
	
	case "$super_server" in
		'xinetd')
		    comment_service_xinetd "$service"
		;;
		'inetd')
		    comment_service_inetd "$service"
		;;
		*)
		    die "Super server type is undefined"
		;;
	esac
}


remove_xinetd()
{
	local service file
	service=$1;
	
	rm -f $xinetd_dir/${service}_${product}
	
	#uncomment old records
	inten="comment out ${product} record for service $service"

	for file in $xinetd_dir/*; do
		awk "/^[[:space:]]*#[[:space:]]*service[[:space:]]+$service($|[[:space:]]+)/,/.*}.*/ \
			{ print substr(\$0,2); next; }
			{print}
			" <$file >$file.tmp &&
		mv -f $file.tmp $file >> $product_log 2>&1
	done;

}

remove_inetd()
{
	local service
	service=$1;

	case "$service" in

		ftp)
			inten="restore ftp service record in the $inetd_conf"

			sed -e "s|^ftp.*/${product}/ftpd/sbin/proftpd.*||g" \
				-e "s|ftp.*/${prev_product}/ftpd/sbin/proftpd.*||g" \
				< $inetd_conf > $inetd_conf.${product}_tmp \
			&& mv -f $inetd_conf.${product}_tmp $inetd_conf >> $product_log 2>&1
		    ;;

		smtp)
			inten="restore smtp service record in the $inetd_conf"

			sed -e "s|^smtp.*$QMAIL_ROOT_D/qmail/bin/tcp-env.*tcp-env.*/qmail/bin/relaylock.*||g" \
				-e "s|^smtp.*${product}/qmail/bin/tcp-env.*tcp-env.*/qmail/bin/relaylock.*||g" \
				-e "s|smtp.*${prev_product}/qmail/bin/tcp-env.*tcp-env.*/qmail/bin/relaylock.*||g" \
				< $inetd_conf > $inetd_conf.${product}_tmp \
			&& mv -f $inetd_conf.${product}_tmp $inetd_conf >> $product_log 2>&1
		    ;;

		smtps)
			inten="restore smtp service record in the $inetd_conf"

			sed -e "s|^smtps.*$QMAIL_ROOT_D/qmail/bin/tcp-env.*tcp-env.*/qmail/bin/relaylock.*||g" \
				-e "s|^smtps.*${product}/qmail/bin/tcp-env.*tcp-env.*/qmail/bin/relaylock.*||g" \
				-e "s|smtps.*${prev_product}/qmail/bin/tcp-env.*tcp-env.*/qmail/bin/relaylock.*||g" \
				< $inetd_conf > $inetd_conf.${product}_tmp \
			&& mv -f $inetd_conf.${product}_tmp $inetd_conf >> $product_log 2>&1
		    ;;

		pop3)
			inten="restore pop3 service record in the $inetd_conf"

			sed -e "s|^pop[-]*3.*/qmail/bin/tcp-env.*tcp-env.*/qmail/bin/pop3$||g" \
				-e "s|^pop[-]*3.*/qmail/bin/tcp-env.*tcp-env.*/qmail/bin/pop3$||g" \
				< $inetd_conf > $inetd_conf.${product}_tmp \
			&& mv -f $inetd_conf.${product}_tmp $inetd_conf >> $product_log 2>&1
			
		    ;;
		poppassd)
			# poppassd stream tcp nowait root /usr/sbin/tcpd /${PRODUCT_ROOT_D}/admin/bin/poppassd
			inten="restore poppassd service record in the $inetd_conf"

			sed -e "s|^poppassd.*$PRODUCT_ROOT_D/admin/bin/poppassd.*||g" \
				< $inetd_conf > $inetd_conf.${product}_tmp \
			&& mv -f $inetd_conf.${product}_tmp $inetd_conf >> $product_log 2>&1
			;;
		
	esac

	# uncomment old records
	sed -e "s|^##commented_by_psa $service|$service|g" < $inetd_conf > $inetd_conf.${product}_tmp \
	&& mv -f $inetd_conf.${product}_tmp $inetd_conf >> $product_log 2>&1


}

remove_super_server()
{
	local service
	service=$1;

	case "$super_server" in

		xinetd)
			remove_xinetd "$service"
			;;
		inetd)
			remove_inetd "$service"
			;;
	esac
}

setup_xinetd()
{
	local service file rbl_on rbl_server
	service=$1;
	rbl_on=$2;
	rbl_server=$3;
	
	#comment old records
	comment_service "$service"
	
	#setup
	service=$1;
	inten="set up record for service $service"
	echo_try "$inten"

	case "$service" in

		ftp)
			echo "
service ftp
{
	socket_type		= stream
	protocol		= tcp
	wait			= no
	disable			= no
	user			= root
	instances		= UNLIMITED
	server			= $PRODUCT_ROOT_D/ftpd/sbin/proftpd
	server_args		= -c $PRODUCT_ROOT_D/ftpd/etc/proftpd.conf
}" > "$xinetd_dir/ftp_${product}" || die "$inten"
			;;

		smtp)

			case "$rbl_on" in

				on)				
					echo "
service smtp
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = root
	instances       = UNLIMITED
	server          = $QMAIL_ROOT_D/bin/tcp-env
	server_args     = -Rt0 $RBLSMTPD $rbl_server $QMAIL_ROOT_D/bin/relaylock $QMAIL_ROOT_D/bin/qmail-smtpd $QMAIL_ROOT_D/bin/smtp_auth $TRUE_BIN $QMAIL_ROOT_D/bin/cmd5checkpw $TRUE_BIN
}" > "$xinetd_dir/smtp_${product}" || die "$inten"
					;;

				*)
					echo "
service smtp
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = root
	instances       = UNLIMITED
	server          = $QMAIL_ROOT_D/bin/tcp-env
	server_args     = -Rt0 $QMAIL_ROOT_D/bin/relaylock $QMAIL_ROOT_D/bin/qmail-smtpd $QMAIL_ROOT_D/bin/smtp_auth $TRUE_BIN $QMAIL_ROOT_D/bin/cmd5checkpw $TRUE_BIN
}" > "$xinetd_dir/smtp_${product}" || die "$inten"
					;;
			esac	
			;;

		smtps)
			case "$rbl_on" in
				on)				
					echo "
service smtps
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = root
	instances       = UNLIMITED
	server          = $QMAIL_ROOT_D/bin/tcp-env
	server_args     = -Rt0 $RBLSMTPD $rbl_server $QMAIL_ROOT_D/bin/relaylock $QMAIL_ROOT_D/bin/qmail-smtpd $QMAIL_ROOT_D/bin/smtp_auth $TRUE_BIN $QMAIL_ROOT_D/bin/cmd5checkpw $TRUE_BIN
}" > "$xinetd_dir/smtps_${product}" || die "$inten"
					;;
				*)
					echo "
service smtps
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = root
	instances       = UNLIMITED
	server          = $QMAIL_ROOT_D/bin/tcp-env
	server_args     = -Rt0 $QMAIL_ROOT_D/bin/relaylock $QMAIL_ROOT_D/bin/qmail-smtpd $QMAIL_ROOT_D/bin/smtp_auth $TRUE_BIN $QMAIL_ROOT_D/bin/cmd5checkpw $TRUE_BIN
}" > "$xinetd_dir/smtps_${product}" || die "$inten"
					;;
			esac	
			;;

		poppassd)
			echo "
service poppassd
{
	socket_type		= stream
	protocol		= tcp
	port			= 106
	wait			= no
	disable			= no
	user			= root
	instances		= 1000
	flags			= KEEPALIVE
	server			= $PRODUCT_ROOT_D/admin/bin/poppassd
}" > "$xinetd_dir/poppassd_${product}" || die "$inten"
			;;
	esac

    case "$machine" in
       Darwin)
echo '#!/bin/sh

name_script="$0"
name_service='org.xinetd.xinetd'
    
    case "$1" in
        start)
           echo "Plesk: Starting xinetd"
           launchctl start "$name_service"
        ;;
        stop)
           echo "Plesk: Stopping xinetd"
           launchctl stop "$name_service"
        ;;
        restart)
           $name_script stop
           $name_script start
        ;;
        *)
           echo "Usage: xinetd [start|stop|restart]"
        ;;
    esac 
' > "$PRODUCT_RC_D/xinetd"

     chmod 755 "$PRODUCT_RC_D/xinetd"
       ;;
       *)
       ;;
    esac

	suc
}

setup_inetd()
{
	local service rbl_on rbl_server

	service=$1;
	rbl_on=$2;
	rbl_server=$3;
	
	local ftp_rec smtp_rec pop3_rec 

	ftp_rec="ftp stream tcp nowait root $PRODUCT_ROOT_D/ftpd/sbin/proftpd proftpd -c $PRODUCT_ROOT_D/ftpd/etc/proftpd.conf"
	
	case "$linux_distr" in
		debian)
			maxconn='.1000'
		;;
		*)
		        maxconn=""
		;;
	esac

	case "$rbl_on" in
		on)
			smtp_rec="smtp stream tcp nowait$maxconn root $QMAIL_ROOT_D/bin/tcp-env tcp-env  $RBLSMTPD $rbl_server $QMAIL_ROOT_D/bin/relaylock $QMAIL_ROOT_D/bin/qmail-smtpd $QMAIL_ROOT_D/bin/smtp_auth $QMAIL_ROOT_D/bin/true $QMAIL_ROOT_D/bin/cmd5checkpw $QMAIL_ROOT_D/bin/true"
			smtps_rec="smtps stream tcp nowait$maxconn root $QMAIL_ROOT_D/bin/tcp-env tcp-env  $RBLSMTPD $rbl_server $QMAIL_ROOT_D/bin/relaylock $QMAIL_ROOT_D/bin/qmail-smtpd $QMAIL_ROOT_D/bin/smtp_auth $QMAIL_ROOT_D/bin/true $QMAIL_ROOT_D/bin/cmd5checkpw $QMAIL_ROOT_D/bin/true"
			;;
		*)
			smtp_rec="smtp stream tcp nowait$maxconn root $QMAIL_ROOT_D/bin/tcp-env tcp-env  $QMAIL_ROOT_D/bin/relaylock $QMAIL_ROOT_D/bin/qmail-smtpd $QMAIL_ROOT_D/bin/smtp_auth $QMAIL_ROOT_D/bin/true $QMAIL_ROOT_D/bin/cmd5checkpw $QMAIL_ROOT_D/bin/true"
			smtps_rec="smtps stream tcp nowait$maxconn root $QMAIL_ROOT_D/bin/tcp-env tcp-env  $QMAIL_ROOT_D/bin/relaylock $QMAIL_ROOT_D/bin/qmail-smtpd $QMAIL_ROOT_D/bin/smtp_auth $QMAIL_ROOT_D/bin/true $QMAIL_ROOT_D/bin/cmd5checkpw $QMAIL_ROOT_D/bin/true"
			;;
	esac

	case "$machine" in
		BSD*)
			poppassd_rec="poppassd stream tcp nowait/1000 root /usr/libexec/tcpd $PRODUCT_ROOT_D/admin/bin/poppassd"
			;;
		*)
			poppassd_rec="poppassd stream tcp nowait/1000 root /usr/sbin/tcpd $PRODUCT_ROOT_D/admin/bin/poppassd"
			;;
	esac

	case "$service" in

		ftp)
			if [ -x /usr/sbin/update-inetd ]; then

				# Use Debian inetd config manipulation facility
				/usr/sbin/update-inetd --enable "ftp"
				/usr/sbin/update-inetd --remove "ftp"
				/usr/sbin/update-inetd --add "$ftp_rec"

			else
				grep_res=`egrep "^ftp.*/${product}/ftpd/sbin/proftpd*." $inetd_conf`
				inten="add ftp service (proftpd) record into the $inetd_conf file"
				echo_try $inten

				case "$grep_res" in
					ftp*)
						p_echo
						p_echo " ftp service (proftpd) is already in the $inetd_conf"
						;;
					*)
						comment_service $service
						echo "$ftp_rec" >> $inetd_conf && suc || die
						;;
				esac
			fi
			;;

		smtp)
			if [ -x /usr/sbin/update-inetd ]; then

				# Use Debian inetd config manipulation facility
				/usr/sbin/update-inetd --enable "smtp"
				/usr/sbin/update-inetd --remove "smtp"
				/usr/sbin/update-inetd --add "$smtp_rec"

			else
				egrep "^smtp.*$QMAIL_ROOT_D/bin/tcp-env.*tcp-env.*$QMAIL_ROOT_D/bin/relaylock.*$" "$inetd_conf" >> $product_log 2>&1
				case "$?" in
					0)
						sed -e "/^smtp/d" < "$inetd_conf" > "$inetd_conf.${product}_tmp" \
						&& mv -f "$inetd_conf.${product}_tmp" "$inetd_conf" || die >> $product_log 2>&1
						;;
					1)
						comment_service $service
						;;
					*)
						err
						;;
				esac

				inten="add smtp service record into the $inetd_conf file"
				echo_try $inten
				echo "$smtp_rec"  >> $inetd_conf  && suc || die $inten
			fi
			;;

		smtps)

			if [ -x /usr/sbin/update-inetd ]; then

				# Use Debian inetd config manipulation facility
				/usr/sbin/update-inetd --enable "smtps"
				/usr/sbin/update-inetd --remove "smtps"
				/usr/sbin/update-inetd --add "$smtps_rec"

			else

				egrep "^smtps.*$QMAIL_ROOT_D/bin/tcp-env.*tcp-env.*$QMAIL_ROOT_D/bin/relaylock.*$" "$inetd_conf" >> $product_log 2>&1
				case "$?" in
					0)
						sed -e "/^smtps/d" < "$inetd_conf" > "$inetd_conf.${product}_tmp" \
						&& mv -f "$inetd_conf.${product}_tmp" "$inetd_conf" || die >> $product_log 2>&1
						;;
					1)
						comment_service $service
						;;
					*)
						err
						;;
				esac

				inten="add smtps service record into the $inetd_conf file"
				echo_try $inten
				echo "$smtps_rec"  >> $inetd_conf  && suc || die $inten
			fi
			;;

		poppassd)

			if [ -x /usr/sbin/update-inetd ]; then

				# Use Debian inetd config manipulation facility
				/usr/sbin/update-inetd --enable "poppassd"
				/usr/sbin/update-inetd --remove "poppassd"
				/usr/sbin/update-inetd --add "$poppassd_rec"
			else
				#	^poppassd.*$PRODUCT_ROOT_D/admin/bin/poppassd.*
				grep_res=`egrep "^poppassd.*$PRODUCT_ROOT_D/admin/bin/poppassd.*" $inetd_conf`
				inten="add poppassd service record in the $inetd_conf"
				echo_try $inten
		
				case "$grep_res" in
					poppassd*)
						p_echo
						p_echo " poppassd service is already in the $inetd_conf"
						;;
					*)
						comment_service $service
						echo "$poppassd_rec" >> $inetd_conf && suc || die
						;;
				esac
			fi
			;;
	esac

}

setup_super_server()
{
	local service rbl_on rbl_server
	service=$1;
	rbl_on=$2;
	rbl_server=$3;

	case "$super_server" in

		xinetd)
			setup_xinetd "$service" "$rbl_on" "$rbl_server"
			;;
		inetd)
			setup_inetd "$service" "$rbl_on" "$rbl_server"
			;;
	esac

}

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

	remove_mysql_auth
	packagemng_set_dirty_flag
	delete_mysql_auth

	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
	if type pidof >/dev/null 2>&1; 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
}
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
}

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

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
}
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=""
	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.swsoft.com/support"
	sales_email="sales@swsoft.com"

	product_version="8.2.1"
	product_db_version="0821"
	product_build="82070924.19"
	conceived_os_vendor=FreeBSD
	conceived_os_version="5.5"
	osrels="fr5.5"

	# This variable contains all versions, which is supported by
	# cumulative upgrade
	known_product_versions="71 75 80 81 82"

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

setenv_mysql()
{
	mysqlsock=`get_my_cnf_param  socket`
	if [ -S "$mysqlsock" ]; then
		MYSQL_UNIX_PORT=$mysqlsock && export MYSQL_UNIX_PORT
	else
		for i in $MYSQL_SOCKETS
		do
			if [ -S "$i" ]; then
				MYSQL_UNIX_PORT=$i
				export MYSQL_UNIX_PORT
				break
			fi
		done
	fi
}

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

 #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
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
QMAIL_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
MAILMAN_ROOT_D=/usr/local/psa/mailman
MAILMAN_VAR_D=/usr/local/psa/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/psa/bin/gpg
TAR_BIN=/usr/bin/gtar
CURL_CA_BUNDLE_FILE=/usr/share/curl/curl-ca-bundle.crt
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

}


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

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

	setenforce "$SELINUX_ENFORCE"
}


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

	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
}
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_ROOT_D}/etc/logrotate.d"
}

parse_logrotate_conf()
{
    local config_in="$1"
    local config_out="$2"

    if [ ! -f ${config_in} ]; then
	return 1
    fi

    sed -e "s|@@PRODUCT_ROOT_D@@|${PRODUCT_ROOT_D}|g" \
	-e "s|@@HTTPD_LOG_D@@|${HTTPD_LOG_D}|g" \
	-e "s|@@CATALINA_HOME@@|${CATALINA_HOME}|g" \
	< $config_in > $config_out || die "$inten"
    
    return 0
}

add_tomcat_to_logrotate()
{
    local template="$1"

    inten="add tomcat logs into logrotate configs"
    echo "$inten"

    parse_logrotate_conf "${PRODUCT_ETC_D}/logrotate.conf-tomcat.in" "${logrotate_conf}-tomcat"
    cat ${logrotate_conf}-tomcat >> $logrotate_conf

    rm -f ${logrotate_conf}-tomcat
    
    return 0
}

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"
	mysql_socket="/tmp/mysql.sock"

	if [ -x "${PRODUCT_RC_D}/mysql-server" ]; then
	    mysql_service="${PRODUCT_RC_D}/mysql-server"
	elif [ -x "${PRODUCT_RC_D}/mysql-server.sh" ]; then
	    mysql_service="${PRODUCT_RC_D}/mysql-server.sh"
	elif [ -x "${PRODUCT_RC_D}/mysqld" ]; then
	    mysql_service="${PRODUCT_RC_D}/mysqld"
	elif [ -x "${PRODUCT_RC_D}/mysql" ]; then
	    mysql_service="${PRODUCT_RC_D}/mysql"
	elif [ "X$DEMO_VERSION" = "Xyes" ]; then
	    mysql_service="${PRODUCT_RC_D}/mysqld"
	else
	    die "$inten"	
	fi
}

set_mysql_client_params()
{
	mysql_client="$MYSQL_BIN_D/mysql"

#	Override these variables as needed
	mysql_db_name="$PRODNAME"
	mysql_passwd_file="$product_etc/.${PRODNAME}.shadow"
	prev_mysql_passwd_file="$PREV_PRODUCT_ROOT_D/admin/conf/admin.conf"

	mysql_auth=""
 	if [ -z "$mysql_unconfigured" ];then
#	Need for mysqld_status related function
		set_mysql_server_params	
		set_mysql_auth
	fi

	mysql_args="-N"
	mysql_args_raw="-B -r"

	# For backward compatibility only, should use mysql() and mysql_raw() instead
	mysql=mysql
	mysql_raw=mysql_raw
}

# 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

	mysqld_status || mysqld_start 1

	mysql_auth="--user=admin --password=$admin_passwd"

	mysql_test_connection || die "$inten"
	suc
}

delete_mysql_auth()
{
	:
}

remove_mysql_auth()
{
	:
}

get_admin_passwd()
{
    [ -z "$admin_passwd" ] || return 0

#    if [ "$do_upgrade" = "1" -a ! -f "$mysql_passwd_file" ]; then
#		die "Unable to get admin passwd on upgrade"
#   fi

    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_auth $mysql_args "$@" 2>>"$product_log"
	else
		$mysql_client $mysql_auth $mysql_args "$@" 2>>"$product_log"
	fi

	local status=$?
	if [ $status -gt 0 ]; then
		$mysql_client $mysql_auth $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_auth $mysql_args "$@" 2>>"$product_log"
}

# Invoke mysql in raw mode
mysql_raw()
{
	mysql $mysql_args_raw "$@"
}

mysql_raw_anydb()
{
	mysql_anydb $mysql_args_raw "$@"
}

mysqld_start()
{
	mysqld_start_freebsd
	if [ -z "$1" ]; then
		mysql_test_connection 5 || die "Unable to perform test connection to mysql"
	fi
}

mysqld_start_freebsd()
{
	local inten service count
	inten="start MySQL server"
	echo_try $inten

	mysqld_status && return 0 \
	    || $mysql_service start >> $product_log 2>&1

	echo -n "Waiting for start mysql daemon.. "

	count=60
	while [ 0$count -gt 0 ]; do
	    mysqld_status && return 0
	    sleep 1
	    count=`expr $count - 1`
	done

	die $inten
}

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 1
	done

	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
}

###	FIXME: probably need var service_restart warn
mysqld_stop()
{
	local op_result i

	inten="stop MySQL server"
	echo_try $inten

	$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 ! mysqld_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"
}

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

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 mysqld_status; then
		p_echo "===>Removing installed $PRODUCT_NAME components ... "
		remove_modules
		mysqld_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

	remove_super_server "ftp"
	remove_super_server "pop3"
	remove_super_server "pop-3"
	remove_super_server "imap4"
	remove_super_server "imap2"
	remove_super_server "imap"
	remove_super_server "smtp"
	remove_super_server "smtps"
	remove_super_server "poppassd"

	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
}
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
		setup_super_server "smtp"
		setup_super_server "smtps"
		setup_super_server "ftp"
		setup_super_server "poppassd"
		

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

    local isBasePackage=""
    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

    ### All additional comonents consists depend to base package
    ### Therefore mysql already exists.
    #Need for BSD_4.x such as all startup scripts from ports
    #use include /etc/rc.subr instead /usr/local/etc/rc.subr
    #rc.subr is exists into BSD_5.x and above.
    if [ ! -f /etc/rc.subr -a -f /usr/local/etc/rc.subr ]; then
	cp -f /usr/local/etc/rc.subr /etc/rc.subr
    fi

    set_mysqld_params
    setenv_mysql
    mysqld_status || mysqld_start || die "start mysql"

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

parse_tomcat_initscript()
{
	local script_name="$1"
	local tomcat_src_file tomcat_dst_file

	if [ "X$PLESK_VZ" = "X1" ]; then        # we are in virtuozzo
		return
	fi

	tomcat_src_file="/etc/init.d/${script_name}"
	tomcat_dst_file="/etc/init.d/${script_name}.parsed"

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

		echo -n "Parsing ${tomcat_src_file} to switch on security mode... "

		cat "${tomcat_src_file}" | awk 'BEGIN { state=0; }
		{
			outstring = $0;

			if (state == 1) {

				i1 = index(outstring, "daemon");
				i2 = index(outstring, "--user");
				ix = index(outstring, "start");
				iy = index(outstring, "-security");

				j1 = index(outstring, "su");
				j2 = index(outstring, "-c");

				if ((iy == 0) && (((i1 > 0 ) && (i2 > i1) && (ix > i2)) ||
					((j1 > 0 ) && (j2 > j1) && (ix > j2)))) {
					gsub("start", "start -security", outstring);

				} else {

					if (index(outstring, "stop() {"))
						state = 2;
				};
			};

			if (state == 0) {
				if (index(outstring, "start() {" ) != 0)
					state = 1;
			};

			print outstring;

		}' > "${tomcat_dst_file}"

		difference=`diff "${tomcat_src_file}" "${tomcat_dst_file}"`

		if [ "X${difference}" = "X" ]; then
			echo "file unchanged."
			rm -f ${tomcat_dst_file}
		else
			echo "done."
			mv -f ${tomcat_dst_file} ${tomcat_src_file}
			chmod 755 ${tomcat_src_file}
			chown root:0 ${tomcat_src_file}
		fi
	fi
}

parse_initscript_suse()
{
    #remove pid file after stopping service..
    local pidfile='/var/run/tomcat5.pid'
    local key1="rm -f $pidfile" 
    local key2="[ ! -f "$pidfile" ] && touch $pidfile; chown tomcat:tomcat $pidfile"
    local script='/etc/init.d/tomcat5'

    cat /etc/init.d/tomcat5 | \
    perl -e '
       foreach $tmp (<STDIN>){
          $string.=$tmp;
       }
  
       if ( $string !~ /@ARGV[0]/){ 
           $string =~ s/(\s stop\).*?)(\;\;)/$1@ARGV[0]\n        $2/gs;
       }
       if ( $string !~ /@ARGV[1]/){
          $string =~ s/(\s start\))(.*?\;\;)/$1\n       @ARGV[1]$2/gs; 
       }
       print $string;
    ' "$key1" "$key2" > "$script.new"

    mv "$script.new" "$script" 

    chmod 755 "$script"
}

parse_initscript_remove_bugs()
{
	local script_name="$1"
	local script="/etc/init.d/${script_name}"
	
	sed -e "s|chown \$TOMCAT_USER:\$TOMCAT_USER \$CATALINA_PID|chown \$TOMCAT_USER \$CATALINA_PID|" \
	    -e "s/\$kipd/\$kpid/g" \
		-e "s/if \[ \$RETVAL = 0 \]\; then/if [ 0 ]; then/g" \
		-e "s|^TOMCAT5_USER=.*|TOMCAT5_USER=\"$tomcat_user\"|g" \
		-e "s|^\(CATALINA_BASE=\).*|\1\$CATALINA_HOME|g" \
		-e "s|^\(TOMCAT5_SECURITY=.*\)|#\1|g" \
		"$script" > "$script.new"

    mv "$script.new" "$script" 

    chmod 755 "$script"
}

tomcat_ln_initscript()
{
		local script_name="$1"
		local script="/etc/init.d/${script_name}"
		local script_rc_d="/etc/rc.d/init.d/${script_name}"
	
		if [ -f $script_rc_d -a ! -f $script ]; then
			ln -sf $script_rc_d $script
		fi
}

parse_initscript_bsd()
{
    if [ "X$machine" = "XBSD" ]; then
         local startup_script="$PRODUCT_RC_D/tomcat5"

         if [ -f $startup_script ]; then
             sed -i "" -e 's|rc_pid=.*|rc_pid=`cat $pidfile`|' $startup_script 
         fi
    fi
}

tomcat_config_script()
{

    set_tomcat_params

    cat > "$tomcat_conf" << EOF

CATALINA_HOME="$CATALINA_HOME"
JASPER_HOME="$CATALINA_HOME"
CATALINA_TMPDIR="$CATALINA_HOME/temp"
JAVA_ENDORSED_DIRS="$CATALINA_HOME/common/endorsed"

TOMCAT_USER="tomcat"

#LANG=en_US

SHUTDOWN_WAIT=30
#JAVA_OPTS="-Xminf0.1 -Xmaxf0.3"

EOF

    set_java_home "$tomcat_conf"

    #parse catalina.sh 
	if [ -f "$CATALINA_HOME/bin/catalina.sh" ]; then
	    sed -e 's|@@@TCCONF@@@|/usr/share/tomcat5/conf|g' "$CATALINA_HOME/bin/catalina.sh" \
    		> "$CATALINA_HOME/bin/catalina.sh.tmp"
	    mv "$CATALINA_HOME/bin/catalina.sh.tmp" "$CATALINA_HOME/bin/catalina.sh"
    	chmod 755 "$CATALINA_HOME/bin/catalina.sh"
	fi
	
    chown -R tomcat:tomcat /var/log/tomcat5
}

tomcat_install_upgrade()
{
        local os_name="fr"
        local os_type="fr_5.5"

	if [ "X$std_to_pkg" = "X1" ]; then
	    CATALINA_OLD="$PRODUCT_ROOT_D/tomcat4"
	else
	    if [ -f /etc/psa/psa.conf ]; then 
	       CATALINA_OLD="`cat /etc/psa/psa.conf | grep CATALINA_HOME| awk '{print $2}'`" 
	    fi
	fi

        install_tomcat

        if [ "X5" = "X5" ]; then
            if [ "X$machine" = "XBSD" ]; then			
               parse_initscript_bsd
	    else
               tomcat_ln_initscript tomcat5
            fi

            if [ "X$os_name" = "Xsuse" ]; then
                 tomcat_config_script
                 parse_initscript_suse
            fi 

			if [ "X$os_type" = "Xsl_es10" -o "X$os_name" = "Xubuntu" -o "X$os_name" = "Xdebian" ]; then
	            parse_initscript_remove_bugs tomcat5
			fi

        else
	    if [ "X$machine" != "XBSD" ]; then
		tomcat_ln_initscript tomcat4
		parse_tomcat_initscript tomcat4
		parse_initscript_remove_bugs tomcat4
	    fi
        fi

        #Move tomcat apps from old CATALINA_HOME to new CATALINA_HOME
        if [ "X$CATALINA_OLD" != "X$CATALINA_HOME" ]; then
			### move dirs to new location
			for i in psa-users psa-wars; do
				[ -L $CATALINA_OLD/$i -a -d $CATALINA_HOME/$i ] \
				|| mkdir -p $CATALINA_HOME/$i \
				&& mv -f $CATALINA_OLD/$i/* $CATALINA_HOME/$i/* \
				&& rm -rf $CATALINA_OLD/$i \
				&& ln -sf $CATALINA_HOME/$i $CATALINA_OLD/$i \
				&& chown -R root:0 $CATALINA_HOME/$i
			done

			### rebuilding of symlinks, reffered from psa-webapps to psa-wars
			if [ -d $CATALINA_OLD/psa-webapps -a ! -d $CATALINA_HOME/psa-webapps ]; then 
	            pwd_dir=`pwd`
				cd $CATALINA_HOME/psa-wars \
				&& ls -d * | while read domain_dir; do
					[ -d "$domain_dir" ] \
	                && mkdir -p $CATALINA_HOME/psa-webapps/$domain_dir \
	                && chown root:$apache_group $CATALINA_HOME/psa-webapps/$domain_dir \
	                && cd $CATALINA_HOME/psa-wars/$domain_dir \
	                && ls *.war | while read war_file; do
			    		[ -f $war_file ] \
	                    && ln -sf $CATALINA_HOME/psa-wars/$domain_dir/$war_file $CATALINA_HOME/psa-webapps/$domain_dir/$war_file
	                done
	            done \
				&& rm -rf $CATALINA_OLD/psa-webapps && ln -sf $CATALINA_HOME/psa-webapps $CATALINA_OLD/psa-webapps
				cd $pwd_dir
			fi
        fi

		tomcat_create_server_link

		remove_apache_module webapp
		
		if [ "X$os_type" = "Xdebian_3.1" ]; then
			add_apache_module jk2
		else
			[ -f "dynamic/jk.conf" ] || \
				add_apache_module jk
		fi

		(unset MYSQL_PWD; ${PRODUCT_ROOT_D}/admin/bin/websrvmng -r) || p_echo "Unable to restart web server, please do it manually"
}

configure_apps_are_using_tomcat()
{
	configure_mod_jk
}

configure_mod_jk()
{
	local config_file
	local workers_file

	if [ "X$machine" = "XBSD" ]; then
	    config_file="$HTTPD_CONF_D/mod_jk.conf"
	    workers_file="$HTTPD_CONF_D/workers.properties"
	else
	    config_file="/etc/httpd/conf/mod_jk.conf"
	fi

#Set default configs
#	if [ ! -f "$config_file" -a -f "$config_file.sample" ]; then
#		cp $config_file.sample $config_file
#	fi

	if [ ! -f "$workers_file" -a -f "$workers_file.sample" ]; then
		cp $workers_file.sample $workers_file
	fi

	if [ -f $config_file -a "X$machine" != "XBSD" ]; then
		# Bug 90478	[tomcat] mod_jk settings disables default scripts to be executed
		sed -e 's|^\([[:space:]]*Alias[[:space:]]\+/test/*[[:space:]]\+\)|#\1|i' $config_file > ${config_file}.psatmp
		unlink ${config_file}.bak 2>/dev/null || rm -f ${config_file}.bak
		ln ${config_file} ${config_file}.bak
		mv ${config_file}.psatmp $config_file
	fi

	if [ "X$machine" = "XBSD" ]; then
#	Write jk configuration to apache config
		$PRODUCT_ROOT_D/admin/bin/websrvmng --reconfigure-all --without-restart
	fi
}

tomcat_common()
{
	read_conf
	set_common_params
	set_apache_params
	set_mysqld_params
	set_admin_params

	tomcat_install_upgrade

	if [ "X$machine" = "XBSD" -a "X$do_upgrade" != "X1" ]; then
		set_logrotate_params
		add_tomcat_to_logrotate
	fi

	configure_apps_are_using_tomcat
}

tomcat_configurator_upgrade_new_post()
{
	tomcat_common
}

tomcat_configurator_install_post()
{
	tomcat_common
}


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 tomcat_configurator_install_pre tomcat-configurator 8.2.1 fr5.5.build82070924.19
        else
	         package_script_call_main_function tomcat_configurator_upgrade_new_pre tomcat-configurator 8.2.1 fr5.5.build82070924.19
        fi
     ;;
     POST-INSTALL)
        if [ "$do_upgrade" = "0" ]; then
	         package_script_call_main_function tomcat_configurator_install_post tomcat-configurator 8.2.1 fr5.5.build82070924.19
        else
                 package_script_call_main_function tomcat_configurator_upgrade_new_post tomcat-configurator 8.2.1 fr5.5.build82070924.19
        fi
     ;;
     *)
          exit 1
     ;;
esac

exit 0


