#!/bin/sh
#  $Id: info.sh,v 1.21.8.2 2006/03/27 15:01:12 barrie Exp $
#  Copyright (C) 2002-2005 Tarantella, Inc.
#  This software code contains proprietary information 
#  and should be treated as confidential.
#
#  Component: Tarantella info command
#  Author: chrisre
#
#  A non-productised script for generating output useful for dev and support.
#  Can be run standalone, or from the tarantella installation as
#  tarantella info.  Portions based on sysinfo.
#  
#  This script is not localised.
#

#  If you are going to distribute the output of this command, please commit
#  this file or change the following line to identify it:
RCS_ID='$Id: info.sh,v 1.21.8.2 2006/03/27 15:01:12 barrie Exp $'

# Temporary fix.
PRODUCT_SHORT_NAME="Secure Global Desktop"

####################################
#
# Parse arguments
#
invocationArgs="$0 $@"

msg_help="
tarantella info:

  Produces information about your $PRODUCT_SHORT_NAME installation intended
  to assist Tarantella Support.

  Mode options:

   --general ( default )   : Outputs general information about 
                             $PRODUCT_SHORT_NAME  
   
   --diff                  : Generate a summary of any customisations or  
                             changes compared to a default installation.

   --check                 : Performs some checks against the state of 
                             your $PRODUCT_SHORT_NAME server.
   
   --user <username>
   --jserver
   --ens
   --packages
   --pid <pid>
   --platform
   --print
   --network               : Generate specific information about the requested
                             system.

   --all                   : Generate a report containing a most of the 
                             above modes.

   --summary | -s [--html] : A short output [in HTML]

   --configdump            : Synonym for --cmd configDump --stdout --quiet
                             to emulate configdump script

   --cmd <function>        : Run the named function from the info script.

   --startdetailed         : Start a detailed analysis of the system. Your
                             server will run slower until info --stopdetailed 
                             is run.

   --stopdetailed          : Stop a detailed analysis of the system.

  Common options:

   --verbose               : Give detail of what is happening at each step.

   --quiet                 : do not give any details of what commands are 
                             being run
                         
   --stdout                : output to stdout instead of generating a tar file.
                             Use with --quiet to get only the output of 
                             commands run.

   --help                  : This help

  All modes except --summary will generate a gzipped tar file to be given to 
  Tarantella Support.  --summary writes to stdout.

Environment variables:
  The following environment variables may be set:

  TTAINSTDIR : $PRODUCT_SHORT_NAME installation directory (may not be needed)
  TTAINFODIR : directory to output information to; prevents prompt for filename
  TI_NOGZIP  : if set, do not gzip the output. 
  TI_TIMEOUT : Timeout in seconds to use when running commands. (default 60s)
               (0 disables timeouts completely)
  TI_USERNAME,
  TI_PASSWORD: username, password of administrator (for debug-httpd output)

"
if [ ! -z "$TTALANG" -a -f $TTAINSTDIR/bin/scripts/$TTALANG/info ] ; then
    . $TTAINSTDIR/bin/scripts/$TTALANG/info
fi

unset MODE_arg
unset QUIETARG
unset VERBOSE
unset MODES
unset PREMODES
unset STDOUTONLY
# basic and the following are used if --all is specified:
preModes="stopdetailed"
allModes="general check diff jserver print ens network packages platform user"
# other modes you can specify:
specificModes="pid"
for a in "$@" ; do 
    if [ ! -z "$MODE_arg" ] ; then
        eval "${MODE_arg}Arg=\"\$${MODE_arg}Arg $a\""
        unset MODE_arg
    else 
      case "$a" in
        --help | -h* )
            echo "$msg_help"
            exit 0
        ;;
        --user | --pid ) 
                MODE_arg=`echo $a | cut -d- -f 3 `
        ;;
        -c | --cmd ) 
            MODE_arg=cmd
            MODES=cmd
            STDOUTONLY=t
        ;;
        --configdump ) 
            MODES=cmd
            STDOUTONLY=t
            QUIETARG=y
            cmdArg=configDump
        ;;
        --startdetailed )
            MODES=startdetailed
            STDOUTONLY=t
            QUIETARG=y
        ;;
        --verbose )
                VERBOSE=y
        ;;
        -q | --quiet ) 
            QUIETARG=y
        ;;
        --summary )
            MODES=summary
            STDOUTONLY=t
        ;;
        -s | --stdout ) 
            STDOUTONLY=t
        ;;
        --all ) 
            MODES="basic $allModes"
        ;;
      esac
    fi
done

if [ -z "$MODES" ] ; then
    MODES=""
    for m in $preModes basic $allModes $specificModes ; do
        for a in $@ --basic ; do
            case $a in
                --$m )
                    MODES="$MODES $m"
                    break
                    ;;
            esac
        done
    done
    if [ "$MODES" = "basic " ]; then
        MODES="basic general"
    fi
fi



#########################################################################
#
# Set up some variables:
#

N=""
C=""
if echo -n | grep n > /dev/null
then
  C="\c"
else
  N="-n"
fi
case "$MACHINEARCH" in
i3li*|ppli*) N="$N -e" ;;
esac
_ss_headlines="--------------------------------------------------------------------------"


# make ps accept the -o option on HP-UX:
UNIX95=t
export UNIX95



givenTTAINFODIR=$TTAINFODIR

if [ -z "$TTAINFODIR" ] ; then
    TTAINFODIR=/tmp
fi

if [ -z "$TI_TIMEOUT" ] ; then
    TI_TIMEOUT=60
fi


msg_prev='prev'
msg_next='next'
msg_top='top'
msg_title="$PRODUCT_SHORT_NAME information report for "
msg_intro='You can find the output of each command in the tar file in the directory <a href="cmds">cmds</a>.  There is also a selection of file in the <a href="files">files</a> directory.<br>This was created by '
msg_firstcommand='First command output'
msg_commandoutput='Output of command: '
msg_commandoutputs='Outputs of commands:'
msg_summary='Summary:'
msg_invocation='Invocation arguments are: '
msg_arch='Architecture is: '
msg_time='Time and date is: '
msg_uptime='This hosts uptime: '
msg_ttaver="$PRODUCT_SHORT_NAME version is:"
msg_aixoslevel='Oslevel -r reports:'
msg_contents='Contents:'
msg_rawout='Raw output'
msg_file='File '
msg_dir='Directory '
msg_exitcode='Exit code: '
msg_timedout='Timed out \(${TI_TIMEOUT}s\)'
msg_firstlast505='First 50 and last 5 lines:'
msg_ellipsis='...'
msg_moderunning='tarantella info running in $mode $arg mode'
msg_nosinglejserverpid='Could not find a single JServer PID'
msg_pidfilebutnojserver='jserver.pid file contains $pid, but could not find that process'
msg_nohttpclient='Could not find a HTTP client. Please install either lynx or wget and ensure it is on the PATH, or live without the debug-httpd feature.'
msg_foundlistener='Found listener on port $port \($desc\)'
msg_notfoundlistener='Cannot find listener on port $port \($desc\)'
msg_tspavailbutoff='TSP is installed but security is disabled; will not check TSP port'
msg_notauxserverchilds='The following processes appear to be orphaned: $notAuxServerChildProcs'
msg_procsnotfound='Could not find processes for the following binaries:'
msg_processesareorphans="Processes $orphanPids are orphans and may be $PRODUCT_SHORT_NAME processes"
msg_foundprocs='Found processes (ignoring protocol engines): '
msg_ttapkgnotfound='Could not find a tta package'
msg_nocpuhogs='No processes appear to be using more than ${ratio}% CPU'
msg_cpuhog='Process $p \($process\) is using more than ${ratio}% CPU'
msg_allfilesok='All files correct.'
msg_ignoredbadchecksums="
Ignored the following files with bad checksums only, as they are modified
during $PRODUCT_SHORT_NAME installation:
"
msg_ignoredbadchecksumsizes="
Ignored the following files with bad checksums and sizes, as they are
modified during $PRODUCT_SHORT_NAME installation:
"
msg_generatedfile='Generated gzipped tar file $optarfile.gz'
msg_generatedfilenotzipped='Generated tar file $optarfile'
msg_morethanoneprimary='tarantella status is reporting more than one primary'
msg_noprimary='tarantella status is not reporting any host as the primary'
msg_toomanylocalhostobjs='There appears to be more than one local tarantella host object.'
msg_morethanoneprimaryinfiles="There appears to be more than one primary host object (This really shouldn't happen)"
msg_noprimaryfile="The primary host object has not been replicated yet (or is missing)"
msg_excesshostfile='Global config contains a host object that is not in the array: $am. \(This should be removed by the server\)'
msg_infilesnotstatus='The following hosts are in the array according to global config but are not listed by tarantella status: $inFilesNotInStatus'
msg_instatusnotfiles='The following hosts are in the array according to status but are not according to global config: $inStatusNotInFiles'
msg_arraytopologyok='Array topology appears consistent.\<br\>Primary=$primary\<br\>Secondaries=$secondaries'
msg_inconsistentmaster='Global config and status disagree who the master is. Status says $primary, global config says $fprimary'
msg_cdmoncdmrunningnoserving='CDM is switched on and is running but there is no listener on port $cdmPort/TCP'
msg_cdmoncdmrunningserving='CDM is switched on, is running, and is listening on port $cdmPort/TCP'
msg_cdmoncdmrunningnonaming='CDM is switched on, is running, is configured to use WINS but is not listening on port 137/UDP'
msg_cdmoncdmrunningnaming='CDM WINS listening on port 137/UDP'
msg_cdmpnaminginusenotbycdm='Note: port 137/UDP is in use but not by CDM. If this is samba, this may interfere with CDM.'
msg_cdmoncdmnotrunningnoportsopen='CDM is switched on but there is no ttacdmd process.  There are no listeners on ports 137/UDP and $cdmPort/TCP'
msg_cdmoncdmnotrunningportsopen='CDM is switched on but there is no ttacdmd process.  There are listeners on ports 137/UDP and/or $cdmPort/TCP.  Check this is not another windows file sharing server such as Samba or VisionFS.'
msg_cdmoffcdmrunning='CDM is switched off but there is a ttacdmd process running'
msg_cdmoffcdmnotrunningportsopen='CDM is switched off and is not running. Something else is listening on ports 137/UDP and $cdmPort/TCP.  You can probably not use CDM on this server.'
msg_cdmoffcdmnotrunningnoportsopen='CDM is switched off and is not running. There are no listeners on ports 137/UDP or $cdmPort/TCP.'

msg_detailedstarted='Started output in detailed mode.

To stop detailed mode, run:

tarantella info --stopdetailed $statusFile
'
msg_missingdetailfile='You must supply the name of a detailed status file, which is probably of the 
form $TTAINFODIR/info.detailed.<number>. (I could found $count such files)'

msg_poutputfile='Output tar filename [$fileName.gz]? '
msg_cannotfindnslookup='Warning: Cannot find an nslookup or host program on the PATH.'
msg_cannotdeterminehostnameofdev='Unable to find a hostname for interface $dev. Either this script doesn'\''t understand your $nslookup program, or DNS is not correctly configured.'
msg_ens_table_header='<table border=1 cellspacing=0 cellpadding=2><tr><th>Base 64 encoded</th><th>Plaintext</th></tr>'
msg_prefs_table_header='<table border=1 cellspace=0 cellpadding=2><tr><th>Encoded name</th><th>Plaintext name</th></tr>'
msg_ens_nob64conv='<b>Could not find a base 64 encoder program. No ENS name dump</b>'
msg_pwherettainstalled="Where is $PRODUCT_SHORT_NAME installed? (Hint: set TTAINSTDIR to tell me)
(Or run from tarantella command line as tarantella info ...)"
msg_errnottainstallation="Error: Cannot find $PRODUCT_SHORT_NAME installation in directory $TTAINSTDIR"
msg_padminusername="
tarantella info needs an administrator username and password to gather
the debug-httpd information.  No permanent changes will be made to your
system. 
(You can set these in the environment as TI_USERNAME and TI_PASSWORD)

What is the administrator's username [root]? "
msg_padminpassword="
What is the administrator's password (will not be echoed)? " 

msg_pstablehead='<table border=1 cellspacing=0 cellpadding=2><tr><td>Binary name</td><td>Threads</td><td>Pid</td><td>ps output</td></tr>'
msg_nohttpdoutput='
This command produced no output.  If you think you may have supplied
incorrect authentication credentials, would like you to try again? (Y/N) '


# Get the latest package name for package pkgname (e.g. tta -> tta.3 )
getLatestPkg() {
pkgname=$1
if pkginfo $pkgname.\* 2>/dev/null >/dev/null ; then
    package=`pkginfo $pkgname.\* | awk '{ print $2 }'`
    echo $package
    return 0
fi         
return 1
}



if [ -z "$TTAINSTDIR" ] ; then
    pkg=`getLatestPkg tta`
    pkginst=`pkgparam $pkg INSTDIR`
    echo $N "$msg_pwherettainstalled [$pkginst] " $C
    read TTAINSTDIR
    if [ -z "$TTAINSTDIR" ]; then
        TTAINSTDIR=$pkginst
    fi
fi

if [ ! -x $TTAINSTDIR/bin/bin/ttahostname -o ! -x $TTAINSTDIR/bin/bin/ttatcl -o ! -x $TTAINSTDIR/bin/tarantella ] ; then
    eval echo $msg_errnottainstallation
    exit 1
fi

# make our tcl not look for /tools.cid (duh!)
TCLX_LIBRARY=$TTAINSTDIR/bin/lib/tcl7.5/
TCL_LIBRARY=$TTAINSTDIR/bin/lib/tcl7.5/

export TCLX_LIBRARY
export TCL_LIBRARY

if [ ! -z "$TTALANG" -a -f $TTAINSTDIR/bin/scripts/$TTALANG/info ] ; then
    . $TTAINSTDIR/bin/scripts/$TTALANG/info
fi

isOnPath() {
# which returns 0 even if the cmd doesn't exist on spso. Astounding.
[ `which $1 2>&1 | wc -w ` = "1" ]
}

unset nslookup
if isOnPath nslookup ; then
    if nslookup 127.0.0.1 2>&1 | grep 'nslookup is deprecated' >/dev/null ; then
        nslookup=""
    else
        nslookup=nslookup
    fi
fi

if [ -z "$nslookup" ] ;then
    if isOnPath host ; then
        nslookup=host
    else
        nslookup=nslookup
        echo "$msg_cannotfindnslookup"
    fi
fi

GetPrivUsrGrp()
{
    cat $TTAINSTDIR/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; }
}


PATH=$TTAINSTDIR/bin:$TTAINSTDIR/bin/bin:$PATH
export PATH
arch=`tarantella version | grep 'Architecture code' | cut -d' ' -f 3`
opbuilddir=$TTAINFODIR/ttainfo.tmp.$$
opcmds=$opbuilddir/cmds
MkTtaDir $opbuilddir $opcmds
opshead1=$opbuilddir/summary.head1.html
opshead2=$opbuilddir/summary.head2.html
opsbody=$opbuilddir/summary.body.html
tmpFile=$opbuilddir/tmp
tmpErr=$opbuilddir/tmpErr
cmdNumber=1
unset TAROUTPUT
cfgList=$opbuilddir/cmds/tarantella_config_list

echo '\\' | wc -c  > $tmpFile.bs
numbs=`cat $tmpFile.bs`
if [ $numbs = 3 ] ; then
    bs='\'
else
    bs='\\'
fi


###################################################################
#
# set up some utility sh-functions:
#

# print message if in verbose mode
verboseEcho() {
if [ ! -z "$VERBOSE" ] ; then 
    if [ "$1" = "-n" ] ; then
        shift
        echo $N $@ $C
    else
        echo $@
    fi
fi
}



# wait for up to $TI_TIMEOUT for some pid to complete.  Writes to status file
# on timeout.
# (based on code from sysinfo)
Timeout() { 
# $1 is pid. 
# $2 is error status file.

pid=$1
status=$2

timeLeft=$TI_TIMEOUT 

while kill -0 $pid 2>/dev/null ; do
    if [ $timeLeft -gt 0 -o "$TI_TIMEOUT" = 0 ] ; then
        sleep 1
        timeLeft=`expr $timeLeft - 1`
    else
        break
    fi
done

if kill -0 $pid 2>/dev/null ; then
    # it's still running. Kill it.
    kill -1 $pid 2>/dev/null
    sleep 1
    kill -15 $pid 2>/dev/null
    sleep 1
    kill -9 $pid 2>/dev/null
    sleep 1
    eval echo $msg_timedout > $status
fi

}

entify() {
sed -e 's,&,\&amp;,g; s,<,\&lt;,g; s,>,\&gt;,g; s,",\&quot;,g'
}

# Replace < > " & with their escaped form.
htmlify() { 
# $1: if -n, then strip newlines
if [ "$1" = "-n" ] ;then
    entify | awk '{ printf $0 }'
else
    entify
fi
}

# execute a command.
# stdout and stderr go to $1.
# time it out as appropriate
executeCmd() {
opf=$1
shift
# run it:

echo $N $C > $opf
unset tailpid
if [ -z "$TAROUTPUT" ] ; then
    tail -f $opf &
    tailpid=$!
fi

(  eval $@ > $opf 2>&1 ; echo $? > $tmpErr )  &
rcpid=$!
Timeout $rcpid $tmpErr
verboseEcho " Completed."
if [ ! -z "$tailpid" ] ; then
    kill $tailpid
    sleep 1
fi
}


# Run a command. Log its output. Add link and output to summary. 
# Time it out if takes too long.
#
runCmd() {
# $@ - command line to run. May be prefixed with Options, which are:
# -q : quiet
# -d <display name> : pretend the command is display name
# -s: provide a description.
# -h: It is HTML output (do not htmlify)

# parse args:
unset QUIET
unset desc
unset displayName
htmlifycmd=htmlify

while [ "$1" = "-q" -o "$1" = "-d" -o "$1" = "-s" -o "$1" = "-h" ] ; do
    if [ "$1" = "-q" ] ; then 
        QUIET=y
        shift
    fi
    if [ "$1" = "-h" ] ; then
        htmlifycmd=cat
        shift
    fi
    if [ "$1" = "-d" ] ; then
        displayName=$2
        shift ; shift
    fi
    if [ "$1" = "-s" ] ; then
        desc="$2"
        shift ; shift
    fi
done

[ -z "$displayName" ] && displayName="$@"
verboseEcho -n "Running $@ ($displayName) ..."
nonshifty=`echo $displayName | sed -e's/[]\`/? >&$^!"'"'"'#%()<*\\]/_/g'`
opFileName=$opcmds/$nonshifty

rm -f $opFileName $tmpFile $tmpErr 2>/dev/null >/dev/null

if [ -z "$TAROUTPUT" ] ; then 
    if [ -z "$QUIETARG" ] ; then
        cat <<EOF
-----------------------------------
`[ ! -z "$desc" ] && echo "$desc - "`
$msg_commandoutput $displayName

EOF
    fi
fi

executeCmd $opFileName $@


# output info:
[ -z "$QUIET" -a ! -z "$TAROUTPUT" ] && (
    cat <<EOF
<li><a href="#cmd$cmdNumber">
    `[ ! -z "$desc" ] && echo "$desc - "`
    `echo "$displayName" | htmlify -n`
</a> (<a href="cmds/$nonshifty">Raw output</a>)</li>
EOF
    ) >> $opshead2

[ -z "$QUIET" -a ! -z "$TAROUTPUT" ] && (
    cat <<EOF 
<h4><a name="cmd${cmdNumber}">
    `[ ! -z "$desc" ] && echo "$desc - "`
    `echo "$displayName" | htmlify`
</a></h4>
<div align="right"><table>
<tr><td><a href="#top">$msg_top</a></td>
<td><a href="#cmd`expr $cmdNumber - 1`">$msg_prev</a></td>
<td><a href="#cmd`expr $cmdNumber + 1`">$msg_next</a></td>
</tr></table></div>
$msg_exitcode <b>`cat $tmpErr`</b>
<a href="cmds/$nonshifty">$msg_rawout</a>
EOF
    # do not cut long stuff in html.
    nls=`cat $opFileName | fold -w 160 | wc -l | awk '{ print $1 }'`
    if [ "$nls" -gt 60 -a "$htmlifycmd" = "htmlify" ]; then
        echo "<br>$msg_firstlast505"
        echo "<pre>"
        cat $opFileName | fold -w 160 | head -50 | $htmlifycmd
        echo $msg_ellipsis
        cat $opFileName | fold -w 160 | tail -5 | $htmlifycmd
    else
        echo "<pre>"
        cat $opFileName | fold -w 160 | $htmlifycmd
    fi
    echo "</pre>"

    ) >> $opsbody

if [ -z "$TAROUTPUT" ] ; then 
    if [ -z "$QUIETARG" ] ; then
        echo ; echo "Exit code: `cat $tmpErr`"
    fi
fi

rm -f $tmpFile $tmpErr 2>/dev/null >/dev/null
cmdNumber=`expr $cmdNumber + 1`
}

# Log information (short) to summary file:
logToFile() {
[ ! -z "$TAROUTPUT" ] && (
cat <<EOF
<li>$@</li>
EOF
) >> $opshead1
[ -z "$TAROUTPUT" ] && echo "$@"
}

# Add a header to HTML file:
addHeader() {
# $1 $2 - may be -h <num>:  level
# rest - header text
level=3
if [ "$1" = "-h" ]; then
    shift
    level=$1
    shift
fi
higherlevel=`expr $level - 1`
if [ ! -z "$TAROUTPUT" ] ; then (
    cat <<EOF
    </ul>
    <h$level>$@</h$level>
    <ul>
EOF
    ) >> $opshead2
    (
    cat <<EOF
    <h$higherlevel>$@</h$higherlevel>
EOF
    ) >> $opsbody
else
    if [ -z "$QUIETARG" ]; then 
        cat <<EOF
-----------------------------------------------------------------

$@

-----------------------------------------------------------------
EOF
    fi
fi
}




# add a file to the tar ball, and a link to the summary.
addFile() {
# $1 - src root
# $2 - src relative to $1
# $3 - target dir, defaults to "files"

[ -z "$TAROUTPUT" ] && return 1

unset file_quiet
if [ "$1" = "-q" ]; then
    file_quiet=t
    shift
fi
srcRoot=$1
srcRel=$2
target=$3
if [ -z "$target" ]; then
    target="files"
fi
# create dirs if needed:
[ ! -d $opbuilddir/$target/`dirname $srcRel` ] && MkTtaDir -p $opbuilddir/$target/`dirname $srcRel`


cp $srcRoot/$srcRel $opbuilddir/$target/`dirname $srcRel`
# add link
[ -z "$file_quiet" ] && echo "<li>File <a href=\"$target/$srcRel\">$srcRel</a></li>" >> $opshead2

}

# Add a whole directory to tarball.
addDirectory() {
# $1 - src root
# $2 - src relative to $1
# $3 - target

cd $1 || return $?
verboseEcho "Adding directory $1/$2"
target=files
[ ! -z "$3" ] && target=$3
echo "<li>Directory <a href=\"$target/$2\">$2</a></li>" >> $opshead2

for f in `find  $2 -type f` ; do
    addFile -q $1 $f $3
done

}

# get the size of a file
fileSize() {
ls -l $1 | awk '{ print $5 }'
}

# call before partailCatPost
partialCatPre() { 
# $1 file to partially cat
# outputs info to pass to partialCatPost
fileSize $1
}

# Displays the new output to a log file.  Must supply the output of
# partialCatPre.  Will wait for file size to become stable before outputting
# anything.
# For example, use as:
# preInfo=`partialCatPre logfile`
# <do some action, which makes server write to logfile>
# partialCatPost $preInfo logfile
partialCatPost() {
# $1 output of partialCatPre
# $2 file to partially cat
size_pre=$1

currSize=$size_pre
oldSize=0
while [ "$currSize" != "$oldSize" ] ; do 
    sleep 3
    oldSize=$currSize
    currSize=`fileSize $2`
done


size_diff=`expr $currSize - $size_pre`
tail -${size_diff}c $2
}

# output a sorted bean properties file
# looks for and sorts javareferenceaddress values.
# (taken from configdump)
outputPropertiesFile () {
# $1 the properties file.
# $2 -v to include header and footer

hf="$2"

filterblanks="grep -v '^$'"
[ ! -z "$hf" ] && filterblanks="cat"

    # get the javareferenceaddress
    jRefAddress=`grep javareferenceaddress $1`    

    # remove unwanted stuff
    jRefAddress=`echo "$jRefAddress" | \
        sed -e 's|javareferenceaddress=||g
                s|\\\||g'`

    #Seperate the records and add numbers to array memebrs

    if [ ! -z "$jRefAddress" ] ; then


        jRefAddress=`echo $jRefAddress | \
            awk 'BEGIN {
                    beanName="'$1'"
                    RS="," 
                    FS="#"
                    lastName=""
                } {
                    if ( lastName != "" ) {
                        # If part of array print posistion
                        if( lastName == $3 || arrayCount > 1) {
                            print beanName"-"lastName"-"arrayCount"="lastValue lastExtra
                            arrayCount+=1
                        } else {
                            print beanName"-"lastName"="lastValue lastExtra
                        }
                        
                        # re-set array position if name has changed
                        if ( lastName != $3 ) {
                            arrayCount=1
                        }
                    }
                    lastName=$3
                    lastValue=$4
                    lastExtra=""

                    for ( i = 5; i < NF; i++ ){ 
                        lastExtra=lastExtra"#"$i
                    }

                } END {
                    # If part of array print position
                    if( arrayCount > 1 ) {
                        print beanName"-"lastName"-"arrayCount"="lastValue lastExtra
                    } else {
                        print beanName"-"lastName"="lastValue lastExtra
                    }
                }'`
    fi

    # Sort it and output it.
    [ ! -z "$hf" ] && echo "# Start of file `getRelativeDir`/$1"
    echo "$jRefAddress
`grep -v javareferenceaddress $1`" | grep -v "^#" | $filterblanks | sort -d
    [ ! -z "$hf" ] && echo "# End of file `getRelativeDir`/$1
"  
}

# shorten and deref a bean name as needed:
derefBean() {
# $1 - a bean name
# returns a bean filename, canonicalised
sname=`basename $1`
dir=$TTAINSTDIR/var/serverconfig/global/beans

file=$dir/$sname
class=`grep 'javaclassname=' $file | cut -d'=' -f 2`
if [ "$class" = "javax.naming.LinkRef" ] ; then
    # need to dereference it
    derefBean `outputPropertiesFile $file |grep LinkAddress | cut -d'=' -f 2`
else
    echo $file
fi
}

isBeanOn() {
# $1 - canonicalised bean filename
beanName=`outputPropertiesFile $1 | grep '.-name=' | cut -d'=' -f 2 | sed -e's/.*\.//g'`
enabled=`grep -i tarantella.config.components.$beanName $TTAINSTDIR/var/serverconfig/global/components.properties | cut -d'=' -f 2`
if [ -z "$enabled" ] ;then 
    return 0
else
    if [ "$enabled" = 1 ] ; then
        return 0
    fi
fi
return 1
}

# Process lines describing what to do:
processLines() {
while read line ; do
    numwords=`echo "$line" | wc -w`
    if [ "$numwords" -gt 0 ] ; then
        case "$line" in 
            '###'* ) 
                addHeader -h 4 `echo "$line" | cut -b 4-`
                ;;
            '##'* )
                logToFile `echo "$line" | cut -b 3-`
                ;;
            *'#'* )
                cmd=`echo "$line" | cut -d'#' -f 1`
                desc=`echo "$line" | cut -d'#' -f 2`
                runCmd -s "$desc" $cmd
                ;;
            * )
                runCmd $line
                ;;
        esac
    fi
done
}


#########################################################################
#
#  Now some bigger utility functions that make up the modes
#

# list external helper binaries
getExternalHelperBinaries() {
svcs=`derefBean services.properties`
listSvcs=`outputPropertiesFile $svcs | grep defaultServices | cut -d'=' -f 2`
for s in $listSvcs ; do
    svcname=`derefBean $s`
    isOn=0
    case $svcname in 
        *SecurIDService* )
            [ -f /etc/sdace.txt ] &&  isOn=1
        ;;
        * )
            isBeanOn $svcname && isOn=1
        ;;
    esac
    if [ "$isOn" = "1" ]; then 
        if grep com.sco.tta.server.services.IExternalService $svcname >/dev/null ; then
            outputPropertiesFile $svcname | grep -i binaryName | cut -d'=' -f 2
        fi
    fi
done
}
        

# output a thread dump of the server
jserverThreadDump() {
# get the pid of the JServer:
cd $TTAINSTDIR/var/info
realpids=""
nopids=0
pidsfound=0
for i in `cat jserver.pid` ; do
    pidsfound=`expr $pidsfound + 1`
    if kill -0 $i 2>/dev/null ; then
        pid=$i
        nopids=`expr $nopids + 1`
    fi
done
if [ "$nopids" != "$pidsfound" -a "$nopids" = "0" ] ; then
    logToFile "<b>`eval echo $msg_pidfilebutnojserver`</b>"
fi

if [ "$nopids" != "1" ]; then
    logToFile "<b>$msg_nosinglejserverpid</b>"
else
    cd $TTAINSTDIR/var/log
    # generate a thread dump:
    stdeoPre=`partialCatPre stderrout.log`
    if kill -0 $pid 2>/dev/null ; then
        kill -QUIT $pid 
        runCmd -d "JServer thread dump (pid $pid)" partialCatPost $stdeoPre stderrout.log
        case "$arch" in
            i3un* ) 
                if [ -x /usr/ccs/bin/debug ] ; then
                    echo 'ps ; stack -p all ; map' | /usr/ccs/bin/debug -ic $pid > $tmpFile
                    runCmd "Native ps, stack -p all, map debug output of jserver pid $pid" cat $tmpFile
                fi
                ;;
        esac
    fi
fi
}

# dump the output of the debug-httpd
jserverDebugHttpd() {

unset cmdLine
unset cmdLineDisp

for i in wget lynx ; do
if isOnPath $i ; then
    cmdLine=$i
    break
fi
done

if [ ! -z "$cmdLine" ] ; then 
    verboseEcho -n "Switching debug httpd on ..."

    [ -f $cfgList ] || runCmd tarantella config list
    oldDebug=`$TTAINSTDIR/bin/tarantella config list --tarantella-config-server-debug-httpd | cut -d' ' -f 2`
    peerPort=`grep port-peer $cfgList | cut -d' ' -f 2`

    if [ "$oldDebug" = "0" ] ; then
        tarantella config edit --tarantella-config-server-debug-httpd 1 >/dev/null
    fi

    verboseEcho " done"
    nAttempts=0
    while :; do
	if [ -z "$TI_USERNAME" -o -z "$TI_PASSWORD" ]; then
	    echo $N "$msg_padminusername"$C
	    read username
	    if [ -z "$username" ] ; then username=root
	    fi
	    echo $N $msg_padminpassword$C
	    stty -echo ; read password ; stty echo
	    echo
	else
	    username="$TI_USERNAME"
	    password="$TI_PASSWORD"
	fi
	url=http://`ttahostname`:$peerPort/
	
	case $cmdLine in 
	    lynx* )
		cmdLine="lynx -dump -source $url -auth $username:\"\$password\""
		cmdLineDisp="lynx -dump $url"
		;;
	    wget* )
		cmdLine="wget --http-user $username --http-passwd \"\$password\" -o/dev/null -O- $url"
		cmdLineDisp="wget $url"
		;;
	esac

	export password
	runCmd -d "$cmdLineDisp" $cmdLine
	unset password
	nAttempts=`expr ${nAttempts} + 1`

	sleep 10	# give the output file a chance to have something in it
	[ -s "${opFileName}" -o "${nAttempts}" -ge 3 -o \( -n "$TI_USERNAME" -a -n "$TI_PASSWORD" \) ] && break
	echo $N "${msg_nohttpdoutput}$C"
	read tryagain
	case "${tryagain}" in y|Y|'') ;; *) break ;; esac

    done

    if [ "$oldDebug" = "0" ] ; then
        verboseEcho -n "Restoring debug-httpd ..."
        tarantella config edit --tarantella-config-server-debug-httpd $oldDebug >/dev/null
        verboseEcho " done"
    fi
else 
    echo $msg_nohttpclient
    logToFile "<b>$msg_nohttpclient</b>"
fi

}

# compare files in templates directory to those in var/serverconfig
diffConfig() {
beans=""
if [ -d $TTAINSTDIR/etc/templates/serverresources/serverconfig/global/beans ]; then
    beans=global/beans
fi
# diff all files in config:
for d in local global $beans ; do 
    srcdir=$TTAINSTDIR/var/serverconfig/$d
    templatedir=$TTAINSTDIR/etc/templates/serverresources/serverconfig/$d
    cd $templatedir
    for i in *.properties ; do 
        verboseEcho "Checking $d/$i"
        if [ ! -z "`diffProps $templatedir/$i $srcdir/$i l`" ] ; then
            runCmd -d "diffProps $d/$i" diffProps $templatedir/$i $srcdir/$i $d/`basename $i.properties` 
        fi
    done
done

# Special files, which do not have template copies. generate a temporary copy:
echo "tarantella.config.type=server
tarantella.config.array.secureport=5307
tarantella.config.array.port=5427
tarantella.config.array.externalport=3144
tarantella.config.name=arraybootstrap" > $tmpFile.bootstrap
hostname=`ttahostname`

echo "tarantella.config.host.master=$hostname
tarantella.config.host.load.power=0
tarantella.config.type=server
tarantella.config.host.tier2loadbalancing.weighting=100
tarantella.config.host.security.active=std
tarantella.config.host.serviceids=scottaxapplication,scottacharacterapplication,scottawindowsapplication
tarantella.config.host.load.cpuload=100
tarantella.config.name=host
tarantella.config.host.load.cpuloadref=0
tarantella.config.host.dns.peer=$hostname
tarantella.config.host.dns.external=$hostname
tarantella.config.host.localprinting.status=0
tarantella.config.host.acceptnewconnections=enabled" > $tmpFile.$hostname

# and then compare:
for i in bootstrap $hostname ; do 
    verboseEcho "Checking global/$i"
    dir=$TTAINSTDIR/var/serverconfig/global
    if [ ! -z "`diffProps $tmpFile.$i $dir/$i.properties l`" ] ; then
        runCmd -d "diffProps global/$i" diffProps $tmpFile.$i $dir/$i.properties global/$i 
    fi
done


}

# Check that there are servers listening on the right ports.
checkPeerAsadPorts() {
# Gather port numbers from config:
verboseEcho -n "Gathering config info ..."
[ -f $cfgList ] || runCmd tarantella config list
verboseEcho " done"
peerPort=`grep port-peer $cfgList | cut -d' ' -f 2`
extPort=`grep port-unencrypted $cfgList | cut -d' ' -f 2`
tspPort=`grep port-encrypted $cfgList | cut -d' ' -f 2`

peerPortDesc="Peer connections"
extPortDesc="External unencrypted connections"
tspPortDesc="External encrypted connections"

ports="peerPort extPort"
if [ -f $TTAINSTDIR/bin/scripts/security_start.tsh ]; then 
    if grep security-connectiontypes $cfgList | grep ssl 2>/dev/null >/dev/null ; then
        ports="$ports tspPort"
    else 
        logToFile $msg_tspavailbutoff
    fi
fi
    

# And check if they are listening:
unset wantNetstat
for pname in $ports ; do 
    port=`eval echo \\$$pname`
    desc=`eval echo \\$${pname}Desc`
    if checkIsListening $port ; then
        verboseEcho "Found server port ($port) for $desc. Good."
        logToFile "`eval echo $msg_foundlistener`"
    else
        logToFile "<b>`eval echo $msg_notfoundlistener`</b>" 
        wantNetstat=t
    fi
done

if [ ! -z "$wantNetstat" ]; then 
    runCmd netstat -a
    runCmd netstat -an
fi
}



# generate a list of differences between two property files, ignoring 
# comments, ordering and \ escaping.
diffProps() {
# $1 the original .properties file
# $2 the current .properties file
# $3 the short name of the file, used for display.

# I'd like to use diff, but diff -u isn't available on all platforms.

if [ ! -s $1 -o ! -s $2 ] ; then
    if [ ! -s $1 ] ; then
        if [ -s $2 ] ; then
            echo "Added property file $3"
            exit 1
        fi
    fi
    if [ ! -s $2 ] ; then
        echo "Removed property file $3"
    fi
fi
name=$3
if [ -z "$name" ] ; then
    name=`basename $2`
fi
rm -f $tmpFile.orig $tmpFile.new 2>/dev/null >/dev/null
cd `dirname $1`
outputPropertiesFile `basename $1` > $tmpFile.orig
cd `dirname $2`
outputPropertiesFile `basename $2` > $tmpFile.new

# tcl script:
echo '

# read in the files into old and new:
set oldfile [ lindex $argv 0 ]
set newfile [ lindex $argv 1 ]
set old [ split [ read_file $oldfile ] "\n" ]
set new [ split [ read_file $newfile ] "\n" ]

# search for removed or changed lines:
foreach l $old {
    if { $l != "" }  {
        if { [ lsearch -exact $new $l ] == -1 } {
            set key [ lindex [ split $l "=" ] 0 ]
            set value "[ crange $l [ expr [ clength $key ] + 1 ] end ]"
            set newIdx [ lsearch -glob $new "$key=*" ]
            if { $newIdx == -1 } {
                puts "'$name': Property removed:     $l"
            } else {
                set newline [ lindex $new $newIdx ]
                set newkey [ lindex [ split $newline "=" ] 0 ]
                set newvalue "[ crange $newline [ expr [ clength $newkey ] + 1 ] end ]"
                regsub -all "'$bs$bs$bs$bs'" "$newvalue" "" vnew
                regsub -all "'$bs$bs$bs$bs'" "$value" "" vold
                if { [ string compare "$vold" "$vnew" ] } {
                    puts "'$name': Property changed from $key=$vold to $vnew"
                }
            }
        }
    }
}

# search for added lines:
foreach l $new {
    set kv [ split $l "=" ] 
    if { [ lsearch -glob $old "[lindex $kv 0 ]*" ] == -1 } {
        puts "'$name': Property added: $l"
    }
}
' | ttatcl -- $tmpFile.orig $tmpFile.new

rm -f $tmpFile.orig $tmpFile.new 2>/dev/null >/dev/null

}


# see if anything is listening on some port
# (No guarantee it is the right process listening)
checkIsListening() {
# $1 - port number to be checked (assumed TCP)
# exits 0 if there is a server listening on the port.
# exits non-zero if not.

port=$1
if [ -z "$port" ] ; then
    return 1
fi
case $arch in 
    i3li*|ppli* )
        netstat --tcp -an |  grep LISTEN | awk '{ print $4 }' | grep ".*:${port}\$"> $tmpFile
    ;;
    spso*|i3so* )
        netstat -an -P tcp | grep LISTEN | awk '{ print $1 }' | grep ".*\.${port}\$" > $tmpFile
    ;;
    * )
        netstat -an  | grep LISTEN | grep $port > $tmpFile
    ;;
esac
test -s $tmpFile 
ret=$?
rm -f $tmpFile >/dev/null 2>/dev/null
return $ret
}


# see if anything is listening on some port
# (No guarantee it is the right process listening)
checkIsListeningUdp() {
# $1 - port number to be checked (assumed UDP)
# exits 0 if there is a server listening on the port.
# exits non-zero if not.

port=$1
if [ -z "$port" ] ; then
    return 1
fi
case $arch in 
    i3li*|ppli* )
        netstat --udp -an | awk '{ print $4 }' | grep ".*:${port}\$"> $tmpFile
    ;;
    spso*|i3so* )
        netstat -an -P udp | awk '{ print $1 }' | grep ".*\.${port}\$" > $tmpFile
    ;;
    * )
        netstat -an  | grep LISTEN | grep $port > $tmpFile
    ;;
esac
test -s $tmpFile 
ret=$?
rm -f $tmpFile >/dev/null 2>/dev/null
return $ret
}

# get a list of TTA pids.  We find all ttaauxserver binaries whose ppid is 1, 
# and list all processes that are children of them.
getTTAPids() {
# tcl script:
echo '
set auxservers {}
set respids {}
set pso [ split [ exec ps -e -o pid,ppid,args ] "\n" ]

foreach line [ lrange $pso 1 [ llength $pso ] ] {
    scan $line "%s %s %s" pid ppid cmd
    keylset ppids $pid $ppid
    keylset cmds  $pid $cmd
}


foreach p [ keylkeys cmds ] {
    set cmd [ keylget cmds $p ]
    switch -glob -- $cmd {
        *ttaauxserv* {
            lappend auxservers $p
            }
    }
}

if  { [ llength $auxservers ] == 0 } { 
    exit 1
}

proc addChildPids { pid } {
    global ppids
    global respids
    lappend respids $pid
    foreach p [ keylkeys ppids ] {
        set ppid [ keylget ppids $p ]
        if { $ppid == $pid } {
            addChildPids $p
        }
    }
}

foreach p $auxservers {
    if { [ keylget ppids $p ] == 1 } {
        addChildPids $p
    }
}

set pn 0

foreach p $respids {
    if { $pn > 0 } {
        puts -nonewline ,
    }
    incr pn
    puts -nonewline $p
}' | ttatcl

}



# generate a list of pids that are eating more than some percentage of CPU,
# by comparing CPU time before and after a sleep 25 call.
getCPUHogs() {
# $1 - the percentage of CPU to count as too much
level=$1
echo '
set cutoff [ expr '$level' / 4 ]
set pstime1 [ exec  ps -ed -o pid,time ]
sleep 25
set pstime2 [ exec  ps -ed -o pid,time ]

set list1 [ lrange [ split $pstime1 "\n" ] 2 end ]
set list2 [ lrange [ split $pstime2 "\n" ] 2 end ]

proc secs { timeStr } {
    set vals [ split $timeStr ":" ]
    set t 0
    foreach v $vals {
        scan $v "%d" n
        set t [ expr { $t * 60 + $n} ]
    }
    return $t
}
foreach l $list1 {
    scan $l "%s %s" pid time1
    set time2 ""
    foreach s $list2 {
        scan $s "%s %s" p2 t2
        if { $pid == $p2 } {
            set time2 $t2
            break
        }
    }
    if { $time2 != "" } {
        set time1 [ secs $time1 ]
        set time2 [ secs $time2 ]
        if {  ($time2 - $time1) > $cutoff } {
            puts $pid
        }
    }
}' | ttatcl --
}    


# utility for pkgchk_tta:
getPkgCheckForFile() {
# $1 file containing pkgchk output
# $2 filename we want pkgchk output for
# $3 file to output to

outFile=$3
unset gettingFile
rm -f $outFile 2>/dev/null >/dev/null
while read line ; do 
    case $line in
        *$2 )
            gettingFile=t
            ;;
        */* ) 
            unset gettingFile
            ;;
        * ) 
            if [ ! -z "$gettingFile" ] ; then
                echo "    $line" >> $outFile
            fi
    esac
done < $1

}

# check the contents of a package are up to date.
# displays a message if they are all OK.
# ignores files that are known to change.
pkgchk_tta() {

pkgchk $1 2> $tmpFile.pkgchk >/dev/null
unset files

if [ ! -s $tmpFile.pkgchk ] ; then
    echo $msg_allfilesok
    return 0
fi

files=`grep "/" < $tmpFile.pkgchk`

for f in $files ; do
    case $f in
        ERROR* )
            : # ignore it.
            ;;
        */bin/ttaauxserv | */var/docroot/cgi-bin/secure/ttawlogin.cgi ) 
            getPkgCheckForFile $tmpFile.pkgchk $f $tmpFile.out
            grep -v cksum < $tmpFile.out > $tmpFile.out2
            if [ -s $tmpFile.out2 ] ; then
                echo $f
                cat $tmpFile.out
            else
                ignoredBadChecksums="$ignoredBadChecksums $f"
            fi
            ;;
         */bin/lpr | */bin/lp | */bin/scripts/en-us/object_new_windowsapp.msg | */bin/scripts/lp_interface.en | */bin/scripts/print_move | */bin/scripts/printtestpage.en.sh | */var/docroot/cgi-bin/ttaprinter.cgi )
            # these are changed by the installation mechanism.
            # ::TODO:: pester toby to get these re-registered after fiddling with.
            ignoredFiles="$ignoredFiles $f"
            ;;
         * )
            echo $f
            getPkgCheckForFile $tmpFile.pkgchk $f $tmpFile.out
            cat $tmpFile.out
            ;;
    esac
done

if [ ! -z "$ignoredBadChecksums" ]; then 
    echo "$msg_ignoredbadchecksums"
    for f in $ignoredBadChecksums ; do echo $f ; done
fi
if [ ! -z "$ignoredFiles" ] ; then
    echo "$msg_ignoredbadchecksumsizes"
    for f in $ignoredFiles ; do echo $f ; done
fi

}




# Check if there are unknown files in the Tarantella directory.
# ignore files in known locations that are new.
pkgchk_newfiles() {
# $1 - list of packages to ignore files from.
pkg=`getLatestPkg tta`
TTADIR=`pkgparam $pkg INSTDIR`
follow=-follow
case $arch in 
    rsai* )
        follow=""
        ;;
esac
# tcl script:
echo '
set allfiles {}

# for each package, add the list of known files to allfiles:
foreach pkg $argv {
    set allfiles [ concat $allfiles [ split [ exec pkgchk -l $pkg | grep Pathname: | cut "-d " -f 2-  ] "\n" ] ] 
}

# search the disk for all files
set foundfiles [ lsort [ split [ exec find '$TTADIR' '$follow' -type f ] "\n" ] ]

# set all files on disk as unknown:
foreach f $foundfiles {
    set klist($f) 0
}

# set those in package db as known:
foreach f $allfiles {
    set klist($f) 1
}

# for each file on disk:
foreach f $foundfiles {
    # see if it is known (in package db):
    set i $klist($f)
    if { $i == 0 } then {
        # or a file that Tarantella creates
        switch -glob $f {
            */var/info/* -
            */var/preferences/* -
            */var/state/* -
            */var/serverconfig/* -
            */var/serverresources/* -
            */var/ens/* - 
            */var/backup/* -
            *.[0-9].[0-9][0-9].[0-9][0-9][0-9]* -
            */var/docroot/resources/* -
            */var/docroot/java/* -
            */etc/data/* -
            */etc/pkg/* -
            */var/spool/* -
            */var/print/* -
            */var/netlet/* -
            */var/pkginfo/* -
            */var/log/* -
            */var/javaenv -
            */var/pkginfo -
            */var/password/* { 
                          set i 1 
                        }

            */var/docroot/help/* {
                if [ regexp ".*/TOC_\[^/\]*" $f ] then {
                    set i 1
                }
            }
            */var/docroot/*  {
                if [ regexp ".*/var/docroot/\[^/\]*\$" $f ] then {
                    set i 1
                }
            }
        }
    }
    # No? Print the filename out
    if { $i == 0 } then {
        puts "New file $f"
    }
}' | ttatcl -- $@
}

# get network traffic stats
# (from ttamonitor)
networkStats() {
case "$arch" in

       i3li*|ppli* ) echo "TCP-bytes-tx: "`cat /proc/net/dev | grep eth0 | tr ':' ' ' | awk '{ print $2 }'` 
               echo "TCP-bytes-rx: "`cat /proc/net/dev | grep eth0 | tr ':' ' ' | awk '{ print $10 }'`
               ;;

       spso*|i3so* ) echo "TCP-bytes-tx: "`netstat -s -Ptcp | grep OutData | tr '=' ' ' | awk '{ print $4 }'`
               #gotta add these up
               IOR=`netstat -s -Ptcp | grep InInorder | tr '=' ' ' | awk '{ print $4 }'`
               OOR=`netstat -s -Ptcp | grep InUnorder | tr '=' ' ' | awk '{ print $4 }'`
               echo "TCP-bytes-rx: "`expr $IOR + $OOR`
               ;;

       * )     echo "TCP-bytes-tx: "`netstat -s -p tcp | grep "data packets" | grep -v retrans | tr '(' ' ' | awk '{ print $4 }'`
               #gotta add these up
               IOR=`netstat -s -p tcp | grep in-sequence | tr '(' ' ' | awk '{ print $3 }'`
               OOR=`netstat -s -p tcp | sed -e s/"out of order"/out-of-order/ | grep out-of-order | tr '(' ' ' | awk '{ print $4 }'` 
               echo "TCP-bytes-rx: "`expr $IOR + $OOR` 
               ;;
esac
}


# utility for checkTTAProcesses:
addPsOutput() {
# $1 - bin name
# $2 - pid
# $3 - output file.
bin=$1
pid=$2
ofile=$3
threads=""
if [ "$bin" = "JServer" ]; then
    case $arch in 
        spso*|i3so* ) 
            threads=`ps -p $pid -o nlwp | tail -1`
            ;;
        i3li*|ppli* )
            ppid=`ps -p $pid -o ppid | tail -1`
            parent=`ps -p $ppid -o args | egrep 'java|jre'`
            if [ ! -z "$parent" ]; then
                return 0
            fi
            # OK, this pid is the original.
            rm $tmpFile.pids 2>/dev/null >/dev/null
            echo $pid > $tmpFile.pids
            oldSz=0
            ps -e -o pid,ppid,args | egrep 'java|jre' > $tmpFile.psthreads
            while [ "`fileSize $tmpFile.pids`" != $oldSz ] ; do
                oldSz=`fileSize $tmpFile.pids`
                cat $tmpFile.psthreads | while read line ; do
                    set $line
                    if grep "^$2\$" $tmpFile.pids 2>/dev/null >/dev/null ; then
                        echo $1 >> $tmpFile.pids
                    fi
                done
                sort $tmpFile.pids | uniq > $tmpFile.pids2
                rm $tmpFile.pids
                mv $tmpFile.pids2 $tmpFile.pids
            done
            threads=`wc -l $tmpFile.pids | awk '{ print $1 }'`
            ;;
    esac
fi
echo "<tr><td><b>$bin</b></td><td>$threads</td><td>$2</td><td><code>`ps -f -p $pid | tail -1|sed -e's/ /\&nbsp;/g'`</code></td></tr>" >>  $ofile
}

# Check all TTA processes that should be are running
checkTTAProcesses() {
externalBinsF=$opbuilddir/cmds/getExternalHelperBinaries
[ -f $externalBinsF ] || runCmd getExternalHelperBinaries

ttapidsf=$opbuilddir/cmds/getTTAPids
[ -f $ttapidsf ] || runCmd getTTAPids

ttapids=`cat $ttapidsf`
unset gotJserver
echo > $tmpFile.cmds
if [ ! -z "$ttapids" ] ;then
    echo "$msg_pstablehead" > $tmpFile.html.pre
    ps -p $ttapids -o pid,args | while read line ; do
        set $line
        c=$2
        case $c in 
            COMMAND )
                : # ignore it; it's the header
                ;;
            *java* | *jre* ) 
                if [ -z "$gotJserver" ] ; then
                    echo jserver >> $tmpFile.cmds
                    gotJserver=t
                fi
                addPsOutput JServer $1 $tmpFile.html
                ;;
            *ttaxpe* | *ttatpe* | *ttappe* )
                : # ignore them.
                ;;
            * )
                echo $c $3 $4 >> $tmpFile.cmds
                addPsOutput `basename $c` $1 $tmpFile.html
                ;;
        esac
    done
fi

cmds=`cat $tmpFile.cmds`

verboseEcho "Found processes $cmds as children of ttaauxserv (good)"

for c in `cat $opbuilddir/cmds/getExternalHelperBinaries` jserver ttaauxserv ttaprintfifo  ; do
    echo $cmds | grep "$c" >/dev/null || nonTTAProcs="$nonTTAProcs $c"
done

verboseEcho "Could not find $nonTTAProcs"

ps -ed -o pid,args > $tmpFile.ps

echo "$msg_pstablehead" > $tmpFile.missingProcs

for c in $nonTTAProcs ; do
    # maybe it's not a child of ttaauxserv?
    pid=`grep "$c" $tmpFile.ps 2>/dev/null | awk ' { print $1 }'`
    if [ ! -z "$pid" ] ; then
        notAuxServerChildProcs="$notAuxServerChildProcs $c (Pid(s) $pid)"
        for p in $pid ; do
            addPsOutput $c $p $tmpFile.missingProcs
        done
    else
        missingProcs="$missingProcs $c"
    fi
done

verboseEcho "$missingProcs are missing (probably bad)"
verboseEcho "$notAuxServerChildProcs are not children of the auxserver"


if [ ! -z "$notAuxServerChildProcs" ] ; then
    logToFile "<b>`eval echo $msg_notauxserverchilds`</b><br>`cat $tmpFile.missingProcs`</table>"
fi

if [ ! -z "$missingProcs" ] ; then 
    unset mProcsList
    for p in $missingProcs ; do
        mProcsList="$mProcsList <li>$p</li>"
    done
    logToFile "<b>$msg_procsnotfound<ul>$mProcsList</ul></b>"
fi

if [ ! -z "$cmds" ] ; then
    sort < $tmpFile.html >> $tmpFile.html.pre
    echo "</table>">> $tmpFile.html.pre
    
    logToFile "$msg_foundprocs<br>`cat $tmpFile.html.pre`"
fi
rm $tmpFile.html* 2>/dev/null

}

# look for any orphaned processes that may be TTA-related
checkTTAOrphans() {
rm -f $tmpFile.orphans 2>/dev/null >/dev/null

echo $msg_pstablehead > $tmpFile.orphan.html
echo > $tmpFile.orphan.pids

ps -ed -o pid,ppid,args > $tmpFile.ps
cat $tmpFile.ps | while read line ; do
    set $line
    if [ "$2" = "1" ]; then
        case $3 in
            *ttaauxserv | *ttacdmd )
                : # ignore it.
                ;;
            *tta* | *tarantella* )
                binary=$3
                case $3 in 
                    *java* | *jre* )
                       binary=JServer
                    ;;
                esac
                echo $1 >> $tmpFile.orphan.pids
                addPsOutput $binary $1 $tmpFile.orphan.html
                ;;
        esac
    fi
done

orphanpids=`cat $tmpFile.orphan.pids`

if [ ! -z "$orphanPids" ] ; then
    logToFile "<b>`eval echo $msg_precessesareorphans ` </b><br>$msg_pstablehead`cat $tmpFile.orphan.html`</table>"
fi
}

   
cleanUp() {
rm -rf $opbuilddir 2>/dev/null >/dev/null
sleep 1
rm -rf $opbuilddir 2>/dev/null >/dev/null
exit 0
}

# check the array topology is coherent
checkArrayTopology() {
statusF=$opbuilddir/cmds/tarantella_status
[ ! -f $statusF ] && runCmd tarantella status

cat $statusF | grep ' - ' > $tmpFile.status-hosts

unset primary
unset secondaries
echo > $tmpFile.primary
echo > $tmpFile.secondaries
unset fprimary
unset fsecondaries
# parse the status output:
while read line ; do 
    host=`echo "$line" | cut -d' ' -f 2 | tr A-Z a-z`
    type=`expr "$line" :  '.*(\(.*\))'`
    case $type in 
        primary ) 
            if [ ! -z "$primary" ]; then
                logToFile "<b>$msg_morethanoneprimary</b>"
            else
                echo $host >> $tmpFile.primary
            fi
            ;;
        secondary )
            echo $host >> $tmpFile.secondaries
            ;;
    esac
done < $tmpFile.status-hosts

for p in `cat $tmpFile.primary` ; do
    primary=$p
done
secondaries=`cat $tmpFile.secondaries`

[ -z "$primary" ] && logToFile "<b>$msg_noprimary</b>"

cd $TTAINSTDIR/var/serverconfig/global
lhname=`ttahostname | tr 'A-Z' 'a-z'`


unset lhostf
unset ffgotprimary
for f in `grep -l -i "tarantella.config.host.dns.peer=$lhname" *.properties` ; do
    if [ ! -z "$lhostf" ]; then
        logToFile "<b>$msg_toomanylocalhostobjs</b>"
    fi
    lhostf=$f
done

flprimary=`grep tarantella.config.host.master $lhostf | cut -d'=' -f 2 | tr A-Z a-z`

for am in `grep -l -i "tarantella.config.host.master=$flprimary" *.properties` ; do
    ffmaster=`grep tarantella.config.host.master $am | cut -d'=' -f 2 | tr A-Z a-z` 
    ffhost=`grep tarantella.config.host.dns.peer $am | cut -d'=' -f 2 | tr A-Z a-z`
    if [ "$ffmaster" = "$ffhost"  ] ; then
        # is a master
        if [ ! -z "$fprimary" ] ; then
            logToFile "<b>$msg_morethanoneprimaryinfiles</b>"
        else
            fprimary=$ffhost
        fi
    else
        # is a secondary
        fsecondaries="$fsecondaries $ffhost"
    fi
done

if [ -z "$fprimary" ]; then
    logToFile "<b>$msg_noprimaryfile</b>"
fi

if [ ! "$primary" = "$fprimary" ]; then
    logToFile "<b>`eval echo $msg_inconsistentmaster`</b>"
fi

for am in `grep -l -i "tarantella.config.host.master" *.properties` ; do
    ffhost=`grep tarantella.config.host.dns.peer $am | cut -d'=' -f 2 | tr A-Z a-z`
    unset isInArray
    for h in $fsecondaries ; do
        if [ "$h" = "$ffhost" ]; then
            isInArray=true
        fi
    done
    if [ -z "isInArray" ] ;then
        logToFile "<b>`eval echo $msg_excesshostfile`</b>"
    fi
done


# list any in one but not the other:

unset inStatusNotInFiles
unset inFilesNotInStatus
for am in $secondaries ; do
    unset inFiles
    for fam in $fsecondaries ; do
        if [ "$am" = "$fam" ]; then
            inFiles=true
        fi
    done
    if [ -z "$inFiles" ]; then
        inStatusNotInFiles="$inStatusNotInFiles $am"
    fi
done

for fam in $fsecondaries ; do
    unset inStatus
    for am in $secondaries ; do
        if [ "$am" = "$fam" ]; then
            inStatus=true
        fi
    done
    if [ -z "$inStatus" ]; then
        inFilesNotInStatus="$inStatusNotInFiles $am"
    fi
done        

# if either status or config is missing a primary, we'll have logged it by now.
    
if [ ! -z "$inFilesNotInStatus" ] ; then
    logToFile "<b>`eval echo $msg_infilesnotstatus`</b>"
fi

if [ ! -z "$inStatusNotInFiles" ] ; then
    logToFile "<b>`eval echo $msg_instatusnotfiles`</b>"
fi


if [ ! -z "$primary" -a ! -z "$fprimary" -a "$primary" = "$fprimary" -a -z "$inFilesNotInStatus" -a -z "$inStatusNotFiles" ]; then
    logToFile "`eval echo $msg_arraytopologyok`"
fi


}         


checkCDMStatus() {
# get config list if not done already:
[ -f $cfgList ] || runCmd tarantella config list
verboseEcho -n "Checking CDM status ... "
cdmEnabled=`grep '^array-cdm:' $cfgList | cut -d' ' -f 2`
cdmWins=`grep '^array-cdm-wins:' $cfgList | cut -d' ' -f 2`
cdmPort=`grep '^tarantella.config.cdm.externalnbtport=' $TTAINSTDIR/var/serverconfig/global/cdm.properties | cut -d'=' -f 2`
unset pnaming
unset pserving
checkIsListeningUdp 137 && pnaming="yes"
checkIsListening $cdmPort && pserving="yes"
cdmpid=`ps -e -o pid,args | grep ttacdmd | awk '{ print $1 }'`
unset logged

if [ "$cdmEnabled" = "1" ] ; then
    if [ ! -z "$cdmpid" ] ; then
        if [ -z "$pserving" ] ; then
            logToFile "<b>`eval echo $msg_cdmoncdmrunningnoserving`</b>"
        else 
            logToFile "`eval echo $msg_cdmoncdmrunningserving`"
        fi
        if [ "$cdmWins" = "1" ]  ; then
            if [ -z "$pnaming" ] ; then
                logToFile "<b>$msg_cdmoncdmrunningnonaming</b>"
            else
                logToFile "$msg_cdmoncdmrunningnaming"
            fi
        else
            if [ ! -z "$pnaming" ] ; then
                logToFile "$msg_cdmpnaminginusenotbycdm"
            fi
        fi
    else
        if [ -z "$pnaming" -a -z "$pserving" ] ; then
            logToFile "<b>`eval echo $msg_cdmoncdmnotrunningnoportsopen`</b>"
        else
            logToFile "<b>`eval echo $msg_cdmoncdmnotrunningportsopen`</b>"
        fi
    fi
else
    if [ ! -z "$cdmpid" ] ; then
        logToFile "<b>$msg_cdmoffcdmrunning</b>"
    else
        if [ -z "$pnaming" -a -z "$pserving" ] ; then
            logToFile "`eval echo $msg_cdmoffcdmnotrunningportsopen`"
        else
            logToFile "`eval echo $msg_cdmoffcdmnotrunningnoportsopen`"
        fi
    fi
fi
verboseEcho "... done"
}

# get a log file for the pid (if there is one)
getLogFileForPid() {
pid=$1
for f in $TTAINSTDIR/var/log/*$pid*.log ; do
    if [ -f "$f" ] ; then
        if [ "`fileSize $f`" -gt 0 ] ; then
            runCmd cat $f 
        fi
    fi
done
}

# get a list of network interfaces 
getInterfaces() {
lines=`netstat -in | grep -v "Kernel Interface table" | wc -l`
lines=`expr $lines - 1`
netstat -in | tail -$lines | awk ' { print $1 }'
}


# get IP of a network interface.
getIpOfInterface() {
dev=$1
case $arch in 
    i3li*|ppli* ) 
        ifconfig $dev |grep "inet addr" | awk '{ print $2 }' | cut -d':' -f 2
    ;;
    * )
        netstat -in  | grep "^$dev" | awk '{ print $4 }' | grep '^[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*$'
    ;;
esac
}
    

dumpEnsNames() {
# get a ttab64conv file
unset ttab64convfile
for f in /usr/package/sadm/pkg/tta*/install/ttab64conv ; do
    if [ -f $f ] ; then
        ttab64convfile=$f
    fi
done

if [ ! -z "$ttab64convfile" ] ; then
    echo "$msg_ens_table_header"
    b64conv=$tmpFile.b64conv
    cp $ttab64convfile $b64conv
    chmod +x $b64conv
    firstcut=`echo $TTAINSTDIR/var/ens | awk -F/ '{ print NF + 1 }'`

    for d in `find $TTAINSTDIR/var/ens | grep -v '\.object'` ; do
        if [ -d $d ] ; then
            unset encoded
            unset unencoded
            cut=$firstcut
            ncut=`echo $d | awk -F/ '{ print NF+1 }'`
            while [ $cut -lt $ncut ] ; do
                name=`echo $d | cut -d/ -f $cut`
                encoded="$encoded/$name"
                unencoded="$unencoded/`$b64conv --decode $name`"
                cut=`expr $cut + 1`
            done
            echo "<tr><td>`echo $encoded | htmlify`</td><td>`echo $unencoded | htmlify`</td></tr>"
        fi
    done
    echo "</table>"
else
    echo "$msg_ens_nob64conv"
fi
}

dumpPreferencesNames() {
# These are B64 encoded like ens, but once decoded you have to unescape the following characters:
# initial ., * / : \ " ? < > |
# the following doesn't actually do that, it just does a hack that's good 
# enough for 7-bit names.
unset ttab64convfile
for f in /usr/package/sadm/pkg/tta*/install/ttab64conv ; do
    if [ -f $f ] ; then
        ttab64convfile=$f
    fi
done

if [ ! -z "$ttab64convfile" ] ; then
    b64conv=$tmpFile.b64conv
    cp $ttab64convfile $b64conv
    chmod +x $b64conv
else 
    echo "$msg_ens_nob64conv"
    return 1
fi

cd $TTAINSTDIR/var/preferences
ls > $tmpFile.prefs
echo "$msg_prefs_table_header"
for f in `cat $tmpFile.prefs` ; do
    echo "<tr><td>"
    echo $f | htmlify 
    echo "</td><td>"
    $b64conv --decode $f | tr + \\377 | tr \\357 + | tr \\267 + | tr \\221 . | tr \\220 \\057  | sed -e's/\+//g' | tr \\377 +  | htmlify
    echo "</td></tr>"
done
echo "</table>"
}


# configdump functionality:

# The ls command to do
myLs () {
    ls -CF $@ 2>/dev/null
}

# List all dirs in current dir, in alphabetical order
dirsOnly () {
    myLs -1 | grep "/" 2>/dev/null
}

# List all properties files in current dir 
# in alpahbetical order
propertiesOnly () {
    myLs -1 | grep "\.properties" 2>/dev/null
}

# Gets the current directory relative 
# to the starting directory
getRelativeDir () {
    echo ".`pwd | sed -e 's|'$startDir'||g'`"
    
}

# usage
usage () {
    echo "Usage: $COMMAND_NAME [ <dirName> ]" 
}

# Run the command in the subdirectories
doSubDirectories () {
    
    # loop through all subDirectories
    for dir in `dirsOnly` ; do
        # Do sorted print
        if cd $dir 2>/dev/null ; then
            doPropertiesFiles
            doSubDirectories
            cd ../
        fi
    done
    
}


# output all properties files in this dir
doPropertiesFiles () {
    
    #loop through all properties files
    for file in `propertiesOnly` ; do
        outputPropertiesFile $file -v
    done 
    #    
}



configDump() {
echo "configdump running as part of info $RCS_ID"
cd $TTAINSTDIR
startDir=`pwd`
if [ -d bin -a -d var ] ; then

    echo "# Start of file ./var/javaenv"
    cat var/javaenv
    echo "# End of file ./var/javaenv
"


    # cat the javaprops file
    if [ -d bin/scripts ] ; then
        echo "# Start of file ./bin/scripts/javaprops"
        cat bin/scripts/javaprops
        echo "# End of file ./bin/scripts/javaprops
"
    fi

    # Do the properties files in serverconfig
    if [ -d var/serverconfig ] ; then
        cd var/serverconfig
        doPropertiesFiles
        doSubDirectories        
        cd ../..
    fi

    # Do the properties files in serverresources/tfn
    if [ -d var/serverresources/tfn ] ; then
        cd var/serverresources/tfn
        doPropertiesFiles
        doSubDirectories        
        cd ../../..
    fi

else
    # Just do the properties files
    doPropertiesFiles
    doSubDirectories
fi
}


      
# called before any work is done. Prompts for a filename if needed.
preBuildTar() {
prompt=f
if [ -z "$givenTTAINFODIR" ] ; then
    prompt=t
fi
fileNumber=0
hostname=`$TTAINSTDIR/bin/bin/ttahostname`
fileNameBase=$TTAINFODIR/tta.info.$hostname

# get a suitable filename:
while [ -s $fileNameBase.$fileNumber.tar -o -s $fileNameBase.$fileNumber.tar.gz -o -s $fileNameBase.$fileNumber.tgz -o -r $fileNameBase.$fileNumber ] ; do
    fileNumber=`expr $fileNumber + 1`
done
fileName=$fileNameBase.$fileNumber.tar

# prompt if needed:
if [ $prompt = t ] ; then
    echo $N `eval echo "$msg_poutputfile"` $C
    read reqFileName
    if [ ! -z "$reqFileName" ] ; then
        fileName=`basename $reqFileName .gz`
    fi
fi

# make the directory:
MkTtaDir -p `dirname $fileName` 2>/dev/null 

# populate some the summary head and body files:
(
cat <<EOF

<html><head> 
<title>$msg_title `ttahostname`</title>
</head>
<body>
<h1><a name="top">$msg_title `ttahostname`</a></h1>
$msg_intro <code>$RCS_ID</code>
<div align=right><table><tr><td><a href="#cmd1">$msg_firstcommand</a></td></tr></table></div>
<h2>$msg_summary</h2>
<ul>

EOF
) > $opshead1

echo "<h2>$msg_contents</h2><ul>" > $opshead2
echo "<h2>$msg_commandoutputs</h2>" > $opsbody

optarfile=$fileName

TAROUTPUT=t

}

# build the tar file.  Called after everything has been done.
buildTar() {

# tidy some stuff up:
echo "</ul>">> $opshead1
echo "</ul>">> $opshead2
echo "</body></html>" >> $opsbody
cat $opshead1 $opshead2 $opsbody > $opbuilddir/summary.html
rm -f $opshead1 $opshead2 $opsbody ${tmpFile}* 2>/dev/null >/dev/null
tardir=$TTAINFODIR/`basename $optarfile .tar`

mv $opbuilddir $tardir

if [ -z "$optarfile" ] ; then
    echo "Error, no output tar file defined"
    exit 2
fi
cd `dirname $optarfile`
# Try with E flag first (required on Solaris for long filenames),
# and fall back if that fails
tar Efc $optarfile `basename $tardir` 2>/dev/null || tar fc $optarfile `basename $tardir`

if [ -z "$TI_NOGZIP" ] ; then
    gzip $optarfile
    eval echo $msg_generatedfile
else
    eval echo $msg_generatedfilenotzipped
fi

}




###########################################################
#
# The modes
#



###########################
#
#  General mode
#
#  (the default)
#
generalMode() {
# (no args) 
processLines <<EOF
tarantella status --verbose
tarantella license query
tarantella license query --history
tarantella license list
netstat -a
netstat -an
lpq -Ptta_printer
lpc status
tarantella security certinfo --full
EOF
case $arch in 
    i3li*|ppli* )
        runCmd ps awwwwwux
        ;;
    * )
        runCmd ps -edf
        ;;
esac
        
addFile $TTAINSTDIR var/javaenv
addFile $TTAINSTDIR bin/scripts/javaprops

for i in $TTAINSTDIR/var/log/*  ; do
    if [ -f $i ] ; then
        addFile $TTAINSTDIR var/log/`basename $i` 
    fi
done

addDirectory $TTAINSTDIR var/serverconfig
addDirectory $TTAINSTDIR var/serverresources/schema
addDirectory $TTAINSTDIR var/serverresources/tfn
verboseEcho -n "Adding beans in helpful format ..."
cd $TTAINSTDIR/var/serverconfig/global/beans
for i in *.properties ; do
    MkTtaDir $tmpFile.beans 2>/dev/null >/dev/null
    bn=`basename $i`
    outputPropertiesFile $i > $tmpFile.beans/$bn
    addFile -q $tmpFile.beans $bn beans
done
verboseEcho done
rm -rf $tmpFile.beans
runCmd pkgparam -v `getLatestPkg tta`
runCmd vmstat 2 5
ttapids=`getTTAPids`
runCmd -d getTTAPids echo "$ttapids" \; echo
if [ ! -z "$ttapids" ] ; then
    runCmd -d 'ps -p `getTTAPids`' ps -f -p `echo $ttapids`
fi

ttapidlist=`echo $ttapids | sed -e's/,/ /g'`
for p in $ttapidlist ; do
    getLogFileForPid $p
done
}


###########################
#
# summary Mode
#
summaryMode() {
# no args
date
uptime
case $arch in 
    i3li*|ppli* )
        runCmd ps awwwwwux
        echo /proc/sys/fs/file-nr: `cat /proc/sys/fs/file-nr`
        ;;
    * )
        runCmd ps -edf
        ;;
esac
runCmd df -i
runCmd df -k
runCmd tarantella status --byserver
runCmd netstat -an
runCmd networkStats
runCmd ps -e \| wc -l
ttapids=`getTTAPids`
runCmd -d getTTAPids echo "$ttapids"
runCmd -d 'ps -p `getTTAPids`' ps -f -p `echo $ttapids`
}


############################
#
# check Mode
#
# Check certain things are as they should be.
#
checkMode() {
checkArrayTopology
checkPeerAsadPorts
checkCDMStatus

ratio=$TI_CPUHOG
if [ -z "$ratio" ]; then
    ratio=25
fi
verboseEcho -n "Generating list of CPU hogs ..."
hogpids=`getCPUHogs $ratio`
verboseEcho " done ($hogpids)"
if [ -z "$hogpids" ] ; then
    logToFile `eval echo $msg_nocpuhogs`
fi

for p in $hogpids ; do
    process=`ps -p $p -o comm | tail -1`
    logToFile "<b>`eval echo $msg_cpuhog`</b>"
    verboseEcho "Examining process $p ($process) as it may be spinning"
    pidMode $p
done

checkTTAOrphans
checkTTAProcesses
}


############################
#
# diff Mode
#
# generate a list of things 
# that are different or have 
# been customised.
#
diffMode() {

diffConfig


# check for any changed files:
for pkg in tta ttapip ttawcp ; do
    package=`getLatestPkg $pkg`
    if [ "$?" = "0" ] ; then
        runCmd -d "pkgchk $pkg" pkgchk_tta $package
    else
        if [ $pkg  = tta ]; then 
            logToFile "<b>$msg_ttapkgnotfound</b>"
            runCmd pkginfo
        fi
    fi
done


# check to see if any files have been added.
runCmd  pkgchk_newfiles `pkginfo | grep Tarantella  |awk '{ print $2 }'`

}

#################
#
# pid Mode
#
pidMode() {
# $1 - pid
pidArg=$1

runCmd ps -p $pidArg
runCmd lsof -p $pidArg

unset stracepid
unset cmd
unset pmapcmd
case $arch in 
    i3li*|ppli* )
        cmd=strace
        echo $N $C > $tmpFile
        $cmd -p $pidArg 2>> $tmpFile.truss &
        stracepid=$!
        pmapcmd="cat /proc/$pidArg/maps"
        ;;
    rsai* )
        cmd=strace
        echo $N $C >$tmpFile
        $cmd -p $pidArg 2>> $tmpFile.truss &
        stracepid=$!
        ;;
    * )
        cmd=truss
        echo $N $C > $tmpFile
        $cmd -p $pidArg 2>> $tmpFile.truss &
        stracepid=$!
        pmapcmd="pmap -x $pidArg"
        ;;
esac
if [ ! -z "$stracepid" ]; then
    sleep 10
    kill $stracepid 2>/dev/null
    runCmd -d "$cmd -p $pidArg" cat $tmpFile.truss
    kill -9 $stracepid 2>/dev/null
fi
if [ ! -z "$pmapcmd" ]; then
    runCmd $pmapcmd
fi


}

##################
#
# ENS mode
#
ensMode() {
addDirectory $TTAINSTDIR var/ens

runCmd -h dumpEnsNames 
}

##################
#
# Print mode
printMode() {
addDirectory $TTAINSTDIR var/preferences
runCmd -h dumpPreferencesNames
runCmd lpstat -t
runCmd lpc status
runCmd lpc status all
runCmd cat /etc/printcap
for i in /var/log/lp* /var/lp/logs/* ; do
    if [ -f "$i" ] ; then
        runCmd cat $i
    fi
done
}

##################
#
# user mode
#
userMode() {
# $1 - a username
user=$1
processLines <<EOF
finger $user
cat /etc/passwd
cat /etc/group
ypcat passwd
niscat passwd.org_dir
niscat passwd.org_dir
cat /etc/nsswitch.conf
domainname
last
w
EOF
}

##################
#
# network mode
#
networkMode() {
processLines <<EOF
hostname
cat /etc/resolv.conf # DNS configuration
netstat -in
netstat -nr
netstat -s
$nslookup `uname -n`
cat /etc/*inetd.conf
arp -a
arp -an
getInterfaces
EOF
if [ -d /etc/xinetd.d ] ; then
    addDirectory / etc/xinetd.d network
fi
for dev in `getInterfaces` ; do
    ip=`getIpOfInterface $dev`
    [ -z "${ip}" ] && continue
    runCmd -d "getIpOfInterface $dev" echo $ip
    runCmd $nslookup $ip
    nslookupFile=$opbuilddir/cmds/${nslookup}_$ip
    numLines=`cat $nslookupFile | wc -l`
    if [ "$numLines" = 1 ]; then
        hostname=`cat $nslookupFile | awk ' { print $NF }' | sed -e's/\\.$//g'`
    else
        hostname=`cat $nslookupFile | grep -i name | grep -i -v server | awk ' { print $NF }' | sed -e's/\\.$//g'`
    fi
    if [ ! -z "$hostname" ] ; then
        runCmd  $nslookup $hostname
    else
        logToFile "<b>`eval echo $msg_cannotdeterminehostnameofdev`</b>"
    fi
done
    
}


startStrace() {
# $1 - name of file to output to
# $2 - pid (may be empty string)
set +m
if [ -z "$2" ] ; then 
    return 1
fi

pidArg=$2

# cannot strace a pid that doesn't exist.
kill -0 $pidArg 2>/dev/null || return 2


file=$detailop/strace.$1

unset stracepid
unset cmd
unset pmapcmd
case $arch in 
    i3li*|ppli* )
        (
        cmd=strace
        echo $N $C > $file
        strace -p $pidArg 2>> $file &
        echo $!
        )
        ;;
    rsai* )
        (
        cmd=strace
        echo $N $C >$file
        strace -p $pidArg 2>> $file &
        echo $!
        )
        ;;
    * )
        (
        cmd=truss
        echo $N $C > $file
        truss -p $pidArg 2>> $file &
        echo $!
        )
        ;;
esac
return 0
}


startdetailedMode() {
statusFile=$TTAINFODIR/info.detailed.$$
detailop=$TTAINFODIR/op.detailed.$$

MkTtaDir $detailop

proxyPid=`cat $TTAINSTDIR/var/info/auxserver.pid 2>/dev/null`
cdmPid=`cat $TTAINSTDIR/var/info/cdmserver.pid 2>/dev/null`
if [ ! -z "$proxyPid" ] ; then
    if kill -0 $proxyPid >/dev/null 2>/dev/null ; then
        # good, proxy is up and running
        # work out the children of this process whose command name is "ttaauxserv"
        ps -e -o ppid,pid | grep " *$proxyPid " | awk '{ print $2 }' > $tmpFile.proxypids
        for i in `cat $tmpFile.proxypids` ; do
            ps -p $i -o args | grep ttaauxserv 2>/dev/null >/dev/null
            if [ "$?" = "0" ]; then
                proxyPids="$proxyPids $i"
            fi
        done
        set $proxyPids >/dev/null 2>/dev/null
        if [ -z "$1" -o -z "$2" ] ; then
            pemPid=""
        else 
            if [ $1 -gt $2 ] ;  then
                pemPid=$1
            else
                pemPid=$2
            fi
        fi
    else
        proxyPid=""
    fi
fi

[ -f $cfgList ] || runCmd tarantella config list >/dev/null 2>&1
oldfilter=`cat $cfgList | grep '^array-logfilter:' | cut -b 18- | sed -e's/,/ /g'`


tarantella config edit --array-logfilter $oldfilter "*/*/*:detailed.log" 2>/dev/null >/dev/null




startStrace proxy $proxyPid > $tmpFile.proxy
startStrace pem $pemPid > $tmpFile.pem
startStrace cdm $cdmPid > $tmpFile.cdm
proxyStracePid=`cat $tmpFile.proxy`
pemStracePid=`cat $tmpFile.pem`
cdmStracePid=`cat $tmpFile.cdm`

cat > $statusFile <<EOF
# detailed information status file.
# to stop the following processes and obtain their output, run
# tarantella info --stopdetailed <path to this file>

proxyStracePid=$proxyStracePid
pemStracePid=$pemStracePid
cdmStracePid=$cdmStracePid
op=$detailop
oldfilter="$oldfilter"
detailedlogpre=$detailedlogpre
EOF

for i in detailed.log proxy$proxyPid.log proxy${proxyPid}_error.log pemanager$pemPid.log pemanager${pemPid}_error.log jserver$jserverPid.log jserver$jserverPid.jsl cpe$cdmPid.log ; do
    n=`echo $i | cut -d'.' -f 1 | sed -e's/[0123456789]//g'`
    if [ -f $TTAINSTDIR/var/log/$i ] ; then
        echo logpre_$n=`partialCatPre $TTAINSTDIR/var/log/$i` >> $statusFile
        echo logfile_$n=$i >> $statusFile
    fi
done

eval echo \""$msg_detailedstarted"\"

}

stopdetailedMode() {
# $1 - name of a statusFile.

if [ -z "$1" -o ! -f "$1" ] ; then 
    unset file
    count=0
    for i in $TTAINFODIR/info.detailed.* ; do
        if [ -f $i ] ; then
            file=$i
            count=`expr $count + 1`
        fi
    done
    if [ "$count" != "1" ] ; then
        eval `echo $msg_missingdetailfile`
        return 1
    fi
    statusFile=$file
else
    statusFile=$1
fi
. $statusFile
kill $proxyStracePid 2>/dev/null
kill $pemStracePid 2>/dev/null
kill $cdmStracePid 2>/dev/null
for name in proxy pem cdm ; do
    if [ -f $op/strace.$name ] ; then
        runCmd -d "strace $name" cat $op/strace.$name
    fi
done

kill -9 $proxyStracePid 2>/dev/null
kill -9 $pemStracePid 2>/dev/null
kill -9 $cdmStracePid 2>/dev/null
for logline in `grep '^logfile_' $statusFile` ; do
    name=`echo $logline | cut -b 9- | cut -d'=' -f 1`
    logpre=`eval echo \\$logpre_$name`
    fname=`eval echo \\$logfile_$name`
    runCmd -d "tail -f $fname" partialCatPost $logpre $TTAINSTDIR/var/log/$fname
done

tarantella config edit --array-logfilter $oldfilter

rm -rf $op 2>/dev/null >/dev/null
rm $statusFile  2>/dev/null >/dev/null
}



#################
#
# JServer Mode
#
jserverMode() {

jserverThreadDump
jserverDebugHttpd    
    
}


###################
#
# Packages mode
#
packagesMode() {
runCmd -d "pkginfo (tta)" pkginfo \| grep Tarantella
runCmd pkginfo -l
runCmd pkgparam -v `getLatestPkg tta`
}

###################
#
# Platform mode
#
# mostly copied from the sysinfo-based scripts
#
platformMode() {
# common stuff:

processLines <<EOF
    ### Common information
    uname -a                                        # System version
    cat /etc/inittab                                # inittab information
    ls -lR /etc/rc.d/                               # startup scripts

EOF

logSize=100

# for unixware/solaris:
if [ -x /etc/hw ]; then
    HWcmd="hw -v                            # hardware details"
else
    HWcmd="echo pcilong | ndcfg -           # hardware details"
fi
# platform-specific stuff:
case $arch in
    i3li*|ppli* )
    # set architecture in $MACHINEARCH
    if [ -z "$MACHINEARCH" ]
    then
machinearch ()
{
#!/bin/sh
#  $Id: ixiarch.sh,v 10.38 2005/06/20 19:21:26 peterc Exp $
#  Copyright (C) 1996-2005 Tarantella, Inc.
#  This software code contains proprietary information
#  and should be treated as confidential.
#
#  Print canonical syscode for platform

# There are three valid types of command line:
#
# 1.     visionarch
# 2.     visionarch <available codes>...
# 3.	 visionarch [-c|-o]
#
# 1. The architecture is echoed
# 2. The best architecture from the list is returned
# 3. The -c and -o options return just the system Code or the OS type.

# 0) INITIALIZE VARIABLES

# Some of these are historical, but dont cause any harm
PATH=/bin:/usr/bin:/sbin:/usr/sbin:$XDTHOME/bin:$PMWMHOME/bin:$IXIHOME/bin:$PATH


# 1) Arguments
numcodes=0
for i
do
  case $i in
    -c )
      codeonly=1
    ;;
  
    -o )
      osonly=1
    ;;

    -n )
      if [ -z "$codeonly" -a -z "$osonly" ]
      then
	  displayname=1	
      fi
    ;;
 
    * )
      checkcodes="$checkcodes $i"
      numcodes=`expr $numcodes + 1`
    ;;

   esac
done

# fast exit
if [ $numcodes = 1 ]
then
  echo $checkcodes
  exit 0
fi


# 2) MESSAGES
myname=`basename $0`

#  First define some messages.
#  They get overwritten by sourcing from a file, scripts.ll_TT,
#  so there's no need to translate them here.  

#  Messages for the visionarch script.
#  These follow text like "visionarch: !4! ", and may extend to several lines.
msg_xdtarch_no_uname=\
'No uname command found.'
msg_xdtarch_os_cpu=\
'Cannot recognize the Operating System or processor type.'
msg_xdtarch_ver_rel=\
'Cannot calculate version or release.'
msg_xdtarch_no_match=\
'Cannot find matching installed system.'

#  End of messages
# Try to find a language script
posslangfiles=""
for lang in C $IXILANG $PANLANG $LANG
do
  for pathname in $XDTHOME/bin/scripts. $PMWMHOME/bin/scripts. $IXIHOME/bin/scripts. ./scripts.
  do
    posslangfiles="$posslangfiles $pathname.$lang"
  done
done

# see if we can find one of those language files
for f in $posslangfiles
do
  if [ -f $f ]
  then
    . $scriptslangfile			# source it
    break
  fi						
done
  
# 3) TRY UNAME AND SET UP VARIABLES

unamev=`uname -v 2>/dev/null`
if [ $? -ne 0 ]
then
  # This isn't really a UNIX system is it?
  echo >&2  "$myname: !2! $msg_xdtarch_no_uname"
  exit 2
fi

U_SYSTEM=`uname -s 2>/dev/null`  || U_SYSTEM=UNKNOWN
U_RELEASE=`uname -r 2>/dev/null` || U_RELEASE=UNKNOWN
U_VERSION=`uname -v 2>/dev/null` || U_VERSION=UNKNOWN

# Some machines use -m arg to return 'model' rather
# than architecture.  For example, NCR SVR4 returns
# 3433,3434.  On such machines need to use -p which
# returns processor.

for MACHARG in m p
do
    U_MACHINE=`uname -"$MACHARG" 2>/dev/null` || U_MACHINE=UNKNOWN

    # 4)  FIND THE MACHINE
    # Note that we only look for cpu/os combinations our products currently
    # support - if you want better matching, most GNU software comes with
    # a script called 'config.guess' which does a more thorough job (and
    # has totally different output!)

    CPU= 			# Characters 1-2 of syscode
    OS= 			# Characters 3-4 of syscode
    VER=			# Digits 5-6 of syscode
    REL= 			# Digits 7-8 of syscode


    case ${U_MACHINE}::${U_SYSTEM}::${U_RELEASE}::${U_VERSION} in
      # Intel FreeBSD
      i*::FreeBSD::*:* )
        CPU=i3
        OS=fb
        NAME="FreeBSD (Intel)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # MacOS X
      powerpc::Darwin::*::*)
        CPU=pp
        OS=dw
        NAME="Darwin (PowerPC)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # PowerPC Linux
      ppc*::Linux::*::*)
        CPU=pp
        OS=li
        NAME="Linux (PowerPC)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # Intel Linux
      i*::Linux::*::* )
	CPU=i3
	OS=li
	NAME="Linux (Intel)"
	VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
	REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
      ;;
      # Athlon 64 Linux
      x86_64::Linux::*::* )
	CPU=i3
	OS=li
	NAME="Linux (AMD 64)"
	VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
	REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
      ;;
      # PowerPC Linux
      ppc*::Linux::*::* )
        CPU=pp
        OS=li
        NAME="Linux (PowerPC)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # Sequent (Intel)
      i*::DYNIX*::*::* )
	CPU=i3
	OS=dy
	NAME="Sequent DYNIX/ptx (Intel)"
	VER=`expr $U_VERSION : 'V\([0-9]\).*'`
	REL=`expr $U_VERSION : 'V[0-9].\([0-9].[0-9]\)' | sed 's/\.//g'`
      ;;

      # The Sun family
      *::SunOS::4.*::* )
	CPU=sp
	OS=su
	VER=4
	NAME="Sun SunOS (Sparc)"
	REL=`expr $U_RELEASE : '4.\([^_]*\)' | sed 's/[^0-9]//g'`
      ;;
      sun*::SunOS::5.*::* )
	CPU=sp
	OS=so
	VER=5
	NAME="Sun Solaris (Sparc)"
	REL=`expr $U_RELEASE : '5.\([0-9][0-9]*\).*' | sed 's/[^0-9]//g'`
      ;;
      *86*::SunOS::5.*::* )
	CPU=i3
	OS=so
	VER=5
	NAME="Sun Solaris (Intel)"
	REL=`expr $U_RELEASE : '5.\(.*\)' | sed 's/[^0-9]//g'`
      ;;
      *::SunOS::5.*::* )
	CPU=sp
	OS=so
	VER=5
	NAME="Sun Solaris (Sparc)"
	REL=`expr $U_RELEASE : '5.\([0-9][0-9]*\).*' | sed 's/[^0-9]//g'`
      ;;

      # HP
      *::HP-UX::*::* )
	CPU=pa
	OS=hp
	NAME="Hewlett-Packard HP-UX (PA-RISC)"
	VER=`expr $U_RELEASE : '[^.]*.\([0-9]*\).*'`
	REL=`expr $U_RELEASE : '[^.]*.[^.]*.\([0-9]*\)'`
      ;;

      # Data General
      *::dgux::5.4*::* )
	CPU=m8
	OS=dg
	VER=54
	NAME="Data General DG/UX (Motorola)"
	REL=`expr $U_RELEASE : '5.4\(.*\)' | sed 's/[^0-9]//g' | sed 's/\(.\).*\(.\)$/\1\2/'`
      ;;

      # Data General on Intel
      *::dgux::R4*::* )
	case `uname -p`  in
	  m* )
	    CPU=m8 ;;
	  * )
	    CPU=i3 ;;
	esac
	OS=dg
	VER=04
	NAME="Data General DG/UX (Intel)"
	REL=`expr $U_RELEASE : 'R4.\(.*\)' | sed 's/[^0-9]//g'`
        REL=`echo $REL | sed 's/\(..\).*/\1/'`
      ;;

      # OSF/1
      alpha::OSF1::*::* )
	CPU=ax
	OS=o1
	NAME="DEC OSF/1 (Alpha)"
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # ULTRIX
      *::ULTRIX::*::* )
	CPU=mp
	OS=ul
	NAME="DEC Ultrix (MIPS)"
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # IRIX
      *::IRIX::4.*::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;
      
      *::IRIX::5.1::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*.[^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # Note
      # If we ever get minor release numbers of 5.2 we'll have to do
      # something different
      *::IRIX::5.2::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=20
      ;;
      # Note
      # This system does not exist yet
      *::IRIX::5.2.*::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # catchall for other irix versions
      # 6.4 and later change from IRIX to IRIX64
      *::IRIX*::*::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # AIX
      # note that we can't figure out the patch level of a 3.2.x (x<4)
      # system (even IBM can't tell you immediately!)
      *::AIX::*::* )
	CPU=rs
	OS=ai
	NAME="IBM AIX (Risc)"
	VER=$U_VERSION
	REL=$U_RELEASE
      ;;

      # RISC OS (the mips variety, not acorn)
      # version 5 like output
      mips::*::*::RISCos )
	CPU=mp
	OS=ro
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;
      # version 4 like output
      mips::*::*::UMIPS )
	CPU=mp
	OS=ro
	VER=`echo $U_RELEASE | sed 's/\([0-9]*\).*/\1/'`
	REL=`echo $U_RELEASE | sed 's/[0-9]*\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # Siemens Nixdorf mips R4000 (at least)
      R4000::*::*::* )
	CPU=mp
	OS=sx
	NAME="Siemens Nixdorf SINIX (MIPS)"
	VER=`echo $U_RELEASE | sed 's/\([0-9]*\).*/\1/'`
	REL=`echo $U_RELEASE | sed 's/[0-9]*\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # Motorola SVR4
      *88*::*::4*::* )
	CPU=m8
	OS=mo
	VER=`expr $U_VERSION : '[^V]*.\([^.]*\).*' | sed 's/[^0-9]//g'`
	REL=`expr $U_VERSION : '[^V]*.[^.]*.\(.*\)' | sed 's/[^0-9]//g'`
      ;;

      # windows nt with nutcracker
      *::Windows_NT::*::* )
	CPU=i3
	OS=wi
	VER="$U_RELEASE"
	REL="$U_VERSION"
      ;;

      DRS*::*::*::* )
	  PROC=`uname -p 2>/dev/null` || PROC=UNKNOWN
	  case "$PROC" in
	    sparc | SPARC )
	      CPU=sp
	      OS=nx
	      NAME="ICL DRS/NX (Sparc)"
	      ;;
	    i386 )
	      CPU=i386
	      OS=nx
	      NAME="ICL DRS/NX (Intel)"
	      ;;
	  esac

	  VER=`expr $U_VERSION : '\([0-9]\).*'`
	  REL=`expr $U_VERSION : '[0-9]..*\([0-9].[0-9]\)' | sed 's/\.//g'`
      ;;

      
      *::UnixWare::*::* )
	CPU=i3
	OS=un
	NAME="SCO UnixWare (Intel)"
	VER=`expr $U_VERSION : '\([0-9]\)'`
	REL=`expr $U_VERSION : '[0-9].\(.*\)' | sed -e 's/\.//'`
	if [ -z "$REL" ]; then
		REL=00
        elif [ "x`expr $REL : '[0-9]\([0-9]\)'`" = "x" ] ; then
		REL="$REL"0
	fi
	;;

      *::OpenUNIX::*::* )
        CPU=i3
        OS=un
        NAME="SCO UnixWare (Intel)"
        VER=`expr $U_VERSION : '\([0-9]\)'`
        REL=`expr $U_VERSION : '[0-9].\(.*\)' | sed -e 's/\.//'`
        if [ -z "$REL" ]; then
                REL=00
        elif [ "x`expr $REL : '[0-9]\([0-9]\)'`" = "x" ] ; then
                REL="$REL"0
        fi
        ;;

      # Various Intel based Unixen.  These seem particularly reluctant
      # to divulge their OS name, so we have to grep through
      # various system files to find the OS string

      *86*::*::*::* )
	if grep -s -i UnixWare /stand/boot 2>/dev/null 1>&2 || strings /stand/1/unix_mp 2>/dev/null | grep -s -i Unixware 2>/dev/null 1>&2
	then
          # It's some version of Unixware obviously
	  CPU=i3
	  OS=un
	  NAME="SCO UnixWare (Intel)"
          if expr $U_VERSION : 'D\([0-9]*.*\)' 2>/dev/null 1>&2
	  then
            # It's a date stamped version ; we dont yet know how to figure out
            # which so just pretend that it is unixware 212
            VER=02
            REL=12
          else
	    VER=`expr $U_VERSION : '\([0-9]\)'`
	    REL=`expr $U_VERSION : '[0-9].\(.*\)' | sed -e 's/\.//'`
	    if [ "x`expr $REL : '[0-9]\([0-9]\)'`" = "x" ] 
	    then
		REL="$REL"0
	    fi
          fi
	else
	  if [ "$U_SYSTEM" = "SCO_SV" ]
	  then
	    CPU=i3
	    OS=sc
	    VER=`expr $U_RELEASE : '^\([0-9]*\)'`
	    NAME="SCO OpenServer (Intel)"
	    # just the release string ie: 3.2v5.0.0
	    relstr=`uname -X | grep Release | awk '{ print $3 }'`
	    # just the major SCO version after the SVR? (3.2v) bit
	    U_VERSION=`expr ${relstr} : '[0-9.]*v\([0-9]\)[0-9.]*'`
	    REL=`expr ${U_RELEASE}::${U_VERSION} : '[0-9]*\(.*\)' | sed 's/[^0-9]//g'`
	  else
	    if grep -s 'The Santa Cruz Operation' /etc/gettydefs 2>/dev/null 1>&2
	    then
	      CPU=i3
	      OS=sc
	      NAME="SCO Unix (Intel)"
	      VER=`expr $U_RELEASE : '^\([0-9]*\)'`
	      REL=`expr ${U_RELEASE}::${U_VERSION} : '[0-9]*\(.*\)' | sed 's/[^0-9]//g'`
	    else
	      # DYNIX/ptx V2 doesn't return 'DYNIX' or 'ptx' in uname.
	      # This kludge may work, may not, it's either this
	      # or flip a coin!   
	      if grep -s 'ptx' /etc/versionlog 2>/dev/null 1>&2
	      then
		CPU=i3
		OS=dy
		NAME="Sequent DYNIX/ptx (Intel)"
		VER=`expr $U_VERSION : 'V\([0-9]\).*'`
		REL=`expr $U_VERSION : 'V[0-9].\([0-9].[0-9]\)' | sed 's/\.//g'`
	      else
	        # Assume OS must be System V Release 4.
	        CPU=i3
	        OS=sv
		NAME="System V Release 4 (Intel)"
	        VER=`expr $U_RELEASE : '^\([0-9]*\)'`
	        REL=`expr ${U_RELEASE}::${U_VERSION} : '[0-9]*\(.*\)' | sed 's/[^0-9]//g'`
	      fi
	    fi
	  fi
	fi
	;;	
    esac

    if [ -n "$CPU" -a -n "$OS" -a -n "$VER" -a -n "$REL" ]
    then
	break
    fi
done

# 5) Do sanity checking and cleanup
VER=`echo $VER | sed 's/[^0-9]//g'`
REL=`echo $REL | sed 's/[^0-9]//g'`

if [ -z "$CPU" -o -z "$OS" ]
then
  echo "$myname: !10! $msg_xdtarch_os_cpu"
  exit 10
fi

if [ -z "$VER" -o -z "$REL" ]
then
  echo "$myname: !11! $msg_xdtarch_ver_rel"
  exit 11
fi

# Add leading zeroes
REL=`echo 0$REL | sed 's/.*\(..\)/\1/'`
VER=`echo 0$VER | sed 's/.*\(..\)/\1/'`

# 6) So we now know it all

syscode=$CPU$OS$VER$REL

if  test -n "$codeonly"
then
    echo $CPU$OS
    exit 0
fi

if  test -n "$osonly"
then
    echo $VER$REL
    exit 0
fi

# 7) Check for codes given on the command line

if [ ! -z "$checkcodes" ]
then
    for i in $checkcodes
    do
	# Filter the input $checkcodes by matching CPU and OS, and strip
	# them off leaving just the VER and REL.  The tr command replaces
	# spaces by line-feeds, so that the following sort can do its stuff.
	posscodes=`echo $checkcodes | tr ' ' '\012' \
				| sed -ne "s/$CPU$OS//p" | sort -n`
	if [ -z "$posscodes" ]
	then				# None supplied for correct CPU+OS
	    echo >&2 "$myname: !5! $msg_xdtarch_no_match"
	    exit 5
	fi 

	# Some of them are the right platform.
	# The following algorithm returns the greatest possible code which
	# is older than this syscode, or, failing that, the least possible
	# code which is more recent than this one.

	for ver_rel in $posscodes
	do
	    if [ $VER$REL -eq $ver_rel ]
	    then 			# bingo we have this exact release
		echo $syscode
		exit 0
	    elif [ $VER$REL -gt $ver_rel ]
	    then 			# store this previous version
		priorcode=$CPU$OS$ver_rel
	    else 			# $VER$REL is < $ver_rel
		if [ -n "$priorcode" ]
		then
		    echo $priorcode
		    exit 0
		else
		    # Oh dear, we have no previous version so we should use
		    # the oldest newer version which is this current one ...
		    echo $CPU$OS$ver_rel
		    exit 0
		fi
	    fi
	done
    done
    if [ -n "$priorcode" ]
    then
        echo $priorcode
        exit 0
    fi
else
    if [ -n "$displayname" ]
    then
	echo "$NAME"
    else
	echo $syscode
    fi
fi

}
MACHINEARCH=`machinearch`
MACHINEFLAVOR=""
LSBFLAVOR=""
if [  `expr $MACHINEARCH : ..li....` -ne 0 ] ; then
	distrib=`ls /etc/*-release 2>/dev/null`
	n_distrib=`echo $distrib | LANG=C LC_ALL=C tr '[A-Z]' '[a-z]'`
        
        for f_distrib in $n_distrib ; do 
	  case "$f_distrib" in
	    *turbolinux* )
	        MACHINEFLAVOR="turbolinux"
		;;
	    *suse* )
	        MACHINEFLAVOR="suse"
	        ;;
	    *caldera* )
                MACHINEFLAVOR="caldera"
                ;;
	    *redhat*|*fedora* )
	        MACHINEFLAVOR="redhat"
	        ;;
            *lsb* )
                eval `grep ^DISTRIB_ID /etc/lsb-release`
                case "$DISTRIB_ID" in
                 *SuSE* )
                        LSBFLAVOR="suse"
                        ;;
                 "SCO Linux"* ) 
                        LSBFLAVOR="scolinux"
                        ;;
                 *UnitedLinux* ) 
                        LSBFLAVOR="unitedlinux"
                        ;;
                esac
                ;;
	    * )
		# Caldera and Debian don't have a -release.
		# But Debian has a debian_version
		if [ -f /etc/debian_version ] ; then
			MACHINEFLAVOR="debian"
		else
			distrib=`rpm -q -a 2>/dev/null | grep OpenLinux 2>/dev/null`
			r_distrib=`echo $distrib | LANG=C LC_ALL=C tr '[A-Z]' '[a-z]'`
			case "$r_distrib" in
				*openlinux* )
					MACHINEFLAVOR="caldera"
					;;
			esac
		fi
     		;;
	  esac
        done
        # use the LSB flavor iff we haven't determined a flavor from files
        # and packages.
        if [ -z "$MACHINEFLAVOR" -a  ! -z "$LSBFLAVOR" ] ; then
                MACHINEFLAVOR=$LSBFLAVOR
        fi
fi



    fi

    if [ -f /etc/debian_version ] ; then
        distversion=/etc/debian_version
    else
        distversion=/etc/*-release
    fi
    processLines <<EOF
    ### Installation
    echo $MACHINEFLAVOR                             # Linux distribution
    cat $distversion                                # distribution version
    cat /etc/sysconfig/init                         # Bootup info
    rpm -qa                                         # list installed packages
    lsmod                                           # list loaded modules
        
    ### Hardware
    lsdev                                           # list devices
    procinfo -a                                     # list resources
    cat /etc/sysconfig/hwconf                       # hwconf info
    cat /etc/sysconfig/keyboard                     # keyboard info
    cat /etc/sysconfig/mouse                        # mouse info

    ### Disk and filesystem
    cat /etc/fstab                                  # filesystem details
    lilo -q                                         # lilo info
    ulimit -f                                       # user limit
    df -k                                           # disk info, basic
    df -i                                           # disk info, with inodes

    ###   Startup, ports 
    chkconfig --list                                # configured services
    cat /etc/printcap                               # lpd printer information
    lpc status                                      # show printer status

    ###  Networking Configuration
    ifconfig                                        # interface config
    cat /etc/sysconfig/network                      # network information
    cat /etc/hosts                                  # hosts information
    cat /etc/resolv.conf                            # resolver information
    cat /etc/nsswitch.conf                          # resolver information
    cat /etc/named.conf                             # named bind8 information
    cat /etc/named.boot                             # named bind4 information
    cat /etc/inetd.conf                             # listener configuration
    cat /etc/services                               # port definitions
    netstat -nr                                     # routing table
    $nslookup `uname -n`

    ###     NFS, RPC and NIS
    cat /etc/exports                                # NFS shares
    showmount -e                                    # NFS shares available
    showmount -a                                    # NFS shares in use
    rpcinfo -p                                      # RPC port info
    ypwhich                                         # NIS binding info

    ###   Kernel and Tuning Info
    ipcs -a                                         # IPC status
    cat /proc/sys/fs/file-nr                        # fd nr, free, max
    cat /proc/sys/fs/inode-nr                       # inodes nr, free
    cat /proc/sys/fs/inode-max                      # inodes max

    ###       Current Activity
    lsof -n                                         # list open files

    ###         Recent Logs
    tail -100 /var/log/messages                     # Recent messages
    tail -100 /var/log/secure                       # security messages
    dmesg                                           # kernel messages
EOF
    ;;
    spso*|i3so* )
        
    processLines <<EOF
    ###        Installation
    uname -a                                        # system version
    uname -X                                        # system information
    pkginfo -l                                      # package information
    showrev -p                                      # patch information

    ###          Hardware
    prtconf                                         # hardware configuration
    cat /etc/device.tab                             # device table
    psrinfo -v                                      # processor(s) status
    memsize -a                                      # memory configuration
    $HWcmd

    ###    Disks and Filesystems
    sdiconfig -l                                    # HBA & drive information
    df -lk                                          # disk info, basic
    df -lb                                          # disk info, with inodes
    cat /etc/vfstab                                 # filesystem details
    ulimit -f                                       # filesize limit
    prtvtoc "/dev/rdsk/*"                           # prtvtoc information

    ###    Ports and Monitors
    sacadm -l                                       # port monitor info
    pmadm -l                                        # port information
    ls -l /etc/init.d/                              # start/stop scripts
    cat /etc/lp/Systems                             # remote printer info
    lpstat -t                                       # printer statust
    crontab -l                                      # cron table info

    ###  Networking Configuration
    cat /etc/hosts                                  # hosts information
    cat /etc/resolv.conf                            # resolver information
    cat /etc/named.conf                             # named bind4 info
    cat /etc/named.boot                             # named bind8 info
    cat /etc/netconfig                              # resolver order info
    cat /etc/inetd.conf                             # listener configuration
    cat /etc/services                               # port definitions
    cat /etc/inet/config                            # network startup
    netcfg -s                                       # network information
    ifconfig -a                                     # network interface
    netstat -nr                                     # routing table
    $nslookup `uname -n`                            # nslookup

    ###   Networking Statistics
    ndstat -l                                       # network card stats
    netstat -ni                                     # interface usage info
    netstat -s                                      # networking statistics
    netstat -na                                     # socket connections
    sockinfo -a                                     # sockinfo (open source)
    ss                                              # ss (open source)
    netstat -rn                                     # routing table details
    netstat -rMs                                    # routing statistics
    echo "strstat"|crash                            # streams statistics

    ###      NFS, RPC, and NIS
    nfsstat                                         # NFS statistics
    cat /etc/dfs/dfstab				    # NFS shares
    showmount -e                                    # NFS shares available
    showmount -a                                    # NFS shares in use
    rpcinfo -p                                      # RPC port info
    ypwhich                                         # NIS binding info

    ###     System Tuning Info
    ipcs -a                                         # IPC status
    sysdef                                          # system tuning info
    cat /etc/conf/cf.d/mtune                        # tuning parameters
    cat /etc/conf/cf.d/stune                        # tuning adjustments
    cat /etc/conf/cf.d/sdevice                      # driver settings

    ###      Current Activity
    ps -elfL                                        # process status
    lsof -n                                         # lsof (open source)
    sar -u 1 10                                     # cpu usage
    sar -c 1 10                                     # syscall utilization

    ###      Recent Log Info
    tail -$LogSize /var/log/sysidconfig.log         # recent sysidconf info
    tail -$LogSize /var/log/syslog                  # recent syslog info
    tail -$LogSize /var/adm/log/cs.debug            # connection server 
    tail -$LogSize /var/saf/zsmon*/log              # ttymon1 log
    

EOF
    ;;
    i3un* )
    
        processLines <<EOF
    ###        Installation
    uname -a                                        # system version
    uname -X                                        # system information
    pkginfo -l base                                 # base package info
    pkginfo -c set -l UnixWare                      # UnixWare set info
    brand -L                                        # license information
    cat /stand/boot                                 # bootfile contents
    pkginfo                                         # package information
    pkginfo -lc patch|grep PSTAMP                   # patch information

    ###          Hardware
    prtconf                                         # hardware configuration
    cat /etc/device.tab                             # device table
    psrinfo -v                                      # processor(s) status
    memsize -a                                      # memory configuration
    resmgr                                          # resmgr output
    $HWcmd

    ###    Disks and Filesystems  
    sdiconfig -l                                    # HBA & drive information
    df -lk                                          # disk info, basic
    df -liv                                         # disk info, with inodes
    cat /etc/vfstab                                 # filesystem details
    ulimit -f                                       # filesize limit
    fsadm "/dev/rroot"                              # largefiles root
    prtvtoc "/dev/rroot"                            # prtvtoc information

    ###    Ports and Monitors
    sacadm -l                                       # port monitor info
    pmadm -l                                        # port information
    ls -l /etc/init.d/                              # start/stop scripts
    cat /etc/lp/Systems                             # remote printer info
    lpstat -t                                       # printer statust
    crontab -l                                      # cron table info

    ###  Networking Configuration
    cat /etc/hosts                                  # hosts information
    cat /etc/resolv.conf                            # resolver information
    cat /etc/inet/named.conf                        # named bind4 info
    cat /etc/inet/named.boot                        # named bind8 info
    cat /etc/netconfig                              # resolver order info
    cat /etc/inetd.conf                             # listener configuration
    cat /etc/services                               # port definitions
    cat /etc/inet/config                            # network startup
    netcfg -s                                       # network information
    ifconfig -a                                     # network interface
    netstat -nr                                     # routing table
    cat /etc/confnet.d/inet/interface               # interface init
    $nslookup `uname -n`		            # nslookup

    ###   Networking Statistics
    ndstat -l                                       # network card stats
    netstat -ni                                     # interface usage info
    netstat -s                                      # networking statistics
    netstat -na                                     # socket connections
    sockinfo -a                                     # sockinfo (open source)
    ss                                              # ss (open source)
    netstat -rAn                                    # routing table details
    netstat -rs                                     # routing statistics
    echo "strstat"|crash                            # streams statistics

    ###      NFS, RPC, and NIS
    nfsstat                                         # NFS statistics
    cat /etc/dfs/sharetab                           # NFS shares
    showmount -e                                    # NFS shares available
    showmount -a                                    # NFS shares in use
    rpcinfo -p                                      # RPC port info
    ypwhich                                         # NIS binding info

    ###     System Tuning Info
    ipcs -a                                         # IPC status
    sysdef                                          # system tuning info
    cat /etc/conf/cf.d/mtune                        # tuning parameters
    cat /etc/conf/cf.d/stune                        # tuning adjustments
    cat /etc/conf/cf.d/sdevice                      # driver settings

    ###      Current Activity
    ps -elfL                                        # process status
    lsof -n                                         # lsof (open source)
    sar -u 1 10                                     # cpu usage
    sar -c 1 10                                     # syscall utilization

    ###      User Information
    who                                             # current users
    who -a                                          # user activity
    finger                                          # network users
    cat /etc/passwd                                 # account info
    cat /etc/group                                  # group info

    ###      Recent Log Info
    tail -$LogSize /var/adm/log/osmlog                   # recent osmlog info
    tail -$LogSize /var/adm/syslog                       # recent syslog info
    tail -$LogSize /var/adm/log/cs.debug                 # connection server 
    tail -$LogSize /var/saf/ttymon*/log                  # ttymon1 log
EOF
    ;;
    pahp* )
        processLines <<EOF
    ###        Installation
    uname -a                                        # system version
    uname -X                                        # system information
    pkginfo -l base                                 # base package info
    pkginfo -c set -l UnixWare                      # UnixWare set info
    cat /stand/boot                                 # bootfile contents
    pkginfo                                         # package information
    pkginfo -lc patch|grep PSTAMP                   # patch information

    ###          Hardware
    cat /etc/device.tab                             # device table
    $HWcmd

    ###    Disks and Filesystems
    df -lk                                          # disk info, basic
    df -liv                                         # disk info, with inodes
    cat /etc/vfstab                                 # filesystem details
    ulimit -f                                       # filesize limit
    fsadm "/dev/rroot"                              # largefiles root

    ###    Ports and Monitors
    ls -l /etc/init.d/                              # start/stop scripts
    cat /etc/lp/Systems                             # remote printer info
    lpstat -t                                       # printer statust
    crontab -l                                      # cron table info

    ###  Networking Configuration
    cat /etc/hosts                                  # hosts information
    cat /etc/resolv.conf                            # resolver information
    cat /etc/inet/named.conf                        # named bind4 info
    cat /etc/inet/named.boot                        # named bind8 info
    cat /etc/netconfig                              # resolver order info
    cat /etc/inetd.conf                             # listener configuration
    cat /etc/services                               # port definitions
    cat /etc/inet/config                            # network startup
    ifconfig -a                                     # network interface
    cat /etc/confnet.d/inet/interface               # interface init
    $nslookup `uname -n`			    # nslookup

    ###   Networking Statistics
    netstat -ni                                     # interface usage info
    netstat -s                                      # networking statistics
    netstat -na                                     # socket connections
    netstat -rAn                                    # routing table details
    netstat -rs                                     # routing statistics
    echo "strstat"|crash                            # streams statistics

    ###      NFS, RPC, and NIS
    nfsstat                                         # NFS statistics
    cat /etc/dfs/sharetab                           # NFS shares
    showmount -e                                    # NFS shares available
    showmount -a                                    # NFS shares in use
    rpcinfo -p                                      # RPC port info
    ypwhich                                         # NIS binding info

    ###     System Tuning Info
    ipcs -a                                         # IPC status
    sysdef                                          # system tuning info
    cat /etc/conf/cf.d/mtune                        # tuning parameters
    cat /etc/conf/cf.d/stune                        # tuning adjustments
    cat /etc/conf/cf.d/sdevice                      # driver settings

    ###      Current Activity
    ps -elfL                                        # process status
    sar -u 1 10                                     # cpu usage
    sar -c 1 10                                     # syscall utilization

    ###      User Information
    who                                             # current users
    who -a                                          # user activity
    finger                                          # network users
    cat /etc/passwd                                 # account info
    cat /etc/group                                  # group info

    ###      Recent Log Info
    tail -$LogSize /var/adm/log/osmlog              # recent osmlog info
    tail -$LogSize /var/adm/syslog                  # recent syslog info
    tail -$LogSize /var/adm/log/cs.debug            # connection server 
    tail -$LogSize /var/saf/ttymon*/log             # ttymon1 log
EOF
    ;;
esac
}

#########################
#
# Basic mode
#
# run in all modes
# that output a tar file:
#
basicMode() {
if [ -z "$TAROUTPUT" ]; then 
    runCmd date
    runCmd ttahostname
    runCmd tarantella version
    case $arch in 
        rsai* ) 
            runCmd oslevel -r
            ;;
    esac
else
    logToFile "$msg_invocation <code>$invocationArgs</code>"
    logToFile "$msg_arch <code>`uname -a`</code>."
    logToFile "$msg_time `date`."
    logToFile "$msg_uptime `uptime`."
    (
    echo $N "<li>$msg_ttaver<pre>"$C
    tarantella version | htmlify
    echo "</pre></li>"
    ) >> $opshead1
    case $arch in 
        rsai* ) 
            logToFile "$msg_aixoslevel: <code>`oslevel -r`</code>."
            ;;
    esac
fi
runCmd tarantella status
}


#########################
#
# cmd Mode
#
# execute just one 
# command.
#
cmdMode() {
$@
}


#################################################################
#
# Back to the main control flow:
#

trap cleanUp 1 2 15

if [ -z "$STDOUTONLY" ]; then
    preBuildTar
fi

for mode in $MODES ; do
    args=`eval echo \\$${mode}Arg`
    arg=`echo $args |cut -d' ' -f 1`
    args=`echo $args | cut -d' ' -f 2-`
    eval ${mode}Arg=\"$args\"
    [ -z "$QUIETARG" ] && addHeader "$mode $arg"
    [ ! -z "$TAROUTPUT" -a "$mode" != "basic" ] &&  eval echo $msg_moderunning
    ${mode}Mode $arg $args
done

if [ -z "$STDOUTONLY" ]; then
    buildTar
else
    cleanUp
fi
