#!/bin/ksh -p
#
# ident "@(#)utrestart.ksh	1.7 02/10/17 SMI"
#
# Copyright 2002 Sun Microsystems, Inc.  All rights reserved.
#
umask 022
PROG=$0
PATH=/bin:/usr/bin:/opt/SUNWut/sbin
export PATH
BASE=`pkginfo -r SUNWuto 2>/dev/null`
SUNWUT=$BASE/SUNWut
SUNWUTSBIN=$SUNWUT/sbin
SUNWUTLIB=$SUNWUT/lib
SUNWUTETC=/etc/opt/SUNWut
SUNWUTLOG=/var/opt/SUNWut/log
SUNWUTPROCDIR=/tmp/SUNWut/session_proc
SUNWUTTOKENS=/var/opt/SUNWut/tokens
SUNWUTXLOCK=/etc/dt/config/config.lock
TMP=/var/opt/SUNWut/tmp/utrestart.log.$$

#
# Functions
#

#
# Command syntax
#
function usage {
        typeset ecode=${1:-99}
        typeset message=${2:-}
        if [[ -n "$message" ]]
        then
                print -u2 -- ERROR: $message
        fi
        cat <<!
Usage:
${0##*/}
${0##*/} -c
${0##*/} -h

        			# Restart/init SunRay services.
				# With no options the sessions are left intact.
        -c                      # Clears out all existing sessions.

        -h                      # Print this message.

!
        exit $ecode
}

#
# Return pid of named process in argument
#
pidproc() {
        /usr/bin/ps -u root -o pid -o args |
                /usr/bin/grep -w "$1" |
                /usr/bin/grep -v grep |
                /usr/bin/sed -e 's/^  *//' -e 's/ .*//'
}

checkAndStartDaemons() {
        ${SUNWUTLIB}/utauthd -e
	SLEEP=5

	sleep $SLEEP

	#
        # Clean up old lock files from utdtsession
        #
        /bin/find $SUNWUTTOKENS -type f \
                -name '*.lock' -print | /bin/xargs /bin/rm -f
        rm -f $SUNWUTXLOCK

        PIDS=`pidproc utsessiond`
        if [ -z "$PIDS" -a -x ${SUNWUTLIB}/utsessiond ];
        then

		(
			cd ${SUNWUTLOG}

			auth_permit=${SUNWUTETC}/auth.permit
			if [ -f ${auth_permit} ]
			then
				autharg="-c ${auth_permit}"
			else
				autharg=""
			fi

			/bin/priocntl -e -c TS -p 30 -m 30 \
				${SUNWUTLIB}/utsessiond -r ${autharg} \
				< /dev/null > /dev/null 2>&1 &
		)
        fi

        PIDS=`pidproc utdevmgrd`
        if [ -z "$PIDS" -a -x ${SUNWUTLIB}/utdevmgrd ];
        then
                (
                        cd ${SUNWUTLOG}

                        auth_permit=${SUNWUTETC}/auth.permit
                        if [ -f ${auth_permit} ]
                        then
                                autharg="-c ${auth_permit}"
                        else
                                autharg=""
                        fi

                        ${SUNWUTLIB}/utdevmgrd -r ${autharg} \
                                < /dev/null > /dev/null 2>&1 &
                )
        fi

        PIDS=`pidproc utparalleld`
        if [ -z "$PIDS" -a -x ${SUNWUTLIB}/utparalleld ]; 
	then
                ${SUNWUTLIB}/utparalleld -r < /dev/null > /dev/null 2>&1 &
        fi

        PIDS=`pidproc utseriald`
        if [ -z "$PIDS" -a -x ${SUNWUTLIB}/utseriald ]; 
	then
                ${SUNWUTLIB}/utseriald -r < /dev/null > /dev/null 2>&1 &
        fi

	PIDS=`pidproc utwsd`
        if [ -z "$PIDS" -a -x /etc/init.d/utws ]; 
	then
                /etc/init.d/utws start < /dev/null > /dev/null 2>&1 &
        fi

        PIDS=`pidproc utdsd`
        if [ -z "$PIDS" -a -x /etc/init.d/utds ]; 
	then
                /etc/init.d/utds start < /dev/null > /dev/null 2>&1 &
        fi

	if [ -f ${SUNWUTETC}/auth.props -a -x ${SUNWUTLIB}/utauthd ]; then
                here=`pwd`
                cd ${SUNWUTLOG}
                ${SUNWUTLIB}/utagelog auth_log 9
                /usr/bin/nohup \
                /bin/priocntl -c TS -p 30 -m 30 -e \
                        ${SUNWUTLIB}/utauthd -b > auth_log 2>&1 </dev/null &
                cd $here
        fi

}

function purgeAndRestart {

            # User might execute the -c when on a sunray box. Though the message displayed
            # will be too quick to see, the warning is still given.

            if [[ -n "${CORONA_TOKEN:-}" ]]
            then
                  print "Your session will also be terminated as the command executes."
		  sleep 5
            else
                  print "Restarting servers... messages will be logged to $SUNWUTLOG/messages."
            fi

        #
        # Prevent utrestart to recurse forever. Setting RECURSE=STOP before the program
        # as a terminating condition
        #
            if [[ -z "${RECURSE:-}"  ]]
            then
                  (nohup  /bin/ksh -p -c "RECURSE=STOP $PROG -c " > /dev/null 2>&1 </dev/null &)
            else
                  # The output will be logged to messages
                  exec > $TMP 2>&1

                  print "Restarting services."

                  /etc/init.d/utsvc stop

                  DISPS_TO_KILL=`listNonDtloginDisplays`
                  PIDS_TO_KILL=`identifyNonDtloginSessions $DISPS_TO_KILL`

                  # Kill the non-dtlogin sessions
                  [[ ! -z ${PIDS_TO_KILL} ]] && kill -9 -- ${PIDS_TO_KILL} 2>/dev/null

                  #
                  # Clean out the SunRay sessions configuration
                  # (utacleanup with no arg does this unconditionally)
                  #
                  /etc/init.d/utacleanup
                  [[ -x /etc/init.d/bbinit ]] && /etc/init.d/bbinit cleanup

                  # Let parent dtlogin kill the outstanding dtlogin sessions
                  kill -HUP $(/bin/cat /var/dt/Xpid)

		  # make sure that SRDS daemon is running (if needed) 
		  if ! ps -e -o comm | grep /opt/SUNWut/srds/lib/utdsd > /dev/null; then 
			[[ -x /etc/init.d/utds ]] && /etc/init.d/utds start > /dev/null 2>&1 
		  fi 

		  # make sure that SRAS daemon is running (if needed) 
		  if ! ps -e -o comm | grep /opt/SUNWut/http/lib/utwsd > /dev/null; then 
			[[ -x /etc/init.d/utws ]] && /etc/init.d/utws start > /dev/null 2>&1 
		  fi 

		  print "\nRestarting SunRay services"

		  (/etc/init.d/utsvc start ) >/dev/null 1>&2

                  logger -f $TMP -p user.info -t UTPOLICY

                  # clean up temp file after messages are logged
                  [ -w $TMP ] && /bin/rm $TMP
		  exit 0
             fi
}

# listNonDtloginDisplays

function listNonDtloginDisplays {
        if [[ -d $SUNWUTPROCDIR ]]
        then
                ( cd $SUNWUTPROCDIR &&
                /bin/nawk -F= '
                $1 == "program" && $2 != "/usr/dt/bin/dtlogin" { print FILENAME }
                ' * 2>/dev/null )
        fi
}

# identifyNonDtloginSessions
# Output the pids for the current non-dtlogin sessions

function identifyNonDtloginSessions {
        # find the session_proc files not related to dtlogin
        NON_DTLOGIN_DISPS=$*

        # Verify each session_proc is valid: doesn't predate display file
        for DISP in $NON_DTLOGIN_DISPS; do
                SPFILE=$SUNWUTPROCDIR/$DISP
                DPYFILE=/var/opt/SUNWut/displays/$DISP

                if [[ -f $SPFILE ]] && [[ -f $DPYFILE ]] \
                    && [[ ! $SPFILE -ot $DPYFILE ]]
                then
                        # It's valid - output the pid
                        # Note: utxexec switches itself to a process group leader,
                        # so use negative pid to kill the entire group for
                        # efficiency
                        print -n -- `sed -n -e 's/^pid=/-/p' \
                                    -e 's/^server_pid=//p' $SPFILE` " "
                fi
        done
}

function justRestart {

	print "Resetting servers... messages will be logged to $SUNWUTLOG/messages."
	
	checkAndStartDaemons

        exit 0
}
               
function mustBeRoot {
        if [[ "$(/usr/xpg4/bin/id -u)" != "0" ]]
        then
                Error 1 "Must be root to reset/restart services."
        fi
}

function Error {
        typeset ecode=${1:-99}
        typeset message=${2:-}
        if [[ -n "$message" ]]
        then
                print -u2 -- ERROR: $message
        fi
        exit $ecode
}


#
# Main program
#


#
# No argument on cmd line, simply print error and exit
#

mustBeRoot

if [ $# -eq 0 ]
then
  justRestart
fi

if [ $# -gt 1 ]
then
        usage 1 "Invalid or extraneous arguments on command line: $*"
fi

UT_OPTIONS=$@
while getopts ch c $UT_OPTIONS 2>/dev/null
do
	case $c in
	(c)    	purgeAndRestart
		;;
	(h)     usage 0
                ;;
        (\?)
                if [[ "$1" != "-?" ]]
                then
                        usage 1 "Invalid option: $1";
                else
                        usage 1
                fi
        esac
done

