#!/bin/sh
#  $Id: stop.sh,v 1.55 2005/06/20 19:15:58 peterc Exp $
#  Copyright (C) 1999-2005 Tarantella, Inc.
#  This software code contains proprietary information
#  and should be treated as confidential.
#
#  Component: script to stop auxserver and JServer
#  Author: billwe

if [ -f $TTAMSG/common -a -f $TTAMSG/tta_stop ]; then
  . $TTAMSG/common
  . $TTAMSG/tta_stop
else
  echo "Unable to open message file: $TTAMSG/tta_stop"
  exit 1
fi


case "$trace" in
x) set -x
esac

# cd to the directory containing this script, so that we can use
# relative pathnames
ttacommand=$0
case "$ttacommand" in
/*) cd `dirname $ttacommand`
    ;;
*)  fullpath=`pwd`/$ttacommand
    cd `dirname $fullpath`
esac


# Function to stamp the "stopped" file.
stamp()
{
    # Touch the stop file with the current time.
    ( umask 077 ; date > ${TTADATADIR}/info/stopped )
    [ -f /var/lock/subsys/Tarantella ] && rm -f /var/lock/subsys/Tarantella
}

# parse the passed in arguments
dokill=no
dorestart=no
unset tclarg
unset quiet
tcltokenarg="SESSIONTOKENFILE="
for o in "$@"; do
   case "$o" in
	--help )
	    echo "$lf_usage" 1>&2
	    exit 1
	    ;;
	--kill )
	    dokill=yes
	    ;;
	--quiet )
	    quiet=$o
	    ;;
	--force ) 
	    tclarg=$o
	    ;;
        --restart )
            dorestart=yes
	    tclarg=$o
	    ;;
        SESSIONTOKENFILE* ) 
	    tcltokenarg=$o
	    ;;
	* )
	    echo "$lf_badarg $o" 1>&2
	    echo "$l_shortusage" 1>&2
	    exit 1
	    ;;
    esac
done

# Make sure that they are running as root
u="`LANG=C LC_ALL=C id | sed 's/.*uid=\([0-9][0-9]*\).*/\1/'`"
if [ "$u" = "0" ]
then
  : # all is okay
else
  echo "You must be root to run this program"
  exit 15
fi


getProcessInfo()
{
    case "$SCOARCH" in
    i3li*|ppli*) processInfo=`ps ajx 2>/dev/null | awk '$2=="'"$1"'"{print}'` ;;
    *)     processInfo=`ps -fp$1 2>/dev/null | awk '$2=="'"$1"'"{print}'`
	   [ -z "$processInfo" ] && processInfo=`ps -ajx 2>/dev/null | awk '$2=="'"$1"'"{print}'`
    esac
    echo "$processInfo"
}

killIt()
{
    name="$1"; shift
    file="$1"; shift
    processids="$*"

    if [ -z "$quiet" ] ; then
	echo "$name pid=$processids"
    fi
    for pid in $processids ; do
        count=10
        while [ $count -gt 0 ]; do
	    processInfo=`getProcessInfo $pid`
            if [ -n "$processInfo" ]; then
                kill $pid
                count=`expr $count - 1`
                sleep 1
            else
		if [ -z "$quiet" ]  ; then
		    echo "${stop_success}$name"
                fi
                break
            fi
        done
        if [ $count -eq 0 ]; then
	    if [ ! -z "$tryhard" ] ; then
		kill -9 $pid
		sleep 1
		processInfo=`getProcessInfo $pid`
	    fi
	    if [ -n "$processInfo" -a -z "$quiet" ] ; then 
		    echo "${stop_failed}$name (PID=$processids)"
            fi
        fi
    done
    rm -f $file

    stamp
}

killHelpers() {
    # Kill the ttaprintfifo process, as on some platforms it may not get killed
    # by the JServer correctly.
	for printfifofile in `ls -d ${TTADATADIR}/info/PrintFifo* 2>/dev/null`; do
	printfifoPid=`expr "$printfifofile" : "${TTADATADIR}/info/PrintFifo\(.*\)"`
	tryhard=t
	killIt printfifo $printfifofile $printfifoPid >/dev/null
	tryhard=
    done

    # Kill the Tier2 load probe explicitly, as sometimes it takes a while to notice
    # that we've gone 
    PROBE_FILE="${TTADATADIR}/info/tier2loadprobe.pid"

    if [ -f "$PROBE_FILE" ]; then
        PROBE_PID="`tail -1 $PROBE_FILE | sed -e 's/ //'`"
        if [ -n "$PROBE_PID" ]; then
            tryhard=t
            killIt tier2loadprobe $PROBE_FILE $PROBE_PID >/dev/null
            tryhard=
	fi
    fi

    if [ "$dorestart" = no ]; then
        # Kill the ttalaunchhelper process (unless a warm restart)
        LaunchHelperInfoFile=${TTADATADIR}/info/launchhelperinfo
        if [ -f "${LaunchHelperInfoFile}" ]; then
	    LaunchHelperPid=`awk '{print $1}' <${LaunchHelperInfoFile}`
	        [ -n "${LaunchHelperPid}" ] && killIt ttalaunchhelper ${LaunchHelperInfoFile} ${LaunchHelperPid} >/dev/null
	    rm -f "${LaunchHelperInfoFile}"
        fi
    fi

    # disable TTA printer
    ${TTADIR}/bin/scripts/lpdisable >/dev/null 2>&1
}

# if we did not get a --kill argument, then we send a message to the server
# asking it to go away.

if [ "$dokill" = no ]; then 
    ./run_tclscript proper_stop $tcltokenarg $tclarg $quiet $ignoresessions
    err=$?
    if [ "$err" != "1" ]; then
        # stop the cdm if it is installed, and this isn't a restart
        if [ "$dorestart" = no -a -x $TTADIR/bin/scripts/stop_cdm ]; then
          $TTADIR/bin/scripts/stop_cdm --quiet
        fi

	killHelpers
	stamp
    fi
    exit $err
fi

# Where are we relative to top of tta tree?
top=.
for _i in 0 1 2 3 4 5 6 7 8 9; do
    [ -d $top/bin/java -a -x $top/bin/tarantella ] && break
    [ -f $top/etc/passwd ] && { top=.; break; }
    top=../$top
done


cwd=`pwd`
cd "$top"
installdir=`pwd`
cd "$cwd"

echo "$stop_killintro"

# stop the cdm if it is installed
if [ -x $TTADIR/bin/scripts/stop_cdm ]; then
  $TTADIR/bin/scripts/stop_cdm --quiet --kill
fi

killHelpers

# Kill the AuxServer
auxserverfile=${TTADATADIR}/info/auxserver.pid
if [ ! -f $auxserverfile ]; then
    if [ -z "$quiet" ] ; then 
	echo "${stop_already}${auxservername}"
    fi
else
    auxserverPid=`cat $auxserverfile`
    killIt "$auxservername" $auxserverfile $auxserverPid
fi

# Kill the JServer
jserverfile=${TTADATADIR}/info/jserver.pid
if [ ! -f $jserverfile ]; then
    if [ -z "$quiet" ]; then 
	echo "${stop_already}${jservername}"
    fi
else
    jserverPid=`cat $jserverfile`
    killIt "$jservername" $jserverfile $jserverPid
fi



getChildrenOfPid() 
{
## Warning - the following code is Linux specific.  (And if 
## /proc/<pid>/exe changes, will break)
## PS: It was changed. And it did break. [Fitz 605468]
ppid="$1"
exepattern="$2"
exclpattern="$3"
childrenpids=""
# Get children of ppid
ALLCHILDPIDS=`echo "$ps_output" | grep "^ *$ppid " | awk '{ print $2 }'`

if [ -z "$exepattern" ] ; then 
    childrenpids="$ALLCHILDPIDS" 
else 
    if [ ! -z "$ALLCHILDPIDS" ] ; then 
	for p in $ALLCHILDPIDS ; do
	    # is the executable one we worry about?
	    if [ -n "`find /proc/$p -name exe -lname \"$exepattern\" 2>/dev/null | sort | sed 1q`" ] ; then
		# yes 
                if [ -z "$exclpattern" ]; then
                    childrenpids="$childrenpids $p"
                else
                    check=`ps --noheading --pid $p -w -o args | grep -- "$exclpattern"`
                    [ -z "$check" ] && childrenpids="$childrenpids $p"
                fi
	    fi
	done
    fi
fi
echo $childrenpids
}

removeSurplusJVMs() 
{
# this will kill any instances of our JVM whose parent is init.
case "$SCOARCH" in
    i3li*|ppli*)
	## cache the output of ps, as it may be called several times, and can
	## be slow.
	ps_output=`ps --no-heading -ax -o ppid,pid 2>/dev/null`
	
	PIDSTOKILL=""
	PPIDS=`getChildrenOfPid 1 "$TTABINDIR/j*" "-classpath $TTADIR/webserver"`
	while [ ! -z "$PPIDS" ] ; do
	    CHILDPIDS=""
	    PIDSTOKILL="$PIDSTOKILL $PPIDS"
	    for pp in $PPIDS ; do 
		CHILDPIDS="$CHILDPIDS `getChildrenOfPid $pp`"
	    done
	    PPIDS="$CHILDPIDS"
	done
	if [ ! -z "$PIDSTOKILL" ] ; then 
	    for p in $PIDSTOKILL ; do 
		if [ -d /proc/$p ] ; then 
		    kill $p 2>/dev/null
		    # give it time to exit
		    sleep 1
		    if [ -d /proc/$p ]; then
			kill -9 $p 2>/dev/null
			echo -n "(Using SIGKILL)"
		    fi
		echo "Killed pid $p (surplus JVM thread)"
		fi
	    done
	fi
	;;
esac
}


removeSurplusJVMs

exit 0
