#! /bin/sh
#
# @(#)rmlpsstartup	1.6	LPS_UNX_COM	06/21/95
#
# Copyright 1995   Digital Equipment Corporation, Maynard, MA
#
# rmlpsstartup
#
# Standalone script to check for and optionally remove the Bourne shell
# commands used to startup all required LPS components at system boot
# time in a platform-specific manner.
#
#    usage:  rmlpsstartup [-q]
#
#    where:  -q  Optional "query" flag that allows the user to decline
#                the removal of the startup commands.  If this flag
#                is not specified, then removal will automatically
#                be performed.
#
# This script is structured into the following "phases":
#
#    Phase 1 - INITIALIZE   Initialize the environment, parse cmdline.
#    Phase 2 - CHECK        Check to see if removal already done.
#    Phase 3 - QUERY        Ask the user if removal should be done. 
#    Phase 4 - BUILD        Create new system startup file (if necessary)
#    Phase 5 - REMOVE       Remove required LPS startup commands.
#    Phase 6 - CLEANUP      Clean up and get out.
#
# The startup commands are removed from the proper system file or
# directory, based on the operating system type.  The platform type is
# automatically derived by this script from the LPS Object Database
# (/etc/lpsodb).
#
# /etc/lpsodb & lpsodblist must exist in /etc when you execute this script.
#
# Prior to removal, the original system file (if applicable) is
# preserved (usually renamed) and the user is informed of the path of
# the preserved file.
#
# If set for query, then if the user declines the removal, a mail
# message is sent to the "root" account describing the commands that must
# be removed from the given system file/directory to stop host-level
# startup of LPS components (most notably "lpsad", the Management Client
# daemon).
#
# Exit values:
#    0 - Returned if:
#           - The startup commands were not found, or
#           - The user did not possess sufficient privileges, or
#           - The user declined the removal.
#    1 - Returned if:
#           - A required system utility could not be found, or
#           - A required system utility returned an error, or
#           - The os name could not be resolved, or
#           - File access error of any kind was encountered.
#
# That is, an error value is returned if the removal should have
# been performed, but for some reason failed.  A success value does
# *not* imply the removal was successfully performed, only that
# all instructions were carried out (including the user indicating
# that the removal should not be performed).
#
###

#----------------------------------------------------------------------

# Phase 1 - INITIALIZE
#
# Set key environment variables.  Most can be set externally by
# the knowledgeable user.

set -a	# Automatically export all variables we create and/or modify

PATH=$PATH:/usr/ucb	# Needed for Solaris

SCRIPTNAME=`basename $0`

: ${CAT:=/bin/cat}
: ${CP:="/bin/cp"}
: ${ECHO:="echo"}
: ${ECHON:="echo -n"}
: ${GREP:=/bin/grep}
: ${HELP:=true}
: ${LOCALHOST:=`hostname`}
: ${LPSAD:=lpsad}
: ${LPSODB:=/etc/lpsodb}
: ${LPSODBLIST:=/etc/lpsodblist}
: ${MAILACCT:=root}
: ${MV:=/bin/mv}
: ${PAGER:=more}
: ${RM:=/bin/rm}
: ${SED:=/bin/sed}
: ${ED:=/bin/ed}
: ${TMPDIR:=/tmp}
: ${UNAME:=uname}

# Temporary files used here

LPSCMDSFILE=$TMPDIR/lpscmds.$$		# Complete set of LPS startup cmds
NEWSTARTUPFILE=$TMPDIR/newstart.$$	# Working copy of new startup file
TROUBLE=$TMPDIR/trouble.$$		# General use error log file

TMPFILES="$LPSCMDSFILE $NEWSTARTUPFILE $TROUBLE"

#----------------------------------------------------------------------

# Define some common functions

Error ()
{
    if [ "$*" ]
    then
	$ECHO ''            1>&2
	$ECHO "${SCRIPTNAME}: $*" 1>&2
    else
	$ECHO 1>&2
    fi

    return 1   # Ensures non-success value in case of simple "exit"
}

cleanup ()
{
    $RM -f $TMPFILES
}

# Setup activities to be executed upon encountering certain signals

trap 'echo ; \
      echo $SCRIPTNAME script terminating... ; \
      echo ; \
      echo LPS startup commands may not be completely installed. ; \
      echo ; \
      cleanup ; \
      exit 1' \
      1 2 3 15

#----------------------------------------------------------------------

# Parse and validate the command line, and ensure the user is 'root'.

error=false
cnt=$#

case $cnt in
    0 ) QUERY=false ;;
    1 ) if [ "$1" = "-q" ] ; then QUERY=true ; else error=true ; fi ;;
    * ) error=true ;;
esac

if $error
then
    Error "    usage: $SCRIPTNAME [-q]"
fi

# Ensure the user is running as 'root'

if /usr/bin/id | $GREP 'uid=0(' > /dev/null 2>&1
then
    :
else
    Error "    You must be running as 'root' to execute this script."
    error=true
fi

if $error
then
    Error
    exit 1
fi

#----------------------------------------------------------------------

# Determine if all required files are intact, checking as many as
# possible before we punt on an error.

ODB="LPS Object Database"

if [ ! -f $LPSODB ]
then
    Error "    The $ODB file '$LPSODB' does not exist!"
    error=true
fi

if [ -f $LPSODBLIST ]
then
    if [ -x $LPSODBLIST ]
    then
	DESC="LPS Management Client daemon"

	if LPSBIN=`$LPSODBLIST -f $LPSODB -e -v lpsbin`
	then
	    LPSADPATH=$LPSBIN/$LPSAD

	    if [ -f $LPSADPATH ]
	    then
		if [ ! -x $LPSADPATH ]
		then
		    Error "    The $DESC '$LPSADPATH' is not set as executable!"
		    error=true
		fi
	    else
		Error "    The $DESC '$LPSADPATH' does not exist!"
		error=true
	    fi
	else
	    Error "    Problem encountered with the $ODB file '$LPSODB'"
	    error=true
	fi
    else
	Error "    The $ODB list utility '$LPSODBLIST' is not set as executable!"
	error=true
    fi
else
    Error "    The $ODB list utility '$LPSODBLIST' does not exist!"

    cat 1>&2 << EOF
    The "lpsodblist" utility should at least exist with all other
    PrintServer software binaries in the directory as installed
    on this system.  You might want to search around on your system
    to locate where you installed the PrintServer software, then copy
    the "lpsodblist" utility to $LPSODBLIST and re-run this script.
EOF

    error=true
fi

if $error
then
    Error
    exit 1
fi

#----------------------------------------------------------------------

# Initialize common and platform-specific environment variables, etc.

LPSROOT=`$LPSODBLIST -f $LPSODB -e -v lpsroot`  # Path of LPS root directory
OSNAME=`$LPSODBLIST  -f $LPSODB -e -v osname` 	# Operating system name

PATH="$LPSROOT/scripts:$LPSBIN:$PATH"	# For LPS scripts & executables

CMDSEXIST=false     # Set true if LPS startup commands are found to exist
REASON="(unknown)"  # Text of reason why installation was not performed
PRESERVE=true	    # Controls perservation of modified system file(s)
LINKFILE=""	    # Symbolic link to real startup file
GID=system	    # Default group id for file ownership

case $OSNAME in
      "AIX" ) : ${STARTUPFILE:=/etc/rc.tcpip}
	      CMDPREFIX=""
	      ;;

     "DYNIX" ) : ${STARTUPFILE:=/etc/init.d/LPSstartup}
              CMDPREFIX=""
              #
              # For Sequent DYNIX/ptx we need to remove a symbolic
              # link to the actual startup file.
              #
              LINKFILE=/etc/rc2.d/S65LPSstartup
              PRESERVE=false
              GID=sys
              ;;
 
    "HP-UX" ) : ${STARTUPFILE:=/etc/rc}
	      : ${MAGICLINE:=": # do nothing instruction"}
	      CMDPREFIX="	"  # Contains a single TAB character!
	      ECHON=echon
	      ;;

     "IRIX" ) : ${STARTUPFILE:=/etc/init.d/LPSstartup}
	      CMDPREFIX=""
	      #
	      # For Silicon Graphics' IRIX we need to remove a symbolic
	      # link to the actual startup file.
	      #
	      LINKFILE=/etc/rc2.d/S65LPSstartup
	      PRESERVE=false
	      GID=sys
	      ;;

     "OSF1" ) : ${STARTUPFILE:=/sbin/init.d/LPSstartup}
	      CMDPREFIX=""
	      #
	      # For OSF/1 we need to remove a symbolic link to the
	      # actual startup file.
	      #
	      LINKFILE=/sbin/rc3.d/S99LPSstartup
	      PRESERVE=false
	      ;;

      "OSx" ) : ${STARTUPFILE:=/etc/init.d/LPSstartup}
              CMDPREFIX=""
              #
              # For Pyramid OSx we need to remove a symbolic
              # link to the actual startup file.
              #
              LINKFILE=/etc/rc2.d/S65LPSstartup
              PRESERVE=false
              GID=sys
              ;;

      "SCO" ) : ${STARTUPFILE:=/etc/rc2.d/S97LPSstartup}
	      CMDPREFIX=""
	      ;;

  "Solaris" ) : ${STARTUPFILE:=/etc/rc2.d/S82LPSstartup}
	      CMDPREFIX=""
	      ECHON=echon
              PRESERVE=false
	      ;;

    "SunOS" ) : ${STARTUPFILE:=/etc/rc.local}
	      CMDPREFIX=""
	      ;;

         * )  Error "This system does not appear to be supported by this script."
	      Error
	      exit 1
	      ;;
esac

#----------------------------------------------------------------------

# Create the temporary file containing the LPS startup commands.
#
#
# Note: the ${CMDPREFIX} stuff is a hack so as to allow for special
#       indentation when required to be a good platform "citizen".

$CAT << ENDOFINPUT > $LPSCMDSFILE

${CMDPREFIX}# Startup all LPS Management Client daemons
${CMDPREFIX}#
${CMDPREFIX}# These commands were created by $SCRIPTNAME
${CMDPREFIX}# on `date`
${CMDPREFIX}#
${CMDPREFIX}if [ -f $LPSODB -a -x $LPSODBLIST ]
${CMDPREFIX}then
${CMDPREFIX}    \`$LPSODBLIST -f $LPSODB -e -v lpsbin\`/$LPSAD -s
${CMDPREFIX}fi
ENDOFINPUT
FIRSTLINE="^${CMDPREFIX}# Startup all LPS Management Client daemons"
LASTLINE="^${CMDPREFIX}fi"
if [ $? -ne 0 ]
then
    Error "    Unable to create the temporary file for the startup commands."
    Error
    exit 1
fi

#----------------------------------------------------------------------

# mailhelp() - A common function for mailing "help" information
#
# The REASON variable should already be set appropriately.

mailhelp ()
{
    mail $MAILACCT << ENDOFINPUT
On `date` the script '$SCRIPTNAME' was
executed in an attempt to remove the shell commands used
to automatically start up all defined PrintServer Software
Management Client daemons every time '$LOCALHOST' is started.

The installation of these critical commands was NOT performed.

Reason installation was not performed:  $REASON

As a result, '$LOCALHOST' will still attempt to automatically
start all PrintServer Software Management Client
daemons whenever '$LOCALHOST' is started.

			[end of message]
ENDOFINPUT

    return 0
}

#----------------------------------------------------------------------

# Phase 2 - CHECK
#
# Check to make sure that the startup commands already exist, if not 
# then exit.
#
# All platforms have the same requirement:  to search for a specific,
# common string containing key LPS path components.  If the search
# fails, then immediately processing is done on a platform-specific basis.
#
# If the search fails, then we're done and can go home.  We zap our
# temporary files, perform cleanup, and exit.
#
# Note the special handling required when a symbolic link is necessary.

$ECHO
$ECHO "    Checking for automatic startup of Management Clients at boot time..." 
found=false

SEARCHSTR="${LPSODB}.*${LPSODBLIST}"	# Common LPS search string

if $GREP "$SEARCHSTR" $STARTUPFILE > /dev/null 2>&1
then
    if [ "$LINKFILE" ]				    # Symbolic link required?
    then
	if ls $LINKFILE > /dev/null 2>&1	    # Link file exist?
	then
	    if ls -L $LINKFILE > /dev/null 2>&1	    # Linked to a real file?
	    then
		if diff $STARTUPFILE $LINKFILE 2>&1 # Link points to our file?
		then
		    found=true
		fi
	    fi
	fi
    else
	found=true
    fi
fi

if [ $found = false ]
then
    $ECHO
    $ECHO "    No LPS startup commands to remove."
    $ECHO

    cleanup

    exit 0
fi

#----------------------------------------------------------------------

# Phase 3 - QUERY
#
# If $QUERY mode is set, ask the user if the installation should be
# performed.  If the user declines, mail a warning message and exit.

if $QUERY
then
    if yesno y "    Remove the required LPS startup commands"
    then
	:
    else
	REASON="User declined the removal."

	$ECHO
	$ECHO "    The LPS startup commands found in the file"
	$ECHO "    '$STARTUPFILE' will not be removed."
	$ECHO

	mailhelp

	cleanup

	exit 0
    fi
fi

#----------------------------------------------------------------------

# Phase 4 - BUILD
#
# This phase is only meaningful if the LPS startup commands have been
# merged into an existing system startup file, the fact of which is
# controlled by the PRESERVE shell variable being set to "true".
#
# Make a copy of the existing system startup file, then remove the
# LPS startup commands from that file.
#
# All commands should redirect stderr to the $TROUBLE file to facilitate
# common error handling.

if $PRESERVE
then
    $ECHO "    Preserving existing startup file '$STARTUPFILE'..."

    if savefile -V -p -s ".OLD" $STARTUPFILE 2> $TROUBLE
    then
	OLDSTARTUPFILE="${STARTUPFILE}.OLD.0" # Created by "savefile" utility
    else
	Error "    Preserving the existing system startup file has failed:"
	$CAT $TROUBLE 1>&2

	if yesno x "    Continue with the removal anyway"
	then
	    $ECHO "    Continuing the removal..."
	else
	    REASON="While attempting to preserve
the existing system startup file '$STARTUPFILE'
the following errors were encountered:

    `$CAT $TROUBLE`
"
	    mailhelp
	    cleanup
	    exit 1
	fi
    fi

    rm -f $NEWSTARTUPFILE

    $ECHO "    Creating a working copy of the startup file in '$NEWSTARTUPFILE'..."

    FAILURE=true	# Assume the worst up front

    case $OSNAME in
	"AIX" | "HP-UX" | "SunOS" ) :
	       # File building involves appending the LPS commands
	       # to the end of the system startup file.

	       $CAT << ENDOFINPUT > $LPSCMDSFILE
/$FIRSTLINE/
.-1,/$LASTLINE/d
w
q
ENDOFINPUT

		cp $STARTUPFILE $NEWSTARTUPFILE
		if $ED $NEWSTARTUPFILE < $LPSCMDSFILE 1> /dev/null 2> $TROUBLE
		then
		    FAILURE=false
		fi
		;;

	    * ) $ECHO "    Invalid operating system: \"$OSNAME\"" >> $TROUBLE
		;;
    esac

    if $FAILURE
    then
	Error "    The removal has failed due to the following errors:"
	$CAT $TROUBLE

	REASON="Failure to create the working copy of the
system startup file '$NEWSTARTUPFILE' due to:
`$CAT $TROUBLE`
"
    fi
fi

#---------------------------------------------------------------------

# Phase 5 - REMOVE
#
# Perform the removal of the LPS automatic startup commands
# based on whether the PRESERVE shell variable is set to:
#
#    "true"	Modify an existing system file
#    "false"	Simply remove the startup file (and a potential link file)

rmlinkfile ()
{
    rc=0

    if [ "$LINKFILE" ]		# A symbolic link to delete?
    then
       $ECHO "    Deleting the symbolic link '$LINKFILE'..."

	if rm $LINKFILE 2>> $TROUBLE
	then
	    :
	else
	    msg="Failure to delete the symbolic link \"$LINKFILE\""
	    $ECHO "    $msg" >> $TROUBLE
	    rc=1
	fi
    fi

    return $rc
}


FAILURE=false			# Flag to indicate overall success/failure

if $PRESERVE
then
    $ECHO "    Updating the system startup file '$STARTUPFILE'..."

    RESTORE=true		# Flag to restore the startup file

    # Copy the working file to the actual startup file, checking for errors
    # along the way.

    if $CP $NEWSTARTUPFILE $STARTUPFILE 2> $TROUBLE
    then
	:
    else
	FAILURE=true
    fi
else
    $ECHO "    Deleting the system startup file '$STARTUPFILE'..."

    if (rm $STARTUPFILE 2> $TROUBLE) && rmlinkfile
    then
	:
    else
	FAILURE=true
	RESTORE=false
	msg="delete"
   fi
fi

# Here we check for a failure condition and possible restoration of the
# original file.
#
# Since we're very near the end of the script, we do NOT exit upon
# failure; rather, we set the final exit value (and any other variables
# if we've failed), then fall thru to the final CLEANUP section.

if $FAILURE
then
    Error "    The removal has failed due to the following errors:"
    $CAT $TROUBLE

    EXITVALUE=1
    SENDHELP=true
    REASON="Failure to copy the new version of the
system startup file '$NEWSTARTUPFILE' to '$STARTUPFILE'
due to:
    `$CAT $TROUBLE`
"
    # Restore the original startup file, if necessary

    if $RESTORE
    then
	$ECHO
	$ECHO "    Restoring the original system startup file..."

	if $CP $OLDSTARTUPFILE $STARTUPFILE
	then
	    $ECHO "    Original system startup file restored."
	    $ECHO
	else
	    cat << ENDOFINPUT
    WARNING!  The original system startup file could not be restored.
              That file was previously saved as '$OLDSTARTUPFILE'.
ENDOFINPUT
	    pause
	    EXITVALUE=1
	fi
    fi
else
    $ECHO
    $ECHO "    The removal of the LPS startup commands was successful."
    $ECHO
    SENDHELP=false
    EXITVALUE=0
fi

#----------------------------------------------------------------------

# Phase 6 - CLEANUP
#
# Send an informative mail message if required

if $SENDHELP
then
    mailhelp
fi

# Zap all temporary files and exit with the resolved value

cleanup

exit $EXITVALUE

#----------------------------------------------------------------------

# Emacs editing parameters
# Local Variables:
# page-delimiter:"^#---"
# fill-column:75
# End:
