#!/bin/sh
# chkconfig: 345 81 29
# description: stunnel

# Source function library.
. /etc/rc.d/init.d/functions

#action $"Stopping $prog: " /bin/true

arg="$1"

product="psa"
product_root="/usr/local/psa"
PATH=/bin:/sbin:/usr/bin:/usr/sbin; export PATH

die()
{
	echo "ERROR! Exiting"
	echo
	exit 1
}

set_local_params()
{
	TARGET_OS="`uname -a`"

	K_TERM="/bin/kill -TERM"

	MYSQL_PORT=3306
	MYSQLS_PORT=30000
	ST_ROOT="/usr/sbin"
	SERT="$product_root/admin/conf/httpsd.pem"
	STUNNEL="$ST_ROOT/stunnel"
	STUNNEL_LOCK="/var/lock/subsys/stunnel"
	STUNNEL_PROG="stunnel"
	STUNNEL_GREP="stunnel"

	common_var=0

	case "$TARGET_OS" in
		BSD/OS*BSDI*i386| \
		FreeBSD*i386| \
		Linux*2.?.*i?86*)	
			ps="/bin/ps axuw"
			;;
		SunOS*5.*sun4*)
			ps="/bin/ps -aef"
			;;
		*)	die
			;;
	esac

	case "`echo 'x\c'`" in
		'x\c')
			echo="echo -n"
			nnl=
			;;
		x)
			echo="echo"
			nnl="\c" 
			;;
		*)
			echo "$0: ERROR -- can't set up echo"
			exit 1
			;;
	esac
}

kill_pids()
{
	ex_f="$1"
	owner="$2"
	pids="`$ps | grep $ex_f | grep -v grep | grep $owner | grep $SERT | awk '{print $2}' -`"

	for i in $pids; do
		if [ $i -gt 1 ]; then
			$K_TERM $i > /dev/null 2>&1
		fi
	done
}

get_pids()
{
	req_pid=`expr 1`

	for i in `$ps | grep $STUNNEL_GREP | grep -v grep | grep root | grep $SERT | awk '{print $2}' -`; do
		req_pid=$i
		break
	done
}

stop()
{
		if [ $req_pid -gt 1 ]; then
			kill_pids $STUNNEL_GREP root
			sleep 2
			rm -f $STUNNEL_LOCK
			action $"Stopping $STUNNEL_PROG: " /bin/true
		else
			action $"Stopping $STUNNEL_PROG: " /bin/false
		fi

}

start()
{
		if [ $req_pid -gt 1 ]; then
			action $"Starting $STUNNEL_PROG: " /bin/true
			return
		fi
		if [ -x $STUNNEL ]; then
			$STUNNEL -d $MYSQLS_PORT -p $SERT -r $MYSQL_PORT
			touch $STUNNEL_LOCK
			action $"Starting $STUNNEL_PROG: " /bin/true
		else
			action $"Starting $STUNNEL_PROG: " /bin/false
		fi
}

# Start actions
set_local_params
get_pids

case "$arg" in
	start|'')
		start
		;;
	stop)
		stop
		;;
	restart)
		if [ $req_pid -gt 1 ]; then
			stop
			get_pids
			start
		else
			start
		fi
		;;
	*)
		echo "wrong usage"
		exit 1
		;;
esac

exit 0
