#! /bin/sh
#
#  Name:
#     lmdown   script file for gracefully shutting down FLEXlm License Manager
#
#  Usage:
#     lmdown [-c licensefile] [-l logfile] [-m marker]
#
#  Description:
#     lmdown shuts down the MATLAB FLEXlm License Manager in a graceful manner.
#
#  Options:
#
#     -c licensefile
#
#           Path of the license file.
#           DEFAULT: $MATLAB/etc/license.dat
#
#     -l logfile
#
#           Path of the log file.
#           DEFAULT: /usr/adm/license.log4  (except sol2)
#                    /usr/sadm/license.log4 (sol2 only)
#
#     -m marker
#
#           Marker string used to build the link names.  The marker string
#           should contain the string 'lm' so you can grep on the output of
#           the 'ps' command using 'lm' as the search string.
#           DEFAULT: lm_TMW4
#
#  Copyright (c) 1986-95 by The MathWorks, Inc.
#  $Revision: 1.20 $  $Date: 1995/05/01 16:11:35 $
#__________________________________________________________________________
#
#**************************************************************************
# Determine the path of the MATLAB root directory - always one directory
# up from the path to this command.
#**************************************************************************
#
    filename=$0
#
# Now it is either a file or a link to a file.
#
    cpath=`pwd`
#
# Follow up to 8 links before giving up. Same as BSD 4.3
#
    n=1
    maxlinks=8
    while [ $n -le $maxlinks ]
    do
#
# Get directory correctly!
#
	newdir=`echo "$filename" | awk '
                        { tail = $0
                          np = index (tail, "/")
                          while ( np != 0 ) {
                             tail = substr (tail, np + 1, length (tail) - np)
                             if (tail == "" ) break
                             np = index (tail, "/")
                          }
                          head = substr ($0, 1, length ($0) - length (tail))
                          if ( tail == "." || tail == "..")
                             print $0
                          else
                             print head
                        }'`
	if [ ! "$newdir" ]; then
	    newdir="."
	fi
	(cd $newdir) > /dev/null 2>&1
	if [ $? -ne 0 ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo 'Internal error 1: We could not determine the path of the'
    echo '                  MATLAB root directory.'
    echo ''
    echo "                  original command path = $0"
    echo "                  current  command path = $filename"
    echo ''
    echo '                  Please contact:'
    echo '' 
    echo '                      MathWorks Technical Support'
    echo ''
    echo '                  for further assistance.'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    exit 1
	fi
	cd $newdir
#
# Need the function pwd - not the built in one
#
	newdir=`/bin/pwd`
#
	newbase=`expr //$filename : '.*/\(.*\)' \| $filename`
        lscmd=`ls -l $newbase 2>/dev/null`
	if [ ! "$lscmd" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo 'Internal error 2: Could not determine the path of the'
    echo '                  MATLAB root directory.'
    echo ''
    echo "                  original command path = $filename"
    echo "                  current  command path = $filename"
    echo ''
    echo '                  Please contact:'
    echo '' 
    echo '                      MathWorks Technical Support'
    echo ''
    echo '                  for further assistance.'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    exit 1
	fi
#
# Check for link portably
#
	if [ `expr "$lscmd" : '.*->.*'` -ne 0 ]; then
	    filename=`echo "$lscmd" | awk '{ print $NF }'`
	else
#
# It's a file
#
	    dir="$newdir"
	    command="$newbase"
#
	    cd $dir/..
	    MATLAB=`/bin/pwd`; export MATLAB
	    break
	fi
        n=`expr $n + 1`
    done
    if [ $n -gt $maxlinks ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo 'Internal error 3: More than $maxlinks links in path to'
    echo "                  this script. That's too many!"
    echo ''
    echo "                  original command path = $filename"
    echo "                  current  command path = $filename"
    echo ''
    echo '                  Please contact:'
    echo '' 
    echo '                      MathWorks Technical Support'
    echo ''
    echo '                  for further assistance.'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	exit 1
    fi
#	
    cd $cpath
#
#**************************************************************************
#
    . $MATLAB/etc/util/arch.sh
    if [ "$Arch" = "unknown" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo '    Sorry! We could not determine the machine architecture for your'
    echo '           host. Please contact:'
    echo '' 
    echo '               MathWorks Technical Support'
    echo ''
    echo '           for further assistance.'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        exit 1
    elif [ "$Arch" = "lnx86" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo '    lmdown is not supported or required on Linux.'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        exit 1
    fi
#
    . $MATLAB/etc/util/whichps.sh
#
    (cd $MATLAB/etc/$Arch) > /dev/null 2>&1
    if [ $? -ne 0 ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo "    Sorry! License manager directory MATLAB/etc/$Arch does not exit."
    echo ''
    echo "           MATLAB = $MATLAB"
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        exit 1
    fi
#
    licensefile=$MATLAB/etc/license.dat
    if [ $Arch != "sol2" ]; then
        lmlogfile=/usr/adm/license.log4
    else
        lmlogfile=/usr/sadm/license.log4
    fi
    marker="lm_TMW4"
#
    set_licensefile="FALSE"
#
# Parse the arguments
#
#     -c licensefile
#     -l logfile
#     -m marker
#
    stat="OK"
    while [ "$stat" = "OK" -a  $# -gt 0 ]; do
        case "$1" in
            -c)
                shift
                if [ $# -gt 0 ]; then
                    case "$1" in
                        -*)
                            stat=""
                            ;;
                         *)
                    	    licensefile="$1"
                    	    shift
                    	    set_licensefile="TRUE"
                            ;;
                    esac
                else
                    stat=""
                fi
                ;;
            -l)
                shift
                if [ $# -gt 0 ]; then
                    case "$1" in
                        -*)
                            stat=""
                            ;;
                         *)
                            lmlogfile="$1"
                            shift
                            ;;
                    esac
                else
                    stat=""
                fi
                ;;
            -m)
                shift
                if [ $# -gt 0 ]; then
                    case "$1" in
                        -*)
                            stat=""
                            ;;
                         *)
                            marker="$1"
                            shift
                            ;;
                    esac
                else
                    stat=""
                fi
                ;;
             *)
                stat="";
                ;;
        esac
    done
    if [ "$stat" = "" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   echo ''
   echo '    Usage: lmdown [-c licensefile] [-l logfile] [-m marker]'
   echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        exit 1
    fi
#
    if [ $set_licensefile = "FALSE" -a ! -f $MATLAB/etc/license.dat ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo '    Sorry! No license.dat file found in MATLAB/etc directory.'
    echo ''
    echo "           MATLAB = $MATLAB"
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        exit 1
    elif [ $set_licensefile = "TRUE" -a ! -f $licensefile ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo '    Sorry! License file does not exist.'
    echo ''
    echo "           file = $licensefile"
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        exit 1
    fi
#
    (cat /dev/null >> $lmlogfile) 2>/dev/null
    if [ $? -ne 0 ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo '    Sorry! Cannot write in log file.'
    echo ''
    echo "           file = $lmlogfile"
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        exit 1
    fi
#
#------------------------------------------------------------------------------
# MANUALLY kill any daemons ----
#------------------------------------------------------------------------------
# 1. verify that you are on the right host - if not error
# 2. get the processes to stop
# 3. kill processes - output message to tell user what is happening.
#
# Get the local hostid by calling lmhostid.
# Get the hostid's from the license.dat file and see if one matches
#
   localhostid=`$MATLAB/etc/lmhostid | sed -e "1d" -e '2s/^[^"]*"//' -e '2s/".*//'`
   lmfilehostids=`cat $licensefile | awk '/SERVER/ {print $3}'`
   found=0
   for i in $lmfilehostids
   do
	if [ "$localhostid" = "$i" ]; then
	    found=1
	    break
	fi
   done 
   if [ "$found" = "0" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo '    Sorry! According to your license.dat file this host'
    echo '           with hostid:'
    echo ''
    echo "               $localhostid"
    echo ''
    echo '           does not match any SERVER hostid. The SERVER lines are'
    echo ''
    echo '-----------------------------------------------'
    grep SERVER $licensefile
    echo '-----------------------------------------------'
    echo ''
    echo '           You must be on one of the SERVER hosts to perform this'
    echo '           license manager operation!'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	exit 1
    fi
#
    searchstr="(/usr/tmp/$marker.dat)"
    if [ "$psCmdSysV" = "FALSE" ]; then
#
# BSD version:
#
	ps agx | egrep $searchstr | awk '
                      { if (index($0,"egrep") == 0) print $1, $5 }' > /tmp/$$a
    else
#
# System V version:
#
        ps -ef | egrep $searchstr | awk '
                      { if (index($0,"egrep") == 0) print $2, $8 }' > /tmp/$$a
    fi
#
    npids=`wc -l /tmp/$$a | awk '{ print $1 }'`
    npids=`expr "$npids" + 0`
    bad=0
#
    if [ $npids -ne 0 ]; then
#
#----------------------------------------------------------------------------
#
# Build timestamp from output of UNIX date function. Does not work
# for Apollo Aegis. Needed for output to logfile.
#
# Example:	Sun Dec  6 09:23:44 EST 1992
#
        d=`date`
	timestamp=`echo "$d" | awk '
			BEGIN { month["jan"] = month["Jan"] = " 1"
				month["feb"] = month["Feb"] = " 2"
			        month["mar"] = month["Mar"] = " 3" 
			        month["apr"] = month["Apr"] = " 4" 
			        month["may"] = month["May"] = " 5" 
			        month["jun"] = month["Jun"] = " 6" 
			        month["jul"] = month["Jul"] = " 7" 
			        month["aug"] = month["Aug"] = " 8" 
			        month["sep"] = month["Sep"] = " 9" 
			        month["oct"] = month["Oct"] = "10" 
			        month["nov"] = month["Nov"] = "11" 
			        month["dec"] = month["Dec"] = "12" } 
				{ split ($4, time, ":")
				   printf ("%2s/%02d %2d:%02d", month[$2], $3, time[1], time[2])}'`
#
#----------------------------------------------------------------------------
#
# kill the daemons - include hostname to remind the user
#
        hostname=`egrep "$localhostid" $licensefile | awk '{ if ($1 == "SERVER") print $2 }'`
#
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo "    Killing license manager daemon processess . . . ($hostname)"
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# Kill lmgrd's first - There should be only one, but there could be
#		       several if things get out of hand. They can be
#		       killed in any order.
#
	(while read pid pname
	 do
	    if [ "$pname" = "/usr/tmp/$marker.ld" ]; then
		msg=`kill -9 $pid 2>&1`
	        if [ "$msg" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "    Sorry! message returned by 'kill -9' for process id = $pid (lmgrd)"
    echo "           $msg"
    echo "$timestamp (lmdown) process id = $pid . . . (lmgrd) - $msg" >> $lmlogfile
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		    bad=1
	        else
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "    process id = $pid killed . . . (lmgrd)"
    echo "$timestamp (lmdown) process id = $pid . . . (lmgrd) - killed" >> $lmlogfile
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		fi
	    fi
	done) < /tmp/$$a
#
# Kill vendor daemons next - kill them in any order since their parents are
#			     dead
#
	(while read pid pname
	 do
	    if [ "$pname" != "/usr/tmp/$marker.ld" ]; then
		msg=`kill -9 $pid 2>&1`
	        if [ "$msg" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "    Sorry! message returned by 'kill -9' for process id = $pid ($pname)"
    echo "           $msg"
    echo "$timestamp (lmdown) process id = $pid . . . ($pname) - $msg" >> $lmlogfile
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		    bad=1
	        else
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "    process id = $pid killed . . . ($pname)"
    echo "$timestamp (lmdown) process id = $pid . . . ($pname) - killed" >> $lmlogfile
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		fi
	    fi
	done) < /tmp/$$a
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
	rm -f /tmp/$$a > /dev/null 2>&1
#
    else
#
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo '    No license manager daemons running . . .'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
	rm -f /tmp/$$a > /dev/null 2>&1
#
    fi
#
# Remove the lockfile and all marker files in any case.
#
    rm -f /usr/tmp/lockMLM4 /usr/tmp/$marker.dat /usr/tmp/$marker.ld /usr/tmp/$marker.vd* > /dev/null 2>&1
#
# Remove /usr/tmp/lmdown link for sgi
#
    if [ "$Arch" = "sgi" ]; then
        rm -f /usr/tmp/lmdown > /dev/null 2>&1
    fi
#
    if [ "$bad" = "0" ]; then
	exit 0
    else
	exit 1
    fi
