#!/bin/sh
#  $Id: objectmanager.sh,v 1.42 2005/06/20 19:15:57 peterc Exp $
#  Copyright (C) 1998-2005 Tarantella, Inc.
#  This software code contains proprietary information
#  and should be treated as confidential.
#
#  Component: Object Manager
#  Author: mikebe

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


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

# check first if all we want is the help
for o in "$@"; do
    case "$o" in
        --help )
	    echo "$lf_usage" 1>&2
	    exit 1 ;;
	-J*)
	    ;;
	--verbose )
	    ;;
        "" )
	    ;;
	*)
	    echo "$lf_badarg $o" 1>&2
	    echo "$l_shortusage" 1>&2
	    exit 1 ;;
    esac
done

# 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


# 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


# Source the Java development environment variables:

# Set port numbers. Start by sourcing info/ports.properties.
if [ -r $top/var/info/ports.properties ]; then
	. $top/var/info/ports.properties
fi

# Use these as defaults for config
tarantella_config_array_externalport=${externalport:-3144}
tarantella_config_array_port=${peerport:-5427}
tarantella_config_array_secureport=${secureport:-5307}
#also include proxiedhttpsurl for firewall traversal
tarantella_config_server_proxiedhttpsurl=${proxiedhttpsurl:-""}
tarantella_config_array_privilegeduser=${privilegeduser:-""}
tarantella_config_array_privilegedgroup=${privilegedgroup:-""}
#also include privileged username for web authentication
tarantella_config_array_webserveruser=${webserveruser:-""}
# Include web auth key refresh
tarantella_config_login_webauth_refreshkeyonrestart=${refreshkeyonrestart:-""}

#Include attribute to tell ttawebtop whether to be verbose or not
tarantella_config_server_cgiverbose=${cgiverbose:-""}

#Include attribute used to modify the archive names
tarantella_config_server_archivemodifier=${archivemodifier:-""}

#Attribute for cgi-bin to tell client to bootstrap from
tarantella_config_server_cgibin_bootscript=${bootscript:-""}

#Attribute passed to client so it knows the route to the server.
tarantella_config_array_netservice_proxy_routes=${routes:-""}

#Attribute passed to client so it knows the correct external name of the server
tarantella_config_server_netservice_proxy_externalnames=${externalnames:-""}

#SHould we use ssl on peer connections? Admin tools need to know
tarantella_config_security_peerssl_enabled=${peerssl:-"0"}

# Use the bootstrap.properties file if we can.
if [ -r $top/var/serverconfig/global/bootstrap.properties ]; then
	eval `sed -e '
		s/^#.*//
		:dotloop
		s/^\([^=]*\)\.\([^=]*=.*\)$/\1_\2/
		tdotloop
		s/ /\\\\ /g' $top/var/serverconfig/global/bootstrap.properties`
fi

# Set the values in the expected variables.
externalport=$tarantella_config_array_externalport
secureport=$tarantella_config_array_secureport
peerport=$tarantella_config_array_port

# Set DNS names. Use the bootstrap.properties file if we can.
if [ -r $top/var/serverconfig/local/bootstrap.properties ]; then
	eval `sed -e '
		s/^#.*//
		:dotloop
		s/^\([^=]*\)\.\([^=]*=.*\)$/\1_\2/
		tdotloop
		s/ /\\\\ /g' $top/var/serverconfig/local/bootstrap.properties`
fi

# We need defaults if the properties file is unreadable or corrupt.
peerhost=${tarantella_config_server_dns_peer:-`$top/bin/bin/ttahostname`}
externalhost="${tarantella_config_server_dns_external:-$peerhost}"
auxhost="$peerhost"

# Get the value of proxiedhttpsurl/cgiverbose/archivemodifier/bootscript from 
# server.properties
if [ -r $top/var/serverconfig/local/server.properties ]; then
        eval `sed -e '
                s/^#.*//
                :dotloop
                s/^\([^=]*\)\.\([^=]*=.*\)$/\1_\2/
                tdotloop
                s/ /\\\\ /g' $top/var/serverconfig/local/server.properties`
fi

# Get the properties from array.properties
if [ -r $top/var/serverconfig/global/array.properties ]; then
        eval `sed -e '
                s/^#.*//
                :dotloop
                s/^\([^=]*\)\.\([^=]*=.*\)$/\1_\2/
                tdotloop
                s/ /\\\\ /g' $top/var/serverconfig/global/array.properties`
fi

# Get web auth properties
if [ -r $top/var/serverconfig/global/webauth.properties ]; then
        eval `sed -e '
                s/^#.*//
                :dotloop
                s/^\([^=]*\)\.\([^=]*=.*\)$/\1_\2/
                tdotloop
                s/ /\\\\ /g' $top/var/serverconfig/global/webauth.properties`
fi

# Get peerssl properties
if [ -r $top/var/serverconfig/global/security.properties ]; then
        eval `sed -e '
                s/^#.*//
                :dotloop
                s/^\([^=]*\)\.\([^=]*=.*\)$/\1_\2/
                tdotloop
                s/ /\\\\ /g' $top/var/serverconfig/global/security.properties`
fi

proxiedhttpsurl=$tarantella_config_server_proxiedhttpsurl
privilegeduser=$tarantella_config_array_privilegeduser
privilegedgroup=$tarantella_config_array_privilegedgroup
webauthrefresh=$tarantella_config_login_webauth_refreshkeyonrestart
cgiverbose=$tarantella_config_server_cgiverbose
archivemodifier=$tarantella_config_server_archivemodifier
bootscript=$tarantella_config_server_cgibin_bootscript
routes=$tarantella_config_array_netservice_proxy_routes
externalnames=$tarantella_config_server_netservice_proxy_externalnames
peerssl=$tarantella_config_security_peerssl_enabled
webserveruser=$tarantella_config_array_webserveruser

INSTALLDIR=$top
export INSTALLDIR

[ -f $top/var/javaenv ] && . $top/var/javaenv

[ -f $top/bin/scripts/javaprops ] && . $top/bin/scripts/javaprops

# (This sets the $jrecommand to be an appropriate jre.)

## Get the uid and gid of the privileged user so that if we need to write
## to disk when we are running as root then we can.
uid=-1
gid=-1
wsid=-1
GetPrivUsrGrpIds()
{
    cat $top/var/serverconfig/global/array.properties 2>/dev/null | awk -F= \
        'BEGIN { u="ttasys"; wu="ttaserv"; g="ttaserv" }
        $1 == "tarantella.config.array.privilegeduser" { u = $2 }
        $1 == "tarantella.config.array.webserveruser" { wu = $2 }
        $1 == "tarantella.config.array.privilegedgroup" { g = $2 }
        END { print u " " wu " " g }'
}
_privusrgrp=`GetPrivUsrGrpIds`
_user=`expr "$_privusrgrp" : '\([^ ]*\) .*'`
_webservusr=`expr "$_privusrgrp" : '.* \([^ ]*\) .*'`
_grp=`expr "$_privusrgrp" : '.* \([^ ]*\)$'`
_userid=`grep "^$_user:" /etc/passwd`
_webservuseid=`grep "^$_webservusr:" /etc/passwd`
_groupid=`grep "^$_grp:" /etc/group`
uid=`expr "$_userid" : '[^:]*:[^:]*:\([^:]*\).*'`
wsid=`expr "$_webservuseid" : '[^:]*:[^:]*:\([^:]*\).*'`
gid=`expr "$_groupid" : '[^:]*:[^:]*:\([^:]*\):.*'`



JAVA_SYSTEM_PROPERTIES="${JAVA_SYSTEM_PROPERTIES}
-Djava.naming.tfn.flavour=autoAdmin
-Djava.naming.diskens.indexing=true
-Dsun.java2d.pmoffscreen=true
-Dtarantella.config.security.peerssl.enabled=$peerssl
-Djava.naming.tfn.diskds.uid=$uid
-Djava.naming.tfn.diskds.gid=$gid"

JAVA_SYSTEM_PROPERTIES="${JAVA_SYSTEM_PROPERTIES}
-Djava.net.preferIPv4Stack=true"


# need to get hold of session token stuff but can't give it just as arg - would
# appear in process list
# Find out if the session token has been set...
if [ -n "$TTA_SESSION_TOKEN" ]; then
    # Check to make sure it's a file and not the actual token...
    if [ ! -r "$TTA_SESSION_TOKEN" ]; then
        # The file doesn't exist so write $TTA_SESSION_TOKEN to a tmp file...
        TOKENFILE=${TMPDIR:-/tmp}/TTA_SESSION_TOKEN.$$

        # Check to see if the file exists by accident...
        if [ -w $TOKENFILE ]; then
            rm -f $TOKENFILE
        fi

        # Write the token to a new file...
        (umask 177; echo "$TTA_SESSION_TOKEN" > $TOKENFILE)

        # Switch the token var to point to the file...
        TTA_SESSION_TOKEN=$TOKENFILE
    fi

    # Do some stuff for the TCL bit...
    TCLTOKENARG="SESSIONTOKENFILE=$TTA_SESSION_TOKEN"
else
    # Do some stuff for the TCL bit...
    TCLTOKENARG="SESSIONTOKENFILE="
fi


# Trick swing to think it is running under KWM, which gives us the best
# size+position behaviour under CWM.
case "$MACHINEARCH" in
i3li*|ppli*) $top/bin/bin/ttaxset -setatom KWM_RUNNING ;;
esac



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
}



u="`LANG=C LC_ALL=C id | sed 's/.*uid=\([0-9][0-9]*\).*/\1/'`"
if [ "$u" = "0" ]
then
    removeSurplusJVMs &
fi



execcommand=exec
case "$SCOARCH" in 
	i3li*|ppli*)
		execcommand=""
	;;
esac


##########################################################
# We can specify the following parameters...
#
# PEERHOST - the host we should connect to (if running on a machine in array).
# PEERPORT - the port number to connect to on PEERHOST.
# EXTERNALHOST - the host clients connect to.
# EXTERNALPORT - the port clients connect to on EXTERNALHOST.
# SECUREPORT - secure server port clients connect to on EXTERNALHOST.
# INSTALLDIR - the install directory.
# CONTEXTSTART - name to resolve enterprise to (".../_ens")
#
###########################################################

IMEPID=""

##ifdef ja-jp
# == # Start IM client process for Japanese input mode
# == case "$MACHINEARCH" in
# == i3li*)  [ -x /usr/bin/X11/kinput2 ] && {
# ==                 XMODIFIERS=@im=kinput2
# ==                 export XMODIFIERS
# ==                 /usr/bin/X11/kinput2 -canna &
# ==                 IMEPID=$!
# ==         } ;;
# == spso*)  [ $OM -a $OM = "Yes" ] && \
# ==         grep "Solaris" $INSTALLDIR/etc/data/keymaps/xjapanese.txt >/dev/null && \
# ==         [ -x /usr/dt/config/Xsession.d/0020.dtims ] && {\
# ==             DTSTARTIMS=True /usr/dt/config/Xsession.d/0020.dtims &
# ==             IMEPID=$!
# ==         };;
# == axo1*)  [ $OM -a $OM = "Yes" ] && \
# ==         grep "Tru64" $INSTALLDIR/etc/data/keymaps/xjapanese.txt >/dev/null && \
# ==         [ -x /usr/dt/config/Xsession.d/0020.dtims ] && {\
# ==             DTSTARTIMS=True /usr/dt/config/Xsession.d/0020.dtims &
# ==             IMEPID=$!  
# ==         };;
# == pahp*)  DTSTARTIMS=True /usr/dt/config/Xsession.d/0020.dtims ;;
# == esac
##endif

##ifdef ko-kr
# == if [ -x /usr/bin/ami ]; then 
# ==     LANG=ko_KR
# ==     LC_ALL=ko_KR
# ==     XMODIFIERS=@im=Ami
# ==     export LANG LC_ALL XMODIFIERS
# ==     /usr/bin/ami &
# ==     IMEPID=$!
# ==     sleep 1
# == elif [ -x /usr/dt/config/Xsession.d/0020.dtims ]; then
# ==     LANG=ko
# ==     LC_ALL=ko
# ==     export LANG LC_ALL
# ==     DTSTARTIMS=True /usr/dt/config/Xsession.d/0020.dtims &
# ==     IMEPID=$!
# ==     sleep 1
# == fi
##endif

###################################
##  Add by bestasp James Zhang   ##
##################################

##ifdef zh-cn
# == if test $LANG=="zh-cn" || test $LANG=="zh_CN" || test $LANG=="zh_CN.GBK" \
# ==        || test $LANG=="zh_CN.GB2312" || test $LANG=="zh.GBK" ;  then
# == 
# ==        case "$MACHINEARCH" in
# ==        i3li*)
# ==                   LC_ALL=$LANG
# ==                   export LC_ALL
# ==                   if [ -e /usr/bin/chinput ]; then
# ==                      XMODIFIERS=@im=Chinput
# ==                      export XMODIFIERS
# ==                      /usr/bin/chinput &
# ==                      IMEPID=$!
# ==                      sleep 1
# ==                   elif [ -e /usr/local/rfinput/bin/rfinput ]; then
# ==                      XMODIFIERS=@im=rfinput
# ==                      export XMODIFIERS
# ==                      /usr/local/rfinput/bin/rfinput &
# ==                      IMEPID=$!
# ==                      sleep 1
# ==                   fi
# ==                ;;
# ==        spso*)
# ==                [ $OM -a $OM = "Yes" ] && \
# ==                grep "Solaris" $INSTALLDIR/etc/data/keymaps/xchinese.txt >/dev/null && \
# ==                [ -x /usr/dt/config/Xsession.d/0020.dtims ] && {\
# ==                        DTSTARTIMS=True /usr/dt/config/Xsession.d/0020.dtims &
# ==                        IMEPID=$!
# ==                };;
# ==        axo1*)
# ==                [ $OM -a $OM = "Yes" ] && \
# ==                grep "Tru64" $INSTALLDIR/etc/data/keymaps/xchinese.txt >/dev/null && \
# ==                [ -x /usr/dt/config/Xsession.d/0020.dtims ] && {\
# ==                        DTSTARTIMS=True /usr/dt/config/Xsession.d/0020.dtims &
# ==                        IMEPID=$!
# ==                };;
# == 
# ==        esac
# == fi
##endif

J2D_PIXMAPS=server 
export J2D_PIXMAPS

#  We use $execcommand, so that on Linux, the JVM is not a direct child of 
#  init. This is so that surplus jvm threads can be identified correctly.
$execcommand $jrecommand $RUNTIME_ARGS -classpath $CLASSPATH -mx54m -ms24m -noclassgc $RUNTIME_ARGS $JAVA_SYSTEM_PROPERTIES $TTA_USER_CMD com.sco.tta.admin.gui.RunAdminGui --objectmanager $TCLTOKENARG CONTEXTSTART=.../_ens/ INSTALLDIR=${TTAINSTDIR} PEERHOST=${peerhost} EXTERNALHOST=${externalhost} EXTERNALPORT=${externalport} SECUREPORT=${secureport} PEERPORT=${peerport} TFNUSER=.../_user/root "$@"

# kill the IME if started.
[ ! -z "$IMEPID" ] && kill -9 $IMEPID

# Will try to remove the token file if it is allowed to.
rm -f $TOKENFILE



