#!/bin/bash
#
# chkconfig: 345 85 15
# description: Plesk Interface and Utilities	
# processname: httpsd
# config: /usr/local/psa/admin/conf/httpsd.conf
# config: /usr/local/psa/admin/conf/httpsd.include
# pidfile: /usr/local/psa/admin/logs/httpsd.pid
# 
# Startup script for the Plesk
#
# Following comments are required for SuSE Linux
#
### BEGIN INIT INFO
# Provides:       plesk psa
# Required-Start: $remote_fs $time
# Required-Stop:
# X-UnitedLinux-Should-Start:
# X-UnitedLinux-Should-Stop:
# Default-Start:  3 5
# Default-Stop:   0 1 2 6
# Description:    Start the Plesk Server Administrator
### END INIT INFO
#
#

p_echo()
{
echo "$*"
}


initial_conf()
{
	DEMO_VERSION="no"
	PRODNAME="psa"
	PRODUCT_NAME="Plesk"
	product_full="Plesk"
	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="@@MYSQL_VERS@@"
	POSTGRESQL_VERS="@@POSTGRESQL_VERS@@"
	EXTERNAL_PACKAGES="@@EXTERNAL_PACKAGES@@"
	EXTERNAL_PACKAGES_DIR="@@EXTERNAL_PACKAGES_DIR@@"

	BUILDER_UID="@@BUILDER_UID@@"

	PERL5LIB=/usr/local/psa/lib/perl5/site_perl/5.8.0
	export PERL5LIB

	product_bs=Plesk
	support_email="support@sw-soft.com"
	sales_email="sales@sw-soft.com"

	product_version="7.5.4"
	product_db_version="0754"
	product_build="75050824.12"
	conceived_os_vendor="CentOS"
	conceived_os_version="3.3"
	osrels="centos3.3"

	# This variable contains all versions, which is supported by
	# cumulative upgrade
	known_product_versions="20 25 50 60 70 71 75"

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

	# GID for mailman
	mm_mailgroup=12

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

	my_name_0="`pwd`"
	if [ $? -ne 0 ]; then
		echo "Unable to determine current working directory."
		echo "Please fix the problem and run installation again."
		exit 1
	fi

	my_name_1="`basename ""$0""`"
	my_name_2=`echo ""$0""|sed -e "s/^\.\///"`
	echo $my_name_2 | egrep '^/' >/dev/null 2>&1
	case "$?" in
		0)
			my_name="$my_name_2"
		;;
		1)
			my_name="$my_name_0"/"$my_name_2"
		;;
	    *)
			echo "Unable to determine the name of installer."
			echo "Please fix the problem and run installation again."
			exit 1
		;;
	esac
}

read_conf()
{
	initial_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
		[ 0$ignore_miss_conf -ne 1 ] && p_echo "Unable to find product configuration file: $prod_conf_t"
		return 1
#		die "find product configuration file: $prod_conf_t"
	fi
	return 0

}

product_conf()
{
	initial_conf
	product_default_conf
	APACHE_ROOT="/usr/local/psa/apache"
	TRUE_BIN="$QMAIL_ROOT_D/bin/true"
	MYSQL_SOCKETS="/var/lib/mysql/mysql.sock /tmp/mysql.sock /var/run/mysqld/mysqld.sock"
	parse_tomcat_conf
}

parse_tomcat_conf()
{
       T4_CF=/etc/tomcat4/tomcat4.conf
       if [ -r $T4_CF ]; then
               catalinahome=`egrep "^CATALINA_HOME=" $T4_CF 2>/dev/null | sed -e "s/CATALINA_HOME=\"\(.*\)\"/\1/"`
               if [ -n $catalinahome ]; then
                       CATALINA_HOME=$catalinahome
			if [ -f $prod_conf_t ]; then
                	       echo "===> Updating $prod_conf_t..."
        	               sed -e "s#^\\(CATALINA_HOME\\)\\([[:space:]]*\\).*#\\1\\2$CATALINA_HOME#" "$prod_conf_t" >"$prod_conf_t.tmp" || die "update $prod_conf_t"
			       mv "$prod_conf_t.tmp" "$prod_conf_t" || die "update $prod_conf_t"
	               fi
		fi
       fi
}

get_my_cnf_param()
{
	local my_cnf cnf_files

	cnf_files="/etc/my.cnf /etc/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
}

conf_update()
{
	local def
	def="$1.default"
	umask 0022

	[ -s "$def" ] || return 1

	if [ ! -s "$1" ]; then
#		cp -f "$def" "$1"
#		return 0
		echo '#' > "$1"
	fi



perl -e '

while(<>){
last if( eof );
s/#.*$//;
next if /^\s*$/;
/(\w+)\s+(.+)$/;
$cf{$1}=$2;}

$cf{PRODUCT_ROOT_D}=$ENV{PRODUCT_ROOT_D} if $ENV{PRODUCT_ROOT_D};

while(<>){
 s/^\s*(\w+)(\s+)(.+)$/"$1$2".( (exists($cf{$1}))? $cf{$1}:$3 )/e;
 print;}

' "$1" "$def" > "$1.new"

	if [ -s "$1.new" ]; then
	  if cmp -s $1.new $1; then
  		rm -f $1.new
		return 1
	  else
		rm -f $1.old
		ln $1  $1.old
		mv -f $1.new $1
		chmod 644 $1    # bug 64313, 65043
		echo "config updated"
		return 0
	  fi
	fi
	return 2
}

# setup new value for parameter
# $1 config file name $1 paramater name, $2 parameter value
conf_setval()
{
	cat $1 | awk -v varname="$2" -v varvalue="$3" \
		'{ if ($1 == varname) { print varname "\t" varvalue; } else { print $0; } }' \
		> $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
}
get_pid()
{
	local i

	ex_f="$1"
	opt="$2"
	owner="$3"

	min_num=`expr 1`

	case "$opt" in
		false)
			for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | awk '{print $2}' -`; do
				min_num=$i
				break
			done
			;;
		true)
			for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | grep "$owner" | awk '{print $2}' -`; do
				min_num=$i
				break
			done
			;;
		*)
			p_echo "get_pid: wrong parameter"
			die "get_pid $ex_f $opt $owner"
			;;
	esac

	common_var=$min_num
	return $min_num
}

kill_pids()
{
	ex_f="$1"
	owner="$2"

	for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | grep $owner | awk '{print $2}' -`; do
		if [ $i -gt 1 ]; then
			$K_TERM $i >> $product_log 2>&1
		fi
	done
}

getppid()
{
	ps -o ppid -p $1|sed '1d;s/[[:space:]]*//g'
}

get_pids_byname()
{
	proc_name="$1"
	PIDS=`ps axww | awk '$5 ~ "'$proc_name'$" {print $1}'`
	echo $PIDS
}

wait_after_stop()
{
        PIDS=`echo "$1" | tr ' ' ,`
        count=${2:-50}
        # $product_log defined on installation only, not in /etc/init.d/psa
		test -n "$product_log" && pnnl_echo "Waiting for processes $PIDS terminates" >> $product_log
        while [ 0$count -gt 0 ]
        do
                ps -p $PIDS > /dev/null 2>&1 || break
                sleep 1
                test -n "$product_log" && pnnl_echo "." >> $product_log  
                count=`expr $count - 1`
        done
        if [ 0$count -eq 0 ]; then
                test -n "$product_log" && pnnl_echo "kill forced" >> $product_log
                kill -9 $1 > /dev/null 2>&1
        fi
		test -n "$product_log" && echo -e "\n" >> $product_log		
        return 0
}
clean_sessions()
{
	#VZP should we clean sessions on target VE?
	if [ -e "$vza_file" ]; then
		return
	fi
	if [ "X$admin_passwd" != "X" ]; then
	    query="delete from sessions"
	    echo "$query" | "$MYSQL_BIN_D/mysql" -u admin -p"$admin_passwd" $PRODNAME
	fi
}

# this function is designed to emulate RedHat-like service reporting on the SuSE Linux
report_action()
{
	# $1 - text to put
	# $2 - status of operation
	case `type -t action` in
		function)
			# red hat operation reporting style
			action $"$1" $2
			;;
		*)
			case `type -t rc_reset` in
				function)
					# suse linux reporting style
					rc_reset
					echo -n $"$1"
					$2
					rc_status -v
					;;
				*)
					# debian style, probably useful for other systems
					echo -n $"$1"
					$2
					if [ $? -eq 0 ]; then
						echo "done"
					else
						echo "failed"
					fi
					;;
			esac
			;;
	esac
}

myname=psa
PRODUCT_NAME="Plesk"

daemon_name=httpsd
do_rpm=1

rc_d="/etc/init.d"

# Source function library.
[ -f ${rc_d}/functions ] && . ${rc_d}/functions

# Source networking configuration.
[ -f /etc/sysconfig/network ] && . /etc/sysconfig/network

# Source subsystem configuration.
[ -f /etc/sysconfig/${myname} ] && . /etc/sysconfig/${myname}

# this way is for SuSE Linux
test -s /etc/rc.status && . /etc/rc.status && rc_reset

#product_conf
read_conf || exit 1

## VZA this directory exists only in SVE
vza_file=/var/vzagent

admin_passwd="`cat /etc/$PRODNAME/.$PRODNAME.shadow`"
chkconf=/sbin/chkconfig
lockdir="/var/lock/subsys"
optional_service="rhdb"
optional_service_wo_lock="${PRODNAME}-spamassassin"
service_after_psa="drwebd"
tomcat_service="tomcat4"
httpd_service="httpd"
named_service="named"
start_sh=${PRODUCT_ROOT_D}/admin/bin/httpsdctl
proccess=admin/bin/httpsd
LOCKDIR_AVAILABLE="Yes"
if [ -e "$vza_file" ]; then
	service="mysqld"
else
	service="${named_service} mysqld qmail courier-imap"
fi

#set openssl config
OPENSSL_CONF="${PRODUCT_ROOT_D}/admin/conf/openssl.cnf"
export OPENSSL_CONF
#set  language
LANG=C
export LANG

setenv_mysql

if [ -x ${rc_d}/xinetd ]; then
	inetd=xinetd
elif [ -x ${rc_d}/inet ]; then
	inetd=inet
elif [ -x ${rc_d}/inetd ]; then
	inetd=inetd
else
  echo "It is problem with inet daemon"
  exit 1
fi

checkservice(){
	for i in $myname $inetd $service; do
		${chkconf} $i || ${chkconf} $i on
	done
}

check_and_enable_service()
{
	[ ! -x ${chkconf} ] || ${chkconf} $1 || ${chkconf} $1 on
}

check_and_start_service(){

	for i in $inetd $service; do
		if [ ! -f ${lockdir}/$i ]; then
			check_and_enable_service $i
			${rc_d}/$i start
		fi
	done
	for i in $optional_service; do
		if [ -f ${rc_d}/$i ]; then
			if [ ! -f ${lockdir}/$i ]; then
				check_and_enable_service $i
				${rc_d}/$i start
			fi
		fi
	done
	for i in $optional_service_wo_lock; do
		if [ -f ${rc_d}/$i ]; then
				check_and_enable_service $i
				${rc_d}/$i start
		fi
	done

	query="SELECT COUNT(*) FROM DomainServices WHERE type='tomcat' AND status=0"
	active_ds=`echo "$query" | "$MYSQL_BIN_D/mysql" -u admin -p"$admin_passwd" -N $PRODNAME | cat`
	if [ 0$active_ds -gt 0 ]; then
		for i in $tomcat_service; do
			if [ -f ${rc_d}/$i ]; then
				if [ ! -f ${lockdir}/$i ]; then
					check_and_enable_service $i
					${PRODUCT_ROOT_D}/admin/sbin/websrvmng -t -r -v
				fi
			fi
		done
	fi

	for i in $httpd_service; do
		if [ -f ${rc_d}/$i ]; then
			if [ ! -f ${lockdir}/$i ]; then
				check_and_enable_service $i
				${PRODUCT_ROOT_D}/admin/sbin/websrvmng -p -v
			fi
		fi
	done
}

check_and_start_service_after_psa(){
	for i in $service_after_psa; do
		if [ -f ${rc_d}/$i ]; then
	  		if [ ! -f ${lockdir}/$i ]; then
				check_and_enable_service $i
	     		${rc_d}/$i start
			fi
		fi
	done
}

stop_service(){
	stop
	for i in $service; do
		if [ "X$i" = "X${named_service}" -a -f /etc/mandrake-release ]; then
			named_pids=`get_pids_byname named`
			if [ ! -z "$named_pids" ];then
				kill -9 $named_pids
				report_action "Stopping named: " /bin/true
				rm -f "$lockdir/named"
			fi
		else
			if [ -f ${lockdir}/$i -o "X$LOCKDIR_AVAILABLE" = "XNo" ]; then
				${rc_d}/$i stop
			fi
		fi
	done
	for i in $optional_service; do
		if [ -f ${rc_d}/$i ]; then
			if [ -f ${lockdir}/$i -o "X$LOCKDIR_AVAILABLE" = "XNo" ]; then
				${rc_d}/$i stop
			fi
		fi
	done
	for i in $optional_service_wo_lock; do
		if [ -f ${rc_d}/$i ]; then
				${rc_d}/$i stop
		fi
	done
	for i in $httpd_service; do
		if [ -f ${rc_d}/$i ]; then
			if [ -f ${lockdir}/$i -o "X$LOCKDIR_AVAILABLE" = "XNo" ]; then
				${rc_d}/$i stop
			fi
			$PRODUCT_ROOT_D/bin/apache_cleanup.sh
		fi
	done
	for i in $tomcat_service; do
		if [ -f ${rc_d}/$i ]; then
			if [ -f ${lockdir}/$i -o "X$LOCKDIR_AVAILABLE" = "No" ]; then
				${rc_d}/$i stop
			fi
		fi
	done
	for i in $service_after_psa; do
		if [ -f ${rc_d}/$i ]; then
			if [ -f ${lockdir}/$i -o "X$LOCKDIR_AVAILABLE" = "No" ]; then
				${rc_d}/$i stop
			fi
		fi
	done

}


start1(){
	${start_sh} start
	ret=$?

	if [ $ret -eq 0 ]; then

		# clean backup flags
		${PRODUCT_ROOT_D}/admin/sbin/bu_flags_cleaner > /dev/null 2>&1

	    report_action "Starting ${PRODUCT_NAME}: " /bin/true
	else
    	    report_action "Starting ${PRODUCT_NAME}: " /bin/false
	fi
	[ $ret -eq 0 ] && [ -d ${lockdir} ] && touch "$lockdir/$myname"
	[ $ret -eq 0 ] && ${PRODUCT_ROOT_D}/admin/bin/packagemng --set-dirty-flag
	return $ret
}

start(){
	check_and_start_service
	sleep 1
	clean_sessions
	if [ -e "$vza_file" ]; then
		# temporary disable updater
		export PLESK_KEYUPDATE_DISABLED="starting"
	fi
	start1
	sleep 1
	check_and_start_service_after_psa
}



stop(){
	if [ -f "$lockdir/$myname" ]; then
		${start_sh} stop
#		[ ! "`get_pids_byname $proccess`" ]
		wait_after_stop "`get_pids_byname $proccess`" 100
		ret=$?
		if [ $ret -eq 0 ]; then
		    report_action "Stopping ${PRODUCT_NAME}: " /bin/true
		else
    		    report_action "Stopping ${PRODUCT_NAME}: " /bin/false
		fi
		[ $ret -eq 0 ] && rm -f "$lockdir/$myname"
		return $ret
	else
		${start_sh} stop > /dev/null 2>&1
		true
	fi
}

restart(){

	status ${myname} ${daemon_name} > /dev/null 2>&1

	case $? in

	0)
		if [ -e "$vza_file" ]; then
			# temporary disable updater
			export PLESK_KEYUPDATE_DISABLED="restarting"
		fi
		${start_sh} restart
		ret=$?
		clean_sessions
		[ $ret -eq 0 ] && ${PRODUCT_ROOT_D}/admin/bin/packagemng --set-dirty-flag
		;;

	*)
		echo "PSA is down, perfoming full restart. "
		start
		;;
	esac
}

condrestart(){
    [ -e "$lockdir/$myname" ] && restart || :
}

reload(){
    [ -e "$lockdir/$myname" ] && ${start_sh} reload
}

# this routine is psa specific override of standard status function
status() {
	local base=${1##*/}
	local dbase=${2##*/}
	local pid

	# Test syntax.
	if [ $# = 0 ] ; then
		echo $"Usage: status {service name} {daemon name}"
		return 1
	fi

	# First try "pidof"
	pid=`pidof -o $$ -o $PPID -o %PPID -x $2 || \
	     pidof -o $$ -o $PPID -o %PPID -x ${dbase}`
	if [ "$pid" != "" ] ; then
	        echo $"${dbase} (pid $pid) is running..."
	        return 0
	fi

	# Next try "/var/run/*.pid" files
	if [ -f /var/run/${base}.pid ] ; then
	        read pid < /var/run/${base}.pid
	        if [ "$pid" != "" ] ; then
	                echo $"${base} dead but pid file exists"
	                return 1
	        fi
	fi
	# See if /var/lock/subsys/${base} exists
	if [ -f /var/lock/subsys/${base} ]; then
		echo $"${base} dead but subsys locked"
		return 2
	fi
	echo $"${base} is stopped"
	return 3
}


# See how we were called.
case "$1" in
  start)
    start
    ;;
  start1)
    start1
    ;;
  startall)
    check_and_start_service
    ;;
  stop)
    stop
    ;;
  stop1)
    stop
    ;;
  stopall)
    stop_service
    ;;
  checkservice|check|chk)
    checkservice
    ;;
  status)
    status ${myname} ${daemon_name}
    ;;
  reload)
    reload
    ;;
  restart)
    restart
    ;;
  restart1)
    stop
    start1
    ;;
  condrestart)
    condrestart
    ;;
  *)
    echo $"Usage: $0 {start|stop|stopall|restart|checkservice|status|condrestart}"
    exit 1
esac

exit $?
