#!/bin/sh
#  $Id: start.sh,v 1.76 2005/08/12 13:39:59 clarep Exp $
#  Copyright (C) 1998-2005 Tarantella, Inc.
#  This software code contains proprietary information
#  and should be treated as confidential.
#
#  Component: Wrapper script for the TTA 2.n Java server
#  Author: andrewsh
#
#  Syntax: start [--debug]

if [ -f $TTAMSG/common -a -f $TTAMSG/tta_start ]; then
  . $TTAMSG/common
  . $TTAMSG/tta_start
else
  echo "Unable to open message file: $TTAMSG/tta_start"
  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 0;;
	--browser|--browser=*) ;;
	--debug-httpd|--debug-httpd=*) ;;
	--file|--file=*) ;;
	--firststart|--firststart=*) ;;
	--gui|--gui=*) ;;
	--monitor|--monitor=*) ;;
	--newkey|--newkey=*) ;;
	--no-bind-test|--no-bind-test=*) ;;
	--no-daemon|--no-daemon=*) ;;
	--pvc-file|--pvc-file=*) ;;
	--pvc-gui|--pvc-gui=*) ;;
	--pvc-text|--pvc-text=*) ;;
	--restart|--restart=*) ;;
	--sesstest|--sesstest=*) ;;
	--sesstest-ratio|--sesstest-ratio=*) ;;
	--sesstest-regprintjobs|--sesstest-regprintjobs=*) ;;
	--sesstest-regwebtopupdates|--sesstest-regwebtopupdates=*) ;;
	--sesstest-sessions|--sesstest-sessions=*) ;;
	--sesstest-sleep|--sesstest-sleep=*) ;;
	--setup|--setup=*) ;;
	--shell|--shell=*) ;;
	--text|--text=*) ;;
	--trace|--trace=*) ;;
	--trace-ldap|--trace-ldap=*) ;;
	--verbose|--verbose=*) ;;
	--*) echo "$l_invalid_arg1$o$l_invalid_arg2" 1>&2; echo "$lf_short_usage" 1>&2; exit 1;;
    esac
done


echo $tta_start_starting

# 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


# 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


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

# Check for the configure file, if it exists the server needs
# to be configured before starting up
if [ -f $installdir/var/configure ]; then
  INSTDIR=$installdir export INSTDIR
  $installdir/bin/scripts/postinstall
  # If postinstall returns an error exit now
  rVal=$?
  [ $rVal -ne 0 ] && exit
fi


GetPrivUsrGrp()
{
    cat $installdir/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=`GetPrivUsrGrp`
privusr=`expr "$_privusrgrp" : '\([^ ]*\) .*'`
webservusr=`expr "$_privusrgrp" : '.* \([^ ]*\) .*'`
privgrp=`expr "$_privusrgrp" : '.* \([^ ]*\)$'`

MkTtaDir()
{
    _newdirs="" _pflag=""
    case "$1" in
    -p) _pflag="-p"; shift
    esac
    for _d in "$@"; do
	while [ -n "$_d" ]; do
	    [ -d "$_d" ] && break
	    _newdirs="$_newdirs $_d"
	    _d=`dirname $_d`
	done
    done
    mkdir $_pflag "$@"
    [ -n "$_newdirs" ] && { chgrp $privgrp $_newdirs 2>/dev/null; chown $privusr $_newdirs 2>/dev/null; }
}


# Create writeable log files for the lp/lpr interface script
#
(
    cd ${installdir}/var/log
    :>>print.log; :>>print_error.log; chmod 600 print.log print_error.log 2>/dev/null
)

# Pick a suitable JServer start script:
if [ "$1" = "-debug" -o "$1" = "--debug" ]
then
  jserver_script=$installdir/var/info/debugjserverstart
  # We'll be starting the JServer ourselves but need
  # to keep the ttaauxserv happy when it launches us:
  echo "#!/bin/sh\n# Dummy JServer wrapper\nwhile true; do sleep 30000; done" > $jserver_script
  chmod a+x $jserver_script
else
  jserver_script=$installdir/bin/scripts/jserverstart
fi

# 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


# Set the PATH so that it will find an auxserver in the new TTA2 tree:
TTAAUXSERV=$installdir/bin/bin/ttaauxserv
[ ! -x "$TTAAUXSERV" ] && TTAAUXSERV=`echo $installdir/bin/????????/ttaauxserv`
[ ! -x "$TTAAUXSERV" ] && exit 1
TTABINDIR=`expr $TTAAUXSERV : '\(.*\)/ttaauxserv$'`

cwd=`pwd`
cd $TTABINDIR
TTABINDIR=`pwd`
cd $cwd

PATH=${PATH}:${TTABINDIR}
export PATH

# The server wants a umask of 077
umask 077

# Write port number files (auxport asadport secureport) etc
# This is for the benefit of the ttawebtop CGI-bin and for
# when we are in "--debug" mode, etc.
# The JServer start script gets them from its command line.
PORTSFILE="$installdir/var/info/ports.properties"

now=`date`
cat >"$PORTSFILE" <<EOF
# These port numbers reflect the state of the server when
# it was last run. This file is created each time the
# server starts, and reflects the server configuration
# which is not available to CGI-BIN programs.
# $now
externalport=$externalport
secureport=$secureport
peerport=$peerport
externalhost=$externalhost
proxiedhttpsurl=$proxiedhttpsurl
cgiverbose=$cgiverbose
archivemodifier=$archivemodifier
bootscript=$bootscript
routes=$routes
externalnames=$externalnames
EOF

# Make sure the ports file is world readable (for the benefit of CGI)
chmod 644 "$PORTSFILE"

# Create empty key.file with correct owner/group/permissions.
touch $installdir/var/info/key.file
chmod 640 $installdir/var/info/key.file
MkTtaDir $installdir/var/info 2>/dev/null
chown $privusr $installdir/var/info/key.file 2> /dev/null
chgrp $privgrp $installdir/var/info/key.file 2> /dev/null

# Create a secure key for web login
if [ -n "$webserveruser" ] && [ -n "$privilegeduser" ] && [ -n "$webauthrefresh" ] && [ "$webauthrefresh" -eq 1 ]; then
  touch $installdir/var/info/weblogin.key
  chmod 600 $installdir/var/info/weblogin.key
  MkTtaDir $installdir/var/info 2>/dev/null
  chown $privusr $installdir/var/info/weblogin.key 2> /dev/null
  chgrp $privgrp $installdir/var/info/weblogin.key 2> /dev/null
  $installdir/bin/bin/ttarandom --keysize 16 > $installdir/var/info/weblogin.key

  # Stamp the ttawlogin binary with the key
  $installdir/bin/bin/ttawloginstomp --file $installdir/var/docroot/cgi-bin/secure/ttawlogin.cgi --username $webserveruser --stomp < $installdir/var/info/weblogin.key
fi

if [ -n "$privilegeduser" ]; then
   # Stomp the ttasshhelper binary with the path and uid
   $installdir/bin/bin/ttasshhelperstomp --file $installdir/bin/bin/ttasshhelper --username $privilegeduser
fi

# Touch the start file with the current time.
date >$installdir/var/info/started

# touch lockfile so we'll get shutdown
[ -d /var/lock/subsys ] && touch /var/lock/subsys/Tarantella

# As the proxy now runs as a daemon, we don't know it's PID until it forks,
# thus we make it write the PID to the appropriate file

# Write the PID to a file, so we know to kill it when we do tarantella stop:
#echo $$" " >> $installdir/var/info/auxserver.pid

#echo "PID is " $$

# Now start ttastart to start the ttaauxserv as a proxy, which will start
# the AuxServer proper and then invoke our JServer wrapper script
# ($jserver_script). (Note that the auxport is dynamically allocated by
# ttaauxserv and communicated to the JServer via the $jserver_script.)

#for arg in "$@"; do
#    if [ "$arg" = "--setup" ]; then
#		exec  $jserver_script $peerport $externalport $secureport 0 $peerhost $externalhost $auxhost "$@"
#    fi
#done



#
# File ./var/info/proxiedhttpsurl
#


# if file `$installdir/var/info/proxiedhttpsurl` exists and 
#    its size > 0 and 
#    it's got possible URL spec and port number (any letter or number)
# then
#    read file contents (proxied https url port; https port) and
#    execute `ttastart`
# 	
#if [ -s $installdir/var/info/proxiedhttpsurl ]; then
#	set -- `cat $installdir/var/info/proxiedhttpsurl`
#	if [ ! -z "`grep [0-9a-zA-Z] $installdir/var/info/proxiedhttpsurl`" ]; then
#	 	proxiedhttpsurl=$1
#		echo "Proxied https URL: $proxiedhttpsurl"
#	else 
#		echo "No proxied https url specified (1st entry)"
#	fi
#		
#	if [ ! -z "`echo $2 | grep [0-9]`" ]; then
#		httpsport=$2
#		echo "https port: $httpsport"
#	else
#		echo "No https port specified (2nd entry)"
#	fi
#
#	exec ${TTABINDIR}/ttastart $installdir/var/log +proxy  $jserver_script $peerport $peerhost $externalport $externalhost $secureport $auxhost $proxiedhttpsurl $httpsport "$@"
#else
#	echo "No proxy"
#	exec ${TTABINDIR}/ttastart $installdir/var/log +proxy  $jserver_script $peerport $peerhost $externalport $externalhost $secureport $auxhost "$@"
#fi
#
#

# Before we launch the proxy server we need to determine the minimum 
# number of file descriptors required to run Tarantella.
# This value is a a tunable server config property
tuningfile=$installdir/var/serverconfig/local/tuning.properties
eval `sed '
s/^#.*//
:dotloop
s/^\([^=]*\)\.\([^=]*=.*\)$/\1_\2/
tdotloop
s/ /\\\\ /g' $tuningfile`

tuningval=${tarantella_config_tuning_maxfds:-4096}
if [ $tuningval -lt 4096 ];then
   tuningval=4096
fi

## we aren't going to start cdm unless it's enabled
cdmfile=$installdir/var/serverconfig/global/cdm.properties
eval `sed '
s/^#.*//
:dotloop
s/^\([^=]*\)\.\([^=]*=.*\)$/\1_\2/
tdotloop
s/ /\\\\ /g' $cdmfile`

cdmval=${tarantella_config_cdm_enabled:-0}

case "$SCOARCH" in
i3sc*) ;;
*)
 # We do not want to run out of file descriptors. 4096 per process is 
 # the minimum acceptable value.
 n_fds=`ulimit -n`
 case $n_fds in
   unlimited ) n_fds=$tuningval;;
   [0-9]* );;
   * ) n_fds=0;; #???
 esac
 [  $n_fds -lt $tuningval ] && ulimit -SHn $tuningval
esac

##ifdef ja-jp
# == # JAPAN
# == case "$SCOARCH" in
# == spso*) LANG=ja LC_ALL=ja DISABLE_FPE_MESSAGE=Yes; export LANG LC_ALL DISABLE_FPE_MESSAGE ;;
# == i3li*) LANG=ja_JP LC_ALL=ja_JP; export LANG LC_ALL ;;
# == rsai*) LANG=ja_JP LC_MESSAGES=C; export LANG LC_MESSAGES ;;
# == axo1*) LANG=ja_JP LC_ALL=ja_JP DISABLE_FPE_MESSAGE=Yes; export LANG LC_ALL DISABLE_FPE_MESSAGE ;;
# == pahp*) LANG=ja_JP.eucJP LC_ALL=ja_JP.eucJP; export LANG LC_ALL ;;
# == *)
# == esac
##endif
##ifdef ko-kr
# == # KOREA
# == case "$SCOARCH" in
# == spso*) LANG=ko LC_ALL=ko DISABLE_FPE_MESSAGE=Yes; export LANG LC_ALL DISABLE_FPE_MESSAGE ;;
# == i3li*) LANG=ko_KR; export LANG LC_ALL ;;
# == rsai*) LANG=ko_KR LC_MESSAGES=C; export LANG LC_MESSAGES ;;
# == axo1*) LANG=ko_KR LC_ALL=ko_KR DISABLE_FPE_MESSAGE=Yes; export LANG LC_ALL DISABLE_FPE_MESSAGE ;;
# == pahp*) LANG=ko_KR LC_ALL=ko_KR; export LANG LC_ALL ;;
# == *)
# == esac
##endif
##ifdef zh-cn
# == # CHINA
# == case "$SCOARCH" in
# == spso*) LANG=zh LC_ALL=zh DISABLE_FPE_MESSAGE=Yes; export LANG LC_ALL DISABLE_FPE_MESSAGE ;;
# == i3li*) LANG=zh_CN LC_ALL=zh_CN; export LANG LC_ALL ;;
# == rsai*) LANG=zh_CN LC_MESSAGES=C; export LANG LC_MESSAGES ;;
# == axo1*) LANG=zh_CN LC_ALL=zh_CN DISABLE_FPE_MESSAGE=Yes; export LANG LC_ALL DISABLE_FPE_MESSAGE ;;
# == pahp*) LANG=zh_CN LC_ALL=zh_CN; export LANG LC_ALL ;;
# == *)
# == esac
##endif

# Set LD_LIBRARY_PATH for Unixware to make use of PAM libraries.
case "$SCOARCH" in
i3un*) if [ -z "$LD_LIBRARY_PATH" ] ; then LD_LIBRARY_PATH=/usr/dt/lib
       else LD_LIBRARY_PATH=/usr/dt/lib:$LD_LIBRARY_PATH
       fi
       export LD_LIBRARY_PATH
esac

# Find the host properties file
HostProps=`grep -li "tarantella.config.host.dns.peer=${peerhost}" ${installdir}/var/serverconfig/global/*.properties`

# Sort out file ownership
:>>${installdir}/var/info/auxserver.pid; chmod ugo+r ${installdir}/var/info/auxserver.pid
:>>${installdir}/var/log/stderrout.log; chmod 600 ${installdir}/var/log/stderrout.log
find ${installdir}/var \( ! -group $privgrp \) -print | xargs chgrp $privgrp 2>/dev/null
find ${installdir}/var \( ! -user  $privusr \) -print | xargs chown $privusr 2>/dev/null

# now we can run the server
# list of properties file includes the host.properties file
${TTABINDIR}/ttastart "INSTALLDIR=$installdir" "PEERHOST=$peerhost" $installdir/var/serverconfig/global/bootstrap.properties $installdir/var/serverconfig/global/array.properties $installdir/var/serverconfig/global/cdm.properties $installdir/var/serverconfig/local/*.properties ${HostProps} $jserver_script "$@"

tta_exit_code=$?

case "$tta_exit_code" in 
  0)  # success
    ;;
  12) # Log file error
    echo "$tta_start_log_file_error"
    exit $tta_exit_code
    ;;
  13) # Unlicensed
    # this is logged as a fatal error, so no need to print out anything here.
    exit $tta_exit_code
    ;;
  14) # server already started
    echo "$tta_start_already_running"
    exit $tta_exit_code
    ;;
  *)  # unknown
    exit $tta_exit_code
    ;;
esac

# successfully started
echo $tta_start_successful

## the local disk access may want starting now
if [ "$tarantella_config_cdm_enabled" = 1 -a -x $TTADIR/bin/scripts/start_cdm ]; then
  $TTADIR/bin/scripts/start_cdm --quiet
  cdm_exit_code=$?
  case "$cdm_exit_code" in
  0|1|2)
    # a valid return code
    ;;
  *)
    # an unexpected error
    echo "$tta_start_cdm_failed"
    exit 255
    ;;
  esac
fi

# enable TTA printer, unless printing services have been stopped
if [ -n "${HostProps}" ] &&\
   [ -n "`grep 'tarantella.config.host.localprinting.status=2' ${HostProps}`" ]
then
    :
else
    ${TTADIR}/bin/scripts/lpenable >/dev/null 2>&1
fi

# use the main server exit code
exit $tta_exit_code


