#!/bin/bash
#
# Startup script for the Plesk
#
# Following comments are required for SuSE Linux
#
### BEGIN INIT INFO
# Provides:       plesk
# 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
#
#
# 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

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"
	
	minimal_changes="0"

	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.0.1"
	product_db_version="0701"
	product_build="040303.21"
	conceived_os_vendor="RedHat"
	conceived_os_version="9"
	osrels="rh9"

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

	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"
		;;
	    *)
			err
		;;
	esac
}

read_conf()
{	
	initial_conf

	if [ -s $prod_conf_t ]; then
		echo "===> Reading $prod_conf_t ..."
		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"
	rpm_suexec_bin=/usr/sbin/psa-suexec
	MYSQL_SOCKETS="/var/lib/mysql/mysql.sock /tmp/mysql.sock"
}


get_my_cnf_param()
{
	my_cnf=/etc/my.cnf

	[ -f ${my_cnf} ] && r=`perl -e '$p="'"$1"'";
	undef $/; $_=<>; s/#.*$//gm; 
	/\[mysqld\](.*?)\[/sg;
	$_=substr($1, rindex $1,"$p=") and 
	/$p=(.*)/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"

	[ -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
		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
		return 0
	  fi
	fi
	return 2
}
get_pid()
{
	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
}

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}
        while [ 0$count -gt 0 ]
        do
                ps -p $PIDS > /dev/null 2>&1 || break
                sleep 1
                count=`expr $count - 1`
        done
        if [ 0$count -eq 0 ]; then 
                echo "kill remaining processes:"
                ps w -p $PIDS 2>/dev/null
				kill -9 $1 > /dev/null 2>&1
        fi
        return 0
}

clean_sessions()
{
	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)
			action $"$1" $2
			;;
		*)
			rc_reset
			echo -n $"$1"
			$2
			rc_status -v
			;;
	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

admin_passwd="`cat /etc/$PRODNAME/.$PRODNAME.shadow`"
chkconf=/sbin/chkconfig
lockdir="/var/lock/subsys"
service="xinetd named mysqld qmail courier-imap"
optional_service="postgresql"
tomcat_service="tomcat4"
httpd_service="httpd"
start_sh=${PRODUCT_ROOT_D}/admin/bin/httpsdctl
proccess=admin/bin/httpsd

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


if [ -x ${rc_d}/xinetd ]; then
	inetd=xinetd
elif [ -x ${rc_d}/inet ]; then
	inetd=inet
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_start_service(){
#	setenv_mysql
	for i in $inetd $service
	do
	  if [ ! -f ${lockdir}/$i ]; then
	     ${chkconf} $i || ${chkconf} $i on
	     ${rc_d}/$i start
	  fi
	done
	for i in $optional_service
	do
	  if [ -f ${rc_d}/$i ]; then
	  	if [ ! -f ${lockdir}/$i ]; then
	     		${chkconf} $i || ${chkconf} $i on
	     		${rc_d}/$i start
		fi
	  fi
	done

	query="select count(*) from DomainServices where type='tomcat'"
	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
		     		${chkconf} $i || ${chkconf} $i on
					${PRODUCT_ROOT_D}/admin/sbin/websrvmng -t -v
			fi
		  fi
		done
	fi

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

stop_service(){
	stop
	for i in $service; do
		if [ "X$i" = "Xnamed" -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 ]; then
				${rc_d}/$i stop
			fi
		fi
	done
	for i in $optional_service; do
		if [ -f ${rc_d}/$i ]; then
			if [ -f ${lockdir}/$i ]; then
				${rc_d}/$i stop
			fi
		fi
	done
	for i in $httpd_service; do
		if [ -f ${rc_d}/$i ]; then
			if [ -f ${lockdir}/$i ]; then
				${rc_d}/$i stop
			fi
		fi
	done
	for i in $tomcat_service; do
		if [ -f ${rc_d}/$i ]; then
			if [ -f ${lockdir}/$i ]; then
				${rc_d}/$i stop
			fi
		fi
	done

}


start1(){
	setenv_mysql
	${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 ] && touch "$lockdir/$myname"
	return $ret
}

start(){
	check_and_start_service
	sleep 1
	clean_sessions
	start1
}



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(){
	${start_sh} restart
	clean_sessions
}

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 $?
