#!/bin/sh
#******************************************************************************
#                       ISTP LZPR SOFTWARE
#               Property of the U.S. Government
#                       NASA/GSFC/Code 560
#******************************************************************************
#
# UNIT NAME: lzp_system
#
# PURPOSE: To make and manage the ISTP LZP system
#
# CHANGE HISTORY:
# Author        Change ID  Build/Release   Date      Description of Change
# ------        ---------  ------------- ---------   ---------------------
# R. Wiechert   ISTP       R1.2          04/25/98    Original code
# R. Wiechert   ISTP       R1.2A         05/06/98    Add chmod 775 $ftpdir,
#                                                     add backup function
#
# NOTES:
#
# The make section executes as ROOT so be extra careful about
# the commands you put in here.  Test the HELL out of this
# script or you may end up crashing the entire system later on!
#
# See the help section embedded in the code for more details.
#
#******************************************************************************
# system make parameters
dbuser=oracle:dba
dumpdir=oracle
ftpdir=cdrblks
hashdir=data2
blkdir=blks
holddir=hold

# general parameters
lockfile=config/Assembly_Decom_Startup.parm
stop_attempts=12
abort_attempts=1
start_sleep=10
stop_sleep=10
native=true
exitcode=0

command="$1"
case $command in
   make)       rootopts="root only"    ;;
   start)      rootopts="oracle first" ;;
   stop)       rootopts="oracle last"  ;;
   abort)      rootopts="oracle last"   ; stop_attempts=$abort_attempts ;;
   hold)       rootopts="user only"    ;;
   release)    rootopts="user only"    ;;
   manual)     rootopts="user only"    ;;
   automatic)  rootopts="user only"    ;;
   flush)      rootopts="oracle only"  ;;
   backup)     rootopts="oracle only"  ;;
   keep)       rootopts="prefer user"  ;;
   unkeep)     rootopts="prefer user"  ;;
   status)     rootopts="prefer user"  ;;
   *) command=help ;;
esac

if [ "$command" = "help" ]
then
more << END_USAGE_TEXT

USAGE:     lzp_system command [username [...]]

PURPOSE:   Creates and maintains the ISTP Level Zero Processor

OPTIONS:   help        display help screen
           make        create and/or tune filesystems
           start       start database and/or software
           stop        stop software and/or database
           abort       abort software and/or database
           hold        place all pending input on hold
           release     restore pending input to queue
           manual      enter manual processing mode
           automatic   enter automatic processing mode
           flush       flush all database memory buffers
           backup      backup database and configuration
           keep        keep database procedures in memory
           unkeep      allow database procedures on disk
           status      show database procedures and status

SYNOPSIS:  This script has three distinct modes of operation,
           depending on the user who invokes it.  The caller
           must be one of:  root, oracle, user.  The script
           verifies and calculates several parameters including
           hostname, IPaddress, username, and home directory.
           Depending on the caller and the command, not all
           commands are available to all users.  Particularly,
           only root and oracle may manipulate other missions.

           The make command is available only to root in order
           to unmount, newfs, tunefs, and/or mount filesystems.
           The make command automatically creates the basic LZP
           filesystem without destroying existing data whenever
           possible.  The make command works for both OPS and
           DEV filesystems.  Note that the software and database
           must be stopped before attempting the make command.

           The start command starts the database when invoked
           by oracle, starts the Level Zero Processor when
           invoked by a regular user, and starts both when
           invoked by root (first database, then software).
           The automatic command must be issued manually.

           The stop command nicely stops the software when
           invoked by a regular user, nicely stops the database
           when invoked by oracle, and nicely stops both when
           invoked by root (first software, then database).
           The stop command implies the manual command.  If,
           after a while, the Level Zero Processor does not
           stop, then the abort command is also implied.

           The abort command abruptly stops the software when
           invoked by a regular user, calls shutdown immediate
           for the database when invoked by oracle, and does
           both when invoked by root (first software, then
           database).  The abort command implies the manual
           command.  Although oracle provides a shutdown abort
           feature, lzp_system does not take advantage of it.

           The hold command moves all block files pending in
           a particular mission blks directory to the hold
           directory in order to prevent them from being
           processed automatically.  The hold command implies
           the manual command and is only available to root
           and regular users.  The hold command will avoid
           all block files with associated log files since
           those files may be active.

           The release command moves all block files held in
           a particular mission hold directory back to the
           blks directory in order to continue the automatic
           processing.  The release command also implies the
           automatic command and is only available to root
           and regular users.

           The manual command removes the cron table for a
           particular mission, preserving it in the mission
           config directory.  This does not interfere with
           any active processes, instead it simply prevents
           automatic processes from running in the future.
           The manual command is only available to root and
           regular users.  The manual command also provides
           an easy way of editing the cron table with your
           favorite text editor.

           The automatic command loads the cron table for
           a particular mission, using the previous cron
           table image which was stored in the mission
           config directory.  This does not interfere with
           any active processes, instead it simply enables
           automatic processes to be run in the future.
           The automatic command is only available to root
           and regular users.

           The flush command flushes pinned and old objects
           from the database memory buffers and is available
           only to root and oracle.  The flush command may
           help to correct memory allocation issues which
           tend to arise within any large database instance.
           The flush command does not interfere with any
           active processes, however it may cause temporary
           performance degradation.

           The backup command copies the contents of the
           mission config directory as well as hidden files
           located within the mission home directory.  The
           mission oracle directory is used to store these
           copies according to database instance, date, and
           current time.  The backup command also performs
           a full export of the database into the mission
           oracle directory.

           The keep and unkeep commands alter database
           storage and memory usage policies so that the
           system will or will not attempt to keep the
           reconstruction rules and procedures in memory
           at all times.  Keeping procedures in memory
           can greatly enhance database performance when
           data volume is not too high.  However, there
           is a trade-off between caching code or data.
           The keep and unkeep commands may be followed
           by two arguments:  the mission and an object
           name string which may contain SQL wildcards.
           If no object string is specified, then the
           wildcard string % will be assumed.  The keep
           and unkeep commands are available to all users
           with trusted database access.  See the status
           command for an example of command syntax.
           
           The status command shows the overall database
           storage and memory usage statistics which are
           useful in determining performance problems and
           solutions.  The status command may be followed
           by two arguments:  the mission and an object
           name string which may contain SQL wildcards.
           If no object string is specified, then the
           wildcard string % will be assumed.  The status
           command is available to all users with trusted
           database access.  For example, to display the
           wind mission status including all database
           objects starting with xxx and ending with yyy,
           use lzp_system status wind xxx%yyy.

NOTES:     This script may be called by root at system
           startup/shutdown time and follows the calling
           conventions established by most UNIX system
           rc scripts.  It is recommended that this script
           complement the oracle startup/shutdown scripts
           since it also takes care of halting the LZP
           software nicely before halting the database.
           While the LZP software may be aborted abruptly,
           the oracle database is never halted with any
           options stronger than shutdown immediate.

END_USAGE_TEXT
exit 9
fi

hostname=`/usr/bin/hostname`
if [ ! "$hostname" ]
then
   printf "\nUnable to determine current host\n\n"; exit 9
fi

DISPLAY=`netstat -n -I hme0 2>/dev/null| tail -1| awk '{ print $4 }'`
if [ "$DISPLAY" ]
then
   DISPLAY="$DISPLAY":0.0
   export DISPLAY
else
   printf "\nUnable to determine IP address\n\n"; exit 9
fi

username=`/usr/ucb/whoami`
if [ ! "$username" ]
then
   printf "\nUnable to determine current user\n\n"; exit 9
fi

userhome=`grep "^$username:" /etc/passwd`
userhome=`expr "$userhome" : '.*:.*:.*:.*:.*:\(.*\):.*'`
if [ "$userhome" ]
then
   semaphore="$userhome/$lockfile"
   crontable="$userhome/config/crontab.$username"
else
   printf "\nUnable to determine home directory\n\n"; exit 9
fi

if [ "$username" = "root" -a "$command" != "make" ]
then
   if [ $# -gt 1 ]
   then
      while [ $# -gt 1 ]
      do
         shift 1
         if [ "$rootopts" = "oracle only" ]
         then
            su - oracle -c "/opt/local/bin/lzp_system $command $1"
         elif [ "$rootopts" = "oracle first" ]
         then
            su - oracle -c "/opt/local/bin/lzp_system $command $1"
            su - $1 -c "/opt/local/bin/lzp_system $command $1"
         elif [ "$rootopts" = "oracle last" ]
         then
            su - $1 -c "/opt/local/bin/lzp_system $command $1"
            su - oracle -c "/opt/local/bin/lzp_system $command $1"
         elif [ "$rootopts" = "user only" -o "$rootopts" = "prefer user" ]
         then
            su - $1 -c "/opt/local/bin/lzp_system $command $1"
         fi
      done
      exit 0
   else
      printf "\nPlease specify a list of users\n\n"; exit 9
   fi
fi

if [ "$username" = "root" -a "$command" = "make" ]
then
   if [ $# -lt 2 ]
   then
      printf "\nPlease specify a list of users\n\n"; exit 9
   fi
   while [ $# -gt 1 ]
   do
      shift 1
      username=$1
      case $username in
         wind)     mission=wind ;
                      team=ops ;
                     owner=wind:wind ;
                   ftpuser=windftp:wind ;
                 rawdevice="/dev/vx/rdsk/windgrp" ;
                 mountopts=yes ;
                tunefsopts="-m 5 -o time" ;
                 newfsopts="-i 131072 -c 32" ;;
         winddev)  mission=wind ;
                      team=dev ;
                     owner=winddev:dev ;
                   ftpuser=winddev:dev ;
                 rawdevice="/dev/vx/rdsk/windgrp" ;
                 mountopts=no ;
                tunefsopts="-m 5 -o time" ;
                 newfsopts="null" ;;
         polar)    mission=polar ;
                      team=ops ;
                     owner=polar:polar ;
                   ftpuser=polarftp:polar ;
                 rawdevice="/dev/vx/rdsk/polargrp" ;
                 mountopts=yes ;
                tunefsopts="-m 5 -o time" ;
                 newfsopts="-i 131072 -c 32" ;;
         polardev) mission=polar ;
                      team=dev ;
                     owner=polardev:dev ;
                   ftpuser=polardev:dev ;
                 rawdevice="/dev/vx/rdsk/polargrp" ;
                 mountopts=no ;
                tunefsopts="-m 5 -o time" ;
                 newfsopts="null" ;;
         geotail)  mission=geotail ;
                      team=ops ;
                     owner=geotail:geotail ;
                   ftpuser=geoftp:geotail ;
                 rawdevice="/dev/vx/rdsk/geotailgrp" ;
                 mountopts=yes ;
                tunefsopts="-m 5 -o time" ;
                 newfsopts="-i 131072 -c 32" ;;
         geodev)   mission=geotail ;
                      team=dev ;
                     owner=geodev:dev ;
                   ftpuser=geodev:dev ;
                 rawdevice="/dev/vx/rdsk/geotailgrp" ;
                 mountopts=no ;
                tunefsopts="-m 5 -o time" ;
                 newfsopts="null" ;;
         *dev)     mission=`expr "$username" : '\(.*\)dev'` ;
                      team=dev ;
                     owner="$username":dev ;
                   ftpuser="$username":dev ;
                 rawdevice="/dev/vx/rdsk/$mission"grp ;
                 mountopts=no ;
                tunefsopts="-m 5 -o time" ;
                 newfsopts="null" ;;
         *)        mission="$username" ;
                      team=ops ;
                     owner="$username":"$username" ;
                   ftpuser="$username"ftp:"$username" ;
                 rawdevice="/dev/vx/rdsk/$mission"grp ;
                 mountopts=yes ;
                tunefsopts="-m 5 -o time"
                 newfsopts="-i 131072 -c 32" ;;
      esac
      printf "\n\n\n============================================================\n\n"
      printf "              Making ISTP $username filesystem\n"
      printf "\n============================================================\n\n\n\n"
      printf "Enter database username [$dbuser]: "
      read in_dbuser
      if [ "$in_dbuser" ]
      then
         dbuser="$in_dbuser"
      fi
      printf "Reformat filesystems (y/n)? "
      read answer
      if [ "$answer" = "y" ]
      then
         printf "Enter raw device [$rawdevice]: "
         read in_rawdevice
         if [ "$in_rawdevice" ]
         then
            rawdevice="$in_rawdevice"
         fi
         printf "Enter newfs options or null [$newfsopts]: "
         read in_newfsopts
         if [ "$in_newfsopts" ]
         then
            if [ "$in_newfsopts" != "null" ]
            then
               newfsopts="$in_newfsopts"
            else
               newfsopts=""
            fi
         fi
      else
         newfsopts=""
      fi
      printf "Tune filesystems (y/n)? "
      read answer
      if [ "$answer" = "y" ]
      then
         printf "Enter tunefs options or null [$tunefsopts]: "
         read in_tunefsopts
         if [ "$in_tunefsopts" ]
         then
            if [ "$in_tunefsopts" != "null" ]
            then
               tunefsopts="$in_tunefsopts"
            else
               tunefsopts=""
            fi
         fi
      else
         tunefsopts=""
      fi
      printf "\nYou have made the following selections:\n\n"
      printf "Database for $username on $hostname owned by $dbuser\n"
      if [ "$newfsopts" ]
      then
         printf "Reformat $rawdevice using:\nnewfs $newfsopts filesystem\n"
         warning="\nWARNING:  REFORMATTING DESTROYS EXISTING DATA\n"
      else
         printf "Existing filesystems will be preserved\n"
         warning=""
      fi
      if [ "$tunefsopts" ]
      then
         printf "Tune $rawdevice using:\ntunefs $tunefsopts filesystem\n"
      else
         printf "Default optimizations will be preserved\n"
      fi
      printf "$warning"
      printf "\nMake $username filesystems (y/n)? "
      read answer
      if [ "$answer" = "y" ]
      then
         echo ""
         echo "Making filesystems for $username on $hostname"
         echo "----------------------------------------------------------------"
         echo "Mounting all filesystems"
         mount -a 1>/dev/null 2>/dev/null
         fscount=0
         fslist=nonempty
         while [ "$fslist" -a "$fscount" -lt 10 ]
         do
            fscount=`expr $fscount + 1`
            fslist=`df -k 2>/dev/null | awk '{ print $6 }' | grep "^/$mission/" \
             | egrep -v "^/$mission/$team/$hashdir|^/$mission/$username" \
             | egrep -v "^/proc|^/dev|^/var|^/tmp|^/opt|^/oracle|^/export"`
            for fsitem in $fslist
            do
               printf "Unmounting $fsitem\n"
               umount $fsitem 1>/dev/null 2>/dev/null
            done
         done
         if [ "$fslist" ]
         then
            echo "ERROR:  Mount points are busy"
            continue
         fi
         if [ "$mountopts" = "yes" ]
         then
            echo "Unmounting /$mission/$team/$hashdir"
            umount /$mission/$team/$hashdir
            if [ $? = 0 -o ! -d /$mission/$team/$hashdir ]
            then
               echo "Removing old mount points"
               rm -rf /$mission/$team/$hashdir
            else
               echo "ERROR"; continue
            fi
         fi
         if [ "$mountopts" = "yes" ]
         then
            echo "Unmounting /$mission/$username"1
            umount /$mission/$username"1"
            if [ $? = 0 -o ! -d /$mission/$username"1" ]
            then
               echo "Removing old mount points"
               rm -rf /$mission/$username"1"
            else
               echo "ERROR"; continue
            fi
         fi
         if [ "$mountopts" = "yes" ]
         then
            echo "Unmounting /$mission/$username"2
            umount /$mission/$username"2"
            if [ $? = 0 -o ! -d /$mission/$username"2" ]
            then
               echo "Removing old mount points"
               rm -rf /$mission/$username"2"
            else
               echo "ERROR"; continue
            fi
         fi
         if [ "$mountopts" = "yes" ]
         then
            echo "Unmounting /$mission"
            umount /$mission 2>/dev/null
            if [ $? = 0 -o ! -d /$mission ]
            then
               echo "Removing old mount points"
               rm -rf /$mission
            else
               echo "WARNING:  Mount point is busy"
            fi
         fi
         echo "Making /$mission"
         mkdir /$mission 2>/dev/null
         if [ "$newfsopts" ]
         then
            printf "Enter newfs options [$newfsopts]: "
            read in_newfsopts
            if [ ! "$in_newfsopts" ]
            then
               in_newfsopts="$newfsopts"
            fi
            newfs $in_newfsopts $rawdevice/$mission"home"
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to reformat /$mission"
               continue
            fi
         fi
         if [ "$tunefsopts" ]
         then
            printf "Enter tunefs options [$tunefsopts]: "
            read in_tunefsopts
            if [ ! "$in_tunefsopts" ]
            then
               in_tunefsopts="$tunefsopts"
            fi
            tunefs $in_tunefsopts /$mission
            if [ $? != 0 ]
            then
               echo "WARNING:  Unable to tune /$mission"
            fi
         fi
         if [ "$mountopts" = "yes" ]
         then
            mount /$mission 2>/dev/null
            df /$mission 1>/dev/null 2>/dev/null
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to mount /$mission"
               continue
            fi
         fi
         echo "Making /$mission/$team"
         mkdir -p /$mission/$team
         chown -h $owner /$mission/$team
         if [ $? != 0 -o ! -d /$mission/$team ]
         then
            echo "ERROR:  Unable to chown /$mission/$team"
            continue
         fi
         echo "Making /$mission/$team/$dumpdir"
         mkdir -p /$mission/$team/$dumpdir/.../...
         chown -h $dbuser /$mission/$team/$dumpdir
         if [ $? != 0 -o ! -d /$mission/$team/$dumpdir/.../... ]
         then
            echo "ERROR:  Unable to protect /$mission/$team/$dumpdir"
            continue
         fi
         echo "Making /$mission/$team/$ftpdir"
         mkdir -p /$mission/$team/$ftpdir/.../...
         chmod 775 /$mission/$team/$ftpdir
         chown -h $ftpuser /$mission/$team/$ftpdir
         if [ $? != 0 -o ! -d /$mission/$team/$ftpdir/.../... ]
         then
            echo "ERROR:  Unable to protect /$mission/$team/$ftpdir"
            continue
         fi
         echo "Making /$mission/$team/$hashdir"
         mkdir -p /$mission/$team/$hashdir/.../...
         if [ ! -d /$mission/$team/$hashdir/.../... ]
         then
            echo "ERROR:  Unable to protect /$mission/$team/$hashdir"
            continue
         fi
         if [ "$newfsopts" ]
         then
            printf "Enter newfs options [$newfsopts]: "
            read in_newfsopts
            if [ ! "$in_newfsopts" ]
            then
               in_newfsopts="$newfsopts"
            fi
            newfs $in_newfsopts $rawdevice/$mission"data2"
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to reformat /$mission/$team/$hashdir"
               continue
            fi
         fi
         if [ "$tunefsopts" ]
         then
            printf "Enter tunefs options [$tunefsopts]: "
            read in_tunefsopts
            if [ ! "$in_tunefsopts" ]
            then
               in_tunefsopts="$tunefsopts"
            fi
            tunefs $in_tunefsopts /$mission/$team/$hashdir
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to tune /$mission/$team/$hashdir"
               continue
            fi
         fi
         echo "Making /$mission/$username"1
         mkdir /$mission/$username"1"
         if [ "$newfsopts" ]
         then
            printf "Enter newfs options [$newfsopts]: "
            read in_newfsopts
            if [ ! "$in_newfsopts" ]
            then
               in_newfsopts="$newfsopts"
            fi
            newfs $in_newfsopts $rawdevice/$mission"ora1"
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to reformat /$mission/$username"1
               continue
            fi
         fi
         if [ "$tunefsopts" ]
         then
            printf "Enter tunefs options [$tunefsopts]: "
            read in_tunefsopts
            if [ ! "$in_tunefsopts" ]
            then
               in_tunefsopts="$tunefsopts"
            fi
            tunefs $in_tunefsopts /$mission/$username"1"
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to tune /$mission/$username"1
               continue
            fi
         fi
         echo "Making /$mission/$username"2
         mkdir /$mission/$username"2"
         if [ "$newfsopts" ]
         then
            printf "Enter newfs options [$newfsopts]: "
            read in_newfsopts
            if [ ! "$in_newfsopts" ]
            then
               in_newfsopts="$newfsopts"
            fi
            newfs $in_newfsopts $rawdevice/$mission"ora2"
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to reformat /$mission/$username"2
               continue
            fi
         fi
         if [ "$tunefsopts" ]
         then
            printf "Enter tunefs options [$tunefsopts]: "
            read in_tunefsopts
            if [ ! "$in_tunefsopts" ]
            then
               in_tunefsopts="$tunefsopts"
            fi
            tunefs $in_tunefsopts /$mission/$username"2"
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to tune /$mission/$username"2
               continue
            fi
         fi
         if [ "$mountopts" = "yes" ]
         then
            mount /$mission/$team/$hashdir
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to mount /$mission/$team/$hashdir"
               continue
            fi
         fi
         chown -h $owner /$mission/$team/$hashdir
         if [ $? != 0 ]
         then
            echo "ERROR:  Unable to chown /$mission/$team/$hashdir"
            continue
         fi
         if [ "$mountopts" = "yes" ]
         then
            mount /$mission/$username"1"
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to mount /$mission/$username"1
               continue
            fi
         fi
         if [ "$mountopts" = "yes" ]
         then
            mount /$mission/$username"2"
            if [ $? != 0 ]
            then
               echo "ERROR:  Unable to mount /$mission/$username"2
               continue
            fi
         fi
         chown -h $dbuser /$mission/$username"1" /$mission/$username"2"
         if [ $? != 0 ]
         then
            echo "ERROR:  Unable to chown /$mission/$username"1
            echo "ERROR:  Unable to chown /$mission/$username"2
            continue
         fi
         printf "Make finished successfully\n"
         printf "\nFilesystem status for $username on $hostname\n"
         printf "----------------------------------------------------------------\n"
         df -k /$mission /$mission/$username"1" /$mission/$username"2" /$mission/$team/$hashdir
      fi
   done
   exit 0
fi

if [ "$rootopts" = "root only" ]
then
   printf "\nOnly root may execute $command\n\n"; exit 9
fi

if [ "$username" = "oracle" ]
then
   case $command in
      start)  svrmgrl="startup" ;;
      stop)   svrmgrl="shutdown normal" ;;
      abort)  svrmgrl="shutdown immediate" ;;
      flush)  svrmgrl="alter system flush shared_pool;" ;;
      backup) svrmgrl="backup" ;;
      *)      svrmgrl="null" ;;
   esac
   if [ $# -gt 1 ]
   then
      if [ "$svrmgrl" != "null" ]
      then
         while [ $# -gt 1 -a "$svrmgrl" != "null" ]
         do
            shift 1
            ORACLE_SID=`echo $1 | tr [a-z] [A-Z]`
            export ORACLE_SID
            if [ "$command" = "backup" ]
            then
               userhome=`grep "^$1:" /etc/passwd`
               userhome=`expr "$userhome" : '.*:.*:.*:.*:.*:\(.*\):.*'`
               file_prefix="$userhome/oracle/$ORACLE_SID"`date "+_%Y%b%d_%H%M%S"`
               export="exp full=y userid=sys file=$file_prefix"_full.dmp
               echo ""
               echo "Executing backup for $1 on $hostname"
               echo "----------------------------------------------------------------"
               echo "Checking for active processes"
               process_list=`ps -eo "ruser pid comm" | grep "oracle$ORACLE_SID" | grep "$1 "`
               if [ "$process_list" ]
               then
                  echo ""
                  echo "    USER   PID COMMAND"
                  echo "$process_list"
                  echo ""
                  echo "WARNING:  Backup may be incomplete"
               fi
               printf "Proceed with backup now (y/n)? "
               read answer
               answer=`echo "$answer" | tr [A-Z] [a-z]`
               if [ "$answer" = "y" ]
               then
                  echo ""
                  echo "Copying config directory"
                  cp -pr $userhome/config $file_prefix"_config" 2>/dev/null
                  echo "Copying home directory"
                  mkdir $file_prefix"_home" 2>/dev/null
                  cp -p $userhome/.* $file_prefix"_home" 2>/dev/null
                  echo "Exporting database objects"
                  echo "$export"
                  $export
               fi
            else

echo ""
echo "Executing server manager for $1 on $hostname"
echo "----------------------------------------------------------------"
echo "$ORACLE_SID> $svrmgrl"
svrmgrl<<ENDORACLEARGS
connect internal
$svrmgrl
exit
ENDORACLEARGS

            fi
         done
         exit 0
      else
         if [ "$rootopts" = "user only" ]
         then
            printf "\nOnly users may execute $command\n\n"; exit 9
         fi
      fi
   else
      printf "\nPlease specify a list of users\n\n"; exit 9
   fi
fi

if [ "$rootopts" = "oracle only" ]
then
   printf "\nOnly oracle may execute $command\n\n"; exit 9
fi

if [ $# -gt 1 ]
then
   if [ "$username" = "$2" ]
   then
      # okay to specify oneself
      native=true
   else
      if [ "$username" = "oracle" -o "$command" = "status" ]
      then
         username="$2"
         native=false
      else
         printf "\nOnly root may specify another user\n\n"; exit 9
      fi
   fi
   shift 2
else
   shift 1
fi

if [ "$command" = "hold" ]
then
   echo ""
   echo "Holding block files for $username on $hostname"
   echo "----------------------------------------------------------------"
   if [ -d "$userhome/$blkdir" -a -d "$userhome/$holddir" ]
   then
      filelist=`ls -trd $userhome/$blkdir/*.blk 2>/dev/null`
      for file in $filelist
      do
         if [ -f "$file"_replay_log ]
         then
            echo "Skipping $file"
         else
            echo "Holding $file"
            /usr/bin/mv -f $file $userhome/$holddir 2>/dev/null
         fi
      done
      command=manual
   else
      echo "ERROR:  Unable to access filesystem"
      exitcode=4
   fi
fi

if [ "$command" = "release" ]
then
   echo ""
   echo "Releasing block files for $username on $hostname"
   echo "----------------------------------------------------------------"
   if [ -d "$userhome/$blkdir" -a -d "$userhome/$holddir" ]
   then
      filelist=`ls -trd $userhome/$holddir/*.blk 2>/dev/null`
      for file in $filelist
      do
         echo "Releasing $file"
         /usr/bin/mv -f $file $userhome/$blkdir 2>/dev/null
      done
      command=automatic
   else
      echo "ERROR:  Unable to access filesystem"
      exitcode=4
   fi
fi

trap "" 1 2 3 15
if [ "$command" = "keep" -o "$command" = "unkeep" -o "$command" = "status" ]
then
   echo ""
   echo "Database status for $username on $hostname"
   echo "----------------------------------------------------------------"
   ORACLE_SID=`echo "$username" | tr [a-z] [A-Z]`
   export ORACLE_SID

   if [ "$native" = "true" ]
   then
      dps_database_user=`decrypt.sql $PICSHOME 2>/dev/null`
   else
      stty -echo
      printf "Password: "
      read dps_database_user
      dps_database_user="$username/$dps_database_user"
      stty echo
      echo ""
   fi

   objects="$*"
   if [ ! "$objects" ]
   then
      objects="%"
   fi

sqlplus /nolog << ENDORACLEARGS
connect $dps_database_user
exec $username.pin_procedures('$command','$username','$objects');
ENDORACLEARGS
fi

if [ "$command" = "start" ]
then
   echo ""
   echo "Starting Level Zero Processor for $username on $hostname"
   echo "----------------------------------------------------------------"

   process_list="PSC|RM|CAS|PAS|CGS|CSD|PPA|CGP|PEP|PEI|PER|PTT|IDF"
   live_processes=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
   | grep "$username " | egrep "$process_list|lzp_process|lzp_replay" | grep -v grep`
   if [ -h "$semaphore" -o "$live_processes" ]
   then
      command=status
      echo "ERROR:  Level Zero Processor already started"
   else
      command=verify
      /usr/bin/touch $semaphore 2>/dev/null
      if [ -d "$PSC_PATH" -a -x "$PSC_PATH" ]
      then
         echo "Starting PDP subsystem"
         cd $PSC_PATH
         ./PSC $hostname &
         sleep $start_sleep
         if [ -d "$PEP_PATH" -a -x "$PEP_PATH" ]
         then
            echo "Starting PEP subsystem"
            cd $PEP_PATH
            ./PEP &
            sleep $start_sleep
            if [ -d "$PTT_PATH" -a -x "$PTT_PATH" ]
            then
               echo "Starting PTT subsystem"
               cd $PTT_PATH
               ./PTT &
               sleep $start_sleep
               if [ -d "$IDF_PATH" -a -x "$IDF_PATH" ]
               then
                  echo "Starting IDF subsystem"
                  cd $IDF_PATH
                  ./IDF &
                  sleep $start_sleep
               fi
            fi
         fi
      fi
   fi
fi

if [ "$command" = "verify" -o "$command" = "status" ]
then
   echo ""
   echo "Level Zero Processor status for $username on $hostname"
   echo "----------------------------------------------------------------"

   error=false
   pscpid=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
   | grep "$username " | grep "PSC" | grep -v grep | awk '{ print $2 }'`
   if [ "$pscpid" ]
   then
      echo "PDP group leader is running"
      psc_child_list="RM CAS PAS CGS"
      for psc_child in $psc_child_list
      do
         parent=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
         | grep "$username " | grep "$psc_child" | grep -v grep | awk '{ print $3 }'`
         if [ "$parent" != "$pscpid" ]
         then
            echo "ERROR:  PDP subsystem not started"
            error=true
            break
         fi
      done
   else
      echo "ERROR:  PDP group leader not started"
      error=true
   fi

   peppid=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
   | grep "$username " | grep "PEP" | grep -v grep | awk '{ print $2 }'`
   if [ "$peppid" ]
   then
      echo "PEP group leader is running"
      pep_child_list="PEI1 PER"
      for pep_child in $pep_child_list
      do
         parent=`/usr/5bin/ps -eo "user pid ppid tty etime comm args" \
         | grep "$username " | grep "$pep_child" | grep -v grep | awk '{ print $3 }'`
         if [ "$parent" != "$peppid" ]
         then
            echo "ERROR:  PEP subsystem not started"
            error=true
            break
         fi
      done
   else
      echo "ERROR:  PEP group leader not started"
      error=true
   fi

   pttpid=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
   | grep "$username " | grep "PTT" | grep -v grep | awk '{ print $2 }'`
   if [ "$pttpid" ]
   then
      echo "PTT group leader is running"
   else
      echo "ERROR:  PTT subsystem not started"
      if [ "$error" = "false" ]
      then
         error=ignore
      fi
   fi

   idfpid=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
   | grep "$username " | grep "IDF" | grep -v grep | awk '{ print $2 }'`
   if [ "$idfpid" ]
   then
      echo "IDF group leader is running"
   else
      echo "ERROR:  IDF subsystem not started"
      if [ "$error" = "false" ]
      then
         error=ignore
      fi
   fi

   case $error in
      false) echo "Level Zero Processor is running"; exitcode=0 ;;
      ignore) echo "Level Zero Processor is running"; exitcode=1 ;;
      true) echo "Level Zero Processor is disabled"; exitcode=2 ;;
   esac

   if [ "$command" = "verify" ]
   then
      if [ "$error" = "true" ]
      then
         # abort only if we have the semaphore
         if [ -f "$semaphore" -a ! -h "$semaphore" ]
         then
            command=abort
            stop_attempts=$abort_attempts
         else
            echo "Level Zero Processor in unknown mode"
         fi
      else
         # release semaphore
         if [ -f "$semaphore" -a ! -h "$semaphore" ]
         then
            /usr/bin/rm -f $semaphore 2>/dev/null
            echo "Level Zero Processor in manual mode"
         else
            echo "Level Zero Processor in unknown mode"
         fi
      fi
   else
      if [ "$native" = "true" ]
      then
         /usr/bin/crontab -l 1>/dev/null 2>/dev/null
         if [ $? = 0 ]
         then
            echo "Level Zero Processor in automatic mode"
         else
            echo "Level Zero Processor in manual mode"
         fi
      else
         echo "Level Zero Processor in unknown mode"
      fi
   fi
fi

if [ "$command" = "automatic" ]
then
   /usr/bin/crontab $crontable 2>/dev/null
   if [ $? = 0 ]
   then
      echo "Level Zero Processor in automatic mode"
   else
      # enter manual mode in case of error
      command=manual
   fi
fi

if [ "$command" = "stop" -o "$command" = "abort" ]
then
   if [ "$command" = "stop" ]
   then
      echo ""
      echo "Stopping Level Zero Processor for $username on $hostname"
      echo "----------------------------------------------------------------"
      while [ forever ]
      do
         echo "Waiting for semaphore..."
         /usr/bin/ln -s stop $semaphore 2>/dev/null
         if [ $? = 0 ]
         then
            trap "echo INTERRUPT; /usr/bin/rm -f $semaphore 2>/dev/null; exit 1" 1 2 3 15
            break
         fi
         trap "echo INTERRUPT; exit 1" 1 2 3 15
         sleep 1
         trap "" 1 2 3 15
      done
   else
      echo ""
      echo "Aborting Level Zero Processor for $username on $hostname"
      echo "----------------------------------------------------------------"
      /usr/bin/touch $semaphore 2>/dev/null
      trap "echo INTERRUPT; echo $semaphore; echo SEMAPHORE NOT REMOVED; exit 1" 1 2 3 15
   fi

   attempts=0
   process_list="PSC|PEP|PEI|PER|PTT|IDF"
   while [ forever ]
   do
      echo "Stopping IDF subsystem"
      echo "Stopping PTT subsystem"
      echo "Stopping PEP subsystem"
      pid_list=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
      | grep "$username " | egrep "$process_list" | grep -v grep | awk '{ print $2 " " }'`
      if [ ! "$pid_list" ]
      then
         break
      fi

      if [ "$attempts" -lt "$stop_attempts" ]
      then
         # request termination nicely
         kill="/usr/bin/kill -15 $pid_list"
      else
         # drop the nuclear warheads
         echo "Using SIGKILL signal"
         kill="/usr/bin/kill -9 $pid_list"
      fi
      $kill

      attempts=`expr $attempts + 1`
      sleep $stop_sleep
   done

   attempts=0
   process_list="RM|CAS|PAS|CGS|CSD|PPA|CGP"
   while [ forever ]
   do
      echo "Stopping PDP subsystem"
      pid_list=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
      | grep "$username " | egrep "$process_list" | grep -v grep | awk '{ print $2 " " }'`
      if [ ! "$pid_list" ]
      then
         break
      fi

      if [ "$attempts" -lt "$stop_attempts" ]
      then
         # request termination nicely
         kill="/usr/bin/kill -15 $pid_list"
      else
         # drop the nuclear warheads
         echo "Using SIGKILL signal"
         kill="/usr/bin/kill -9 $pid_list"
      fi
      $kill

      attempts=`expr $attempts + 1`
      sleep $stop_sleep
   done

   attempts=0
   process_list="activity_detail|dps_main|event_list|pdps_data_maint|product_gaps|product_list"
   process_list="$process_list|product_monitor|product_spec|product_spec_list|resource_monitor"
   process_list="$process_list|session_list|session_monitor"
   while [ forever ]
   do
      echo "Stopping GUI subsystem"
      pid_list=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
      | grep "$username " | egrep "$process_list" | grep -v grep | awk '{ print $2 " " }'`
      if [ ! "$pid_list" ]
      then
         break
      fi
 
      if [ "$attempts" -lt "$stop_attempts" ]
      then
         # request termination nicely
         kill="/usr/bin/kill -15 $pid_list"
      else
         # drop the nuclear warheads
         echo "Using SIGKILL signal"
         kill="/usr/bin/kill -9 $pid_list"
      fi
      $kill
 
      attempts=`expr $attempts + 1`
      sleep $stop_sleep
   done

   attempts=0
   process_list="lzp_process |lzp_replay |sw_sync |labview |sqlplus "
   while [ forever ]
   do
      echo "Stopping FE subsystem"
      pid_list=`/usr/5bin/ps -eo "user pid ppid tty etime comm" \
      | grep "$username " | egrep "$process_list" | grep -v grep | awk '{ print $2 " " }'`
      if [ ! "$pid_list" ]
      then
         break
      fi
 
      if [ "$attempts" -lt "$stop_attempts" ]
      then
         # request termination nicely
         kill="/usr/bin/kill -15 $pid_list"
      else
         # too sensitive for nukes
         echo "WARNING:  Sensitive processes not stopped"
         exitcode=3
         break
      fi
      $kill
 
      attempts=`expr $attempts + 1`
      sleep $stop_sleep
   done

   # release automation semaphore
   /usr/bin/rm -f $semaphore 2>/dev/null

   echo "Level Zero Processor is stopped"
fi

trap "" 1 2 3 15
if [ "$command" = "stop" -o "$command" = "abort" -o "$command" = "manual" ]
then
   /usr/bin/crontab -l 1>/dev/null 2>/dev/null
   if [ $? = 0 ]
   then
      /usr/bin/rm -f $crontable 2>/dev/null
      /usr/bin/crontab -l 1> $crontable 2>/dev/null
   fi
   /usr/bin/crontab -r 2>/dev/null
   echo "Level Zero Processor in manual mode"
fi

echo ""
exit $exitcode
