#!/bin/sh
#
# Setup environment for running SMARTS programs
#
# Copyright (C) 1995-2007, EMC Corporation ("EMC")
# All Rights Reserved
#
# RCS $Id: //depot/ECOM/gold/common/runcmd#2 $
prepend() {
    VAR=$1
    shift
    for DIR
    do
    	eval "case \$$VAR in
		'') $VAR=$DIR ;;
		*) $VAR=$DIR:\$$VAR ;;
	      esac"
    done
}

append() {
    VAR=$1
    shift
    for DIR
    do
	eval "case \$$VAR in
		'') $VAR=$DIR ;;
		$DIR) : ;;
		$DIR:*) : ;;
		*:$DIR) : ;;
		*:$DIR:*) : ;;
		*) $VAR=\$$VAR:$DIR ;;
	      esac"
    done
}

appendJava() {
    VAR=$1
    shift
    PREFIX=$1
    shift
    for DIR
    do
        case $PREFIX in
	    '') append $VAR $DIR  ;;
	    *)  append $VAR $PREFIX/$DIR ;;
	esac
    done
}

cleanpath() {
    VAR=$1
    eval "VALUE=\$$VAR"

    #eliminate any ../ in the "path"
    NEW=`echo $VALUE | sed -e 's:/[^/.][^/]*/\.\.::g'` 
    while [ "$NEW" != "$VALUE" ] ; do
	VALUE="$NEW"
	NEW=`echo $VALUE | sed -e 's:/[^/.][^/]*/\.\.::g'`    
	done

    # eliminate any ./ in the resulting path
    NEW=`echo $VALUE | sed -e 's:/\./:/:g'` 
    while [ "$NEW" != "$VALUE" ] ; do
	VALUE="$NEW"
        NEW=`echo $VALUE | sed -e 's:/\./:/:g'`
        done
	
    eval "$VAR=$NEW"
}

# Locate program's option file if any and process.
#
# For now we export all from the options file.  While we do not 
# need this, if the application crashes we can see the variables in the
# log file.
processAppOptions() {
    PROG=$1
    RAWPATH="$2:"
    CANDIDATE=`expr "$RAWPATH" : '\([^:]*\):.*'`
    RAWPATH=`expr "$RAWPATH" : '[^:]*:\(.*\)'`
    while [ -n "$CANDIDATE" ]; do
        if [ -f "$CANDIDATE/bin/system/$PROG.options" ]; then
	    set -a
            . "$CANDIDATE/bin/system/$PROG.options"
	    set +a
	    return
        fi
        CANDIDATE=`expr "$RAWPATH" : '\([^:]*\):.*'`
        RAWPATH=`expr "$RAWPATH" : '[^:]*:\(.*\)'`
    done
}

javaSpecified() {
    ARGS="$*";
    for arg in $ARGS; do
        if [ "`echo ${arg} | cut -c1-6`" = "--java" ]; then
	    seventh="`echo ${arg} | cut -c7`"
	    if [ "$seventh" = "=" ] || [ "$seventh" = "" ]; then
	        javaEnabled="YES"
	    fi
	fi
    done
}

# Locate a file
#
# ARG1 is file name.
# ARG2 is DIRECTORY which is applied to SM_HOME, SM_DEFHOME
# ARG3 is extra search path, the DIRECTORY  is not applied
#         is optional
#
# shell variable LOCATEDFILE is full path to file or "" if not found
locateFile() {
    FILENAME="$1"
    DIRECTORY="$2"
    LOCATEDFILE=""
    RAWPATH="$3:${SM_HOME}/${DIRECTORY}:"
    if [ -n "$SM_DEFHOME" ]; then
        RAWPATH="${RAWPATH}${SM_DEFHOME}/${DIRECTORY}:"
    fi
    while [ -n "$RAWPATH" ]; do
	CANDIDATE=`expr "${RAWPATH}" : '\([^:]*\):.*'`
	RAWPATH=`expr "${RAWPATH}" : '[^:]*:\(.*\)'`
	if [ -n "${CANDIDATE}" ] && [ -f "${CANDIDATE}/${FILENAME}" ]; then
	    LOCATEDFILE="${CANDIDATE}/${FILENAME}"
	    return
        fi
    done
}

#
# Some systems (HP/UX) decide we're in a restricted shell, and refuse to
# allow the shell builtin pwd to be redefined.  Instead, we define PWD (to
# be a path-independent pwd), and all code here *must* use PWD, not pwd.
PWD() { if [ `/bin/uname` = "VMkernel" ]; then pwd; else /bin/pwd; fi }

cat() { /bin/cat ${1+"$@"}; }

# Most systems have /bin/expr, but not Linux.  However, all our current
# platforms have /usr/bin/expr.
expr() { /usr/bin/expr ${1+"$@"}; }

# Most systems have /bin/logger, but not Linux.  However, all our current
# platforms have /usr/bin/logger.
logger() { /usr/bin/logger ${1+"$@"}; }

ln() { /bin/ln ${1+"$@"}; }

ls() { /bin/ls ${1+"$@"}; }

rm() { /bin/rm ${1+"$@"}; }

# 
# Do all the actually setting of LPVAR and LD_PRELOAD here
#
setup_lpvar() {
	_x=
	for D in `echo ${SITEMOD} | sed -e 's;:; ;g'`
	do
	    if [ -d $D/lib ]; then
		append _x $D/lib
	    fi
	done
	if [ -n "$_x" ]; then
	    prepend $LPVAR $_x
	    for i in $LPVAR_OPT
	    do
	        prepend $i $_x
            done
	fi

 	if [ -n "$AT_SMARTS" ]; then
 	    if [ -d $SM_HOME/local/slib ]; then
 		append $LPVAR $SM_HOME/local/slib
	        for i in $LPVAR_OPT
	        do
	            append $i $SM_HOME/local/slib
                done
	    fi
        fi

	append $LPVAR $SM_HOME/lib
	for i in $LPVAR_OPT
	do
	    append $i $SM_HOME/lib
        done
	if [ -n "$AT_SMARTS" ]; then
	    append $LPVAR $SM_HOME/slib
	    for i in $LPVAR_OPT
    	    do
	        append $i $SM_HOME/slib
            done
	fi
	if [ -n "$HAVEDEF" ]; then
	    if [ -d $SM_DEF/local/lib ]; then
	        append $LPVAR $SM_DEF/local/lib
	        for i in $LPVAR_OPT
    	        do
	            append $i $SM_DEF/local/lib
                done
	    fi
	    if [ -n "$AT_SMARTS" ]; then
		if [ -d $SM_DEF/local/slib ]; then
	            append $LPVAR $SM_DEF/local/slib
	            for i in $LPVAR_OPT
    	            do
	                append $i $SM_DEF/local/slib
                    done
		fi
	    fi

	    append $LPVAR $SM_DEF/lib
	    for i in $LPVAR_OPT
    	    do
	        append $i $SM_DEF/lib
            done
	    if [ -n "$AT_SMARTS" ]; then
		append $LPVAR $SM_DEF/slib
	        for i in $LPVAR_OPT
    	        do
	            append $i $SM_DEF/slib
                done
	    fi
	fi

	if [ -n "$SM_LIBPATH" ]; then
		prepend $LPVAR $SM_LIBPATH
	        for i in $LPVAR_OPT
    	        do
	            prepend $i $SM_LIBPATH
                done
	fi

	# Java Virtual Machine Support
	# only want to do this if java 
	if [ "$javaEnabled" = "YES" ]; then
	    if [ -n "$SM_JAVA" ]; then
	        append $LPVAR $SM_JAVA
	        for i in $LPVAR_OPT
    	        do
	            append $i $SM_JAVA
                done
	    else
	        appendJava $LPVAR $SM_HOME $JVM
	        for i in $LPVAR_OPT
    	        do
	            appendJava $i $SM_HOME $JVM
                done
	    fi	
	fi

	# Clean up extraneous :'s in $LPVAR:  Doubled colons, or colons at
	# the beginning or end.  The meaning of the empty elements these
	# introduced is uncertain, and a double colon can cause crashes at
	# shutdown on HPUX.  Note that these are often introduced by code
	# that appends to SM_LIBPATH in a simple-minded way, e.g, using
	# SM_LIBPATH=my/path:$SM_LIBPATH
	eval "TEMP=\$$LPVAR"
	eval $LPVAR=`echo $TEMP | sed -e 's/::*/:/g' -e 's/^://' -e 's/:$//'`
	for i in $LPVAR_OPT
	do
		eval "TEMP=\$$i"
		eval $i=`echo $TEMP | sed -e 's/::*/:/g' -e 's/^://' -e 's/:$//'`
	done

	# setup any required preload libraries
	if [ -n "$SM_LIB_PRELOAD" ]; then
	    append PRELOAD_LIST $SM_LIB_PRELOAD
	    fi

	# only want to do this if java enabled
	if [ "$javaEnabled" = "YES" ]; then
	    if [ -n "$SM_JAVA_PRELOAD" ]; then
	        append PRELOAD_LIST $SM_JAVA_PRELOAD
	    elif [ -n "$RUNCMD_JAVA_PRELOAD" ]; then
		append PRELOAD_LIST $RUNCMD_JAVA_PRELOAD
            fi
	fi

	LD_PRELOAD=$PRELOAD_LIST
	if [ -n "$LD_PRELOAD" ]; then 
	    export LD_PRELOAD
	fi
	
	# for diagnostic purposes, set SM_LIBPATH to current $LPVAR
	eval "SM_LIBPATH=\$$LPVAR"
	for i in $LPVAR_OPT
	do
		eval "SM_LIBPATH_$i=\$$i"
	done
}

# Just the basic OS name may not be sufficient in the future, but for now
# it's enough to make the distinctions we need to make.
#
# LPVAR is the name of the environment variable that sets the library search
# list.
#
# Caution!!!!  No setting of environment variables in this piece of code
# may be dependent on the old value of a variable that is, or could ever
# be, part of the SM_POP_n mechanism defined just after the case statement.
javaEnv=""
javaEnabled="YES"
OS=`/bin/uname`
case $OS in
	"AIX")
		LPVAR=LIBPATH
		LPVAR_OPT=

		# Various threads-related optimizations, mainly of
		# significance in AIX 4.3 or later.

		export AIXTHREAD_MUTEX_DEBUG
		export AIXTHREAD_COND_DEBUG
		export AIXTHREAD_RWLOCK_DEBUG
		AIXTHREAD_MUTEX_DEBUG=OFF
		AIXTHREAD_COND_DEBUG=OFF
		AIXTHREAD_RWLOCK_DEBUG=OFF
		# Controls whether to keep track of these objects for a
		# debugger.  Very expensive when you have many of them.

		export AIXTHREAD_MNRATIO
		AIXTHREAD_MNRATIO=1:1
		# Number of user mode threads per kernel thread.  Our processes
		# end up at 1:1 in the long run because most threads are
		# blocked most of the time, so starting there saves time.

		export MALLOCMULTIHEAP
		MALLOCMULTIHEAP=1
		# Enable an SMP-friendly malloc implementation.

		export SPINLOOPTIME
		SPINLOOPTIME=1000
		# How long to spin in user mode before doing a kernel call
		# when running on a multi-processor machine.

		if [ -z "${SM_NO_SET_ULIMIT}" ]
		then
			ulimit -m unlimited
			ulimit -t unlimited
			ulimit -d unlimited	
		fi
		;;
	"HP-UX")
		LPVAR=SHLIB_PATH
		LPVAR_OPT=
		# Workaround for BSAFE bug in HP-UX for PA-RISC.
		# It expects LD_LIBRARY_PATH to be set instead of SHLIB_PATH 
		LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$SM_HOME/thirdparty
		if [ -n "$LD_LIBRARY_PATH" ]; then
			LPVAR_OPT=LD_LIBRARY_PATH
		fi
		#
		# Set magic variable to control HPUX 10.20 thread
		# dispatching parameters:
		#	Use ITIMER_VIRTUAL
		#	100 usec timer interval
		#	1=timeslice_quanta "Quanta for each thread" ?
		#	Don't set real-time timer
		# If the user has already set this variable, assume he
		# knows what he is doing.
		#
		export CMA_HP_SCHED_OPT
		if [ -z "${CMA_HP_SCHED_OPT}" ]
		then
			CMA_HP_SCHED_OPT="1 100 1 0"
		fi
		;;
	"Linux"|"VMkernel")
		EXPR=/usr/bin/expr
		LPVAR=LD_LIBRARY_PATH
		LPVAR_OPT=
		;;
	"SunOS")
		LPVAR=LD_LIBRARY_PATH
		LPVAR_OPT=
		if [ -n "$LD_LIBRARY_PATH_32" ]; then
			LPVAR_OPT=LD_LIBRARY_PATH_32
		fi
		if [ -n "$LD_LIBRARY_PATH_64" ]; then
			LPVAR_OPT="$LPVAR_OPT LD_LIBRARY_PATH_64"
		fi
		;;
	*)
		echo "System '$OS' unsupported by this version of runcmd"
		exit 1
esac

# Process the debugging info
if [ -n "${SM_RUNCMD_DEBUG}" ]
then
	set -x
fi

# Set up copies of environment variables that need to be saved and
# restored from the surrounding environment.  Do this as early as possible,
# before this code, or runcmd_env.sh, has a chance to change a value we
# might need to save and restore.  All these variables must be exported
# to the environment, hence the set -a.
set -a
SM_POP_1=PATH="$PATH"
eval "SM_POP_2=$LPVAR=\$$LPVAR"
SM_POP_3=LM_LICENSE_FILE="$LM_LICENSE_FILE"
SM_POP_4=SM_LIBPATH="$SM_LIBPATH"
SM_POP_5=SM_BROKER="$SM_BROKER"
SM_POP_6=SM_BROKER_DEFAULT="$SM_BROKER_DEFAULT"
SM_POP_6=SM_PROCESS_PATH="$SM_PROCESS_PATH"
set +a

# Check for runcmd recursion
if [ -z "$SM_RUNCMD_DEPTH" ]; then
    SM_RUNCMD_DEPTH=1
    export SM_RUNCMD_DEPTH
elif [ "$SM_RUNCMD_DEPTH" -gt 5 ]; then
    echo "runcmd: Cannot find SMARTS program $0!"
    exit 1
else
    SM_RUNCMD_DEPTH=`expr $SM_RUNCMD_DEPTH + 1`
    export SM_RUNCMD_DEPTH
fi

# The following line will be/was adjusted to the correct value by the build env.
SM_DEF_DEFHOME=/tmp/bogus
if [ -z "$SM_DEFHOME" ]; then
    SM_DEFHOME=$SM_DEF_DEFHOME
fi

# Determine program name
PROG=`expr "/$0" : '.*/\(..*\)'`
if [ "$PROG" = 'runcmd' -a -n "$1" ]; then
    PROG="$1"
    shift;
fi

# Determine SM_HOME
if [ -z "$SM_HOME" ]; then
    DIR=`expr "$0" : '\(.*\)/[^/]*'`
fi

while [ -z "$SM_HOME" ]
do
    case "$DIR" in
	/*/bin)
	    SM_HOME=`expr "$DIR" : '\(.*\)/[^/]*'`
	    ;;
	.)
	    DIR=`PWD`
	    ;;
	./*)
	    DIR=`PWD`/`expr "$DIR" : './\(.*\)'`
	    ;;
	*/.)
	    DIR=`PWD`/`expr "$DIR" : '\(.*\)/.'`
	    ;;
	*/bin|bin)
	    DIR=`PWD`/$DIR
	    ;;
	'') IFS=": \
	"
	    for D in $PATH
	    do
		if [ -x $D/$PROG ]; then
		    DIR=$D
		    break
		fi
	    done
	    # Could only be here if :: in PATH and PROG invoked with no path
	    DIR=.                   
	    IFS=" \
	"
	    ;;
	*)  echo 1>&2 "runcmd must be run from SMARTS directory"
	    exit 1
	    ;;
    esac
done

cleanpath SM_HOME

case $OS in
	"AIX")
	        locateFile "sm_server" "bin/system"
		if [ -n "${LOCATEDFILE}" ]; then
                    IS_64=`/bin/file "${LOCATEDFILE}" | /bin/grep "64-bit"`
		fi
		# Path to Java Virtual Machine Libraries
 	        if [ "$IS_64" != "" ]; then
		   JVM="jre/bin/classic jre/bin jre/lib"
                else
		   JVM="jre/bin/classic jre/bin jre/lib"
	        fi

		javaEnv="export LDR_CNTRL; LDR_CNTRL=USERREGS"
		;;
	"HP-UX")
	        locateFile "libsm_sms.sl" "lib" "${SM_LIBPATH}"
		if [ -n "${LOCATEDFILE}" ]; then
                    IS_64=`/bin/file "${LOCATEDFILE}" | /bin/grep  "ELF-64"`
		fi
		# Path to Java Virtual Machine Libraries
 	        if [ "$IS_64" != "" ]; then
		   JVM="jre/lib/PA_RISC2.0W/native_threads jre/lib/PA_RISC2.0W/hotspot jre/lib/PA_RISC2.0W"
                else
                   JVM="jre/lib/PA_RISC2.0/native_threads jre/lib/PA_RISC2.0/hotspot jre/lib/PA_RISC2.0"
	        fi
		RUNCMD_JAVA_PRELOAD=libjvm.sl
		
	        # Determine if Java specified
		javaEnabled="$SM_JAVA_ENABLED"
		javaSpecified "$*"

		;;
	"Linux")
	        locateFile "libsm_sms.so" "lib" "${SM_LIBPATH}"
		if [ -n "${LOCATEDFILE}" ]; then
                    IS_64=`/usr/bin/file "${LOCATEDFILE}" | /bin/grep "64-bit"`
		fi
		# Path to Java Virtual Machine Libraries
 	        if [ "$IS_64" != "" ]; then
		    JVM="jre/lib/amd64/server jre/lib/amd64/client jre/lib/amd64"
		else
		    JVM="jre/lib/i386/client jre/lib/i386"
		fi
		;;
	"SunOS")
	        locateFile "libsm_sms.so" "lib" "${SM_LIBPATH}"
		if [ -n "${LOCATEDFILE}" ]; then
                    IS_64=`/bin/file "${LOCATEDFILE}" | /bin/grep "ELF 64-bit"`
		fi
		# Path to Java Virtual Machine Libraries
	        if [ `/bin/uname -p` = i386 ]; then
                   JVM="jre/lib/i386/native_threads jre/lib/i386/client jre/lib/i386"
 	        elif [ "$IS_64" != "" ]; then
		   JVM="jre/lib/sparcv9/native_threads jre/lib/sparcv9/client jre/lib/sparcv9/server jre/lib/sparcv9"
                else
                   JVM="jre/lib/sparc/native_threads jre/lib/sparc/client jre/lib/sparc"
	        fi
		;;
	"VMkernel")
		;;
	*)
		echo "System '$OS' unsupported by this version of runcmd"
		exit 1
esac

# Read installed presets if present
if [ -r $SM_HOME/local/conf/runcmd_env.sh ]; then
    set -a
    . $SM_HOME/local/conf/runcmd_env.sh
    set +a
fi

if [ -n "$SM_SITEMOD" ]; then
    SITEMOD=$SM_SITEMOD
    append SM_SITEMOD $SM_HOME/local
    append SITEMOD $SM_HOME/local
else
    SITEMOD=$SM_HOME/local
    SM_SITEMOD=$SITEMOD
fi

# Set environment variables
SETTING_ENV_VARS=""
if [ -z "$SM_DEF" ]
then
	# Setting up the environment 
	SETTING_ENV_VARS=yes

	export SM_HOME SM_DEF
	SM_DEF=$SM_DEFHOME

	export PATH $LPVAR TCL_LIBRARY PERL_LIBRARY
	export SM_FIXED SM_SITEMOD SM_WRITEABLE SM_LIBPATH SM_PIPEDIR
	# for now still export deprecated SM_RULESET_PATH
	export SM_RULESET_PATH

	for i in $LPVAR_OPT	
	do
		export $i
	done

	# SM_DEF is the secondary installation directory.  It is set to
	# /dev/null if there is no such directory.  It should only be used
	# in runcmd if HAVEDEF is true.
	if [ -z "$SM_DEF" ]; then
		SM_DEF=/dev/null
	fi

	if [ "$SM_DEF" = "/dev/null" ]; then
		HAVEDEF=""
	else
		HAVEDEF=1
	fi

	# SM_SITEMOD
	append SM_SITEMOD $SM_HOME
	if [ -n "$HAVEDEF" ]; then
	    append SM_SITEMOD $SM_DEF/local
	    append SM_SITEMOD $SM_DEF
	fi
fi

# look for options file
if [ -n "$PROG" ]; then
    processAppOptions $PROG $SM_SITEMOD 
fi

if [ -n "$SETTING_ENV_VARS" ]
then
	if [ -z "$SM_NOT_AT_SMARTS" -a -f /etc/smarts/system ]; then
	    AT_SMARTS=1
	fi

	# note - order is reversed as each entry is prepended
	if [ -n "$HAVEDEF" ]; then
	    prepend PATH $SM_DEF/bin/system
	    if [ -d "$SM_DEF/local/bin/system" ]; then
	        prepend PATH $SM_DEF/local/bin/system
	    fi
	fi
	
	prepend PATH $SM_HOME/bin/system
	_x=
	for D in `echo ${SITEMOD} | sed -e 's;:; ;g'`
	do
	    if [ -d $D/bin/system ]; then
		append _x $D/bin/system
	    fi
	done

	if [ -n "$_x" ]; then
	    prepend PATH $_x
	fi

	if [ -n "$SM_PATH_PREPEND" ]; then
	    PATH=$SM_PATH_PREPEND:$PATH
	fi

	# SM_FIXED
	append SM_FIXED $SM_HOME
	if [ -n "$HAVEDEF" ]; then
	    append SM_FIXED $SM_DEF
	fi

	# SM_WRITEABLE
	if [ -z "$SM_WRITEABLE" ]; then
	    append SM_WRITEABLE $SM_HOME/local
        fi
    
	# do not need to produce the deprecated SM_RULESET_PATH

	if [ -z "$TCL_LIBRARY" ]; then
		if [ -r $SM_HOME/lib/tcl/init.tcl ]; then
		    TCL_LIBRARY=$SM_HOME/lib/tcl
		else
		    if [ -n "$HAVEDEF" ]; then
			TCL_LIBRARY=$SM_DEF/lib/tcl
		    fi
		fi
	fi

        # Perl support the $SM_HOME/sm_perl/lib/perl ... should
        # probably be a smarts-specific area, not a perl install area.
	# Also, the PERL_LIBRARY should include both SMARTS raw perl distr
	# area and our additional perl area.  If separate, we don't
	# have issues of chasing down the site_perl in the perl distr
	# in order to have our built additions there!
	if [ -z "$PERL_LIBRARY" ]; then
		if [ -r $SM_HOME/sm_perl/lib/perl/init.pl ]; then
		    PERL_LIBRARY=$SM_HOME/sm_perl/lib
		else
		    if [ -n "$HAVEDEF" ]; then
			PERL_LIBRARY=$SM_DEF/sm_perl/lib
		    fi
		fi
	fi

	# set SM_PIPEDIR
	if [ -z "$SM_PIPEDIR" ]; then
		SM_PIPEDIR=/var/smarts/pipes/
	fi

	# set up any java specific environment
 	if [ "$javaEnabled" = "YES" ] && [ -n "$javaEnv" ]; then
	    eval "$javaEnv"
	fi

fi

# Execute the program
case $PROG in
    runcmd)
	RAWPATH="$SM_SITEMOD:"
        CANDIDATE=`expr "$RAWPATH" : '\([^:]*\):.*'`
        RAWPATH=`expr "$RAWPATH" : '[^:]*:\(.*\)'`
	while [ -n "$CANDIDATE" ]; do
	    for L in $CANDIDATE/bin/system/*
	    do
		LFILE=`expr "/$L" : '.*/\(..*\)'`
		if [ "$LFILE" = '*' ]
		then
		    continue
		fi

		# Only create link if file is executable
		if [ ! -x $CANDIDATE/bin/system/$LFILE ]; then
	            continue;
		fi
		if [ ! -r $SM_HOME/bin/$LFILE ]; then
		    rm -f $SM_HOME/bin/$LFILE
		    ln -s runcmd $SM_HOME/bin/$LFILE
		    echo $LFILE
		fi
	    done	
	    CANDIDATE=`expr "$RAWPATH" : '\([^:]*\):.*'`
	    RAWPATH=`expr "$RAWPATH" : '[^:]*:\(.*\)'`
	done
	exit 0
	;;

    *) 
	# Only set up license vars if we're running code that cares
	if [ -z "${SM_NOLICENSE}" ]; then
	  # Check for existence of SMARTS.licserv
	  licfile=local/conf/SMARTS.licserv
	  if [ -f "$SM_HOME/$licfile" ]; then
	      licfile="$SM_HOME/$licfile"
  	  elif [ -n "$SM_DEFHOME" -a -f "$SM_DEFHOME/$licfile" ]; then
	      licfile="$SM_DEFHOME/$licfile"
	  fi

	  # Check deprecated $licfile and SM_LICENSE
	  if [ -n "${SM_LICENSE}" ]; then
	      liccontents=${SM_LICENSE}
	  elif [ -n "$licfile" -a -r $licfile -a "${AT_SMARTS}"x != x ]; then
	      echo "WARNING: use of $licfile is deprecated.  Set SM_LICENSE directly instead."
	      liccontents=`cat $licfile`
	  else
	      echo "ERROR: SM_LICENSE is not set."
	      exit 1
  	  fi

	  if [ -z "${LM_LICENSE_FILE}" ]; then
	      # No LM_LICENSE_FILE variable. Need to create one
	      # which points to our license file
	      LM_LICENSE_FILE=$liccontents
	  else
	      LM_LICENSE_FILE=${LM_LICENSE_FILE}:$liccontents
	  fi

	  export LM_LICENSE_FILE
        fi

	# Set SM_BROKER and pass to children
	export SM_BROKER; SM_BROKER=${SM_BROKER:=$SM_BROKER_DEFAULT}

	ARGS=${1+"$@"};

	# Remap the program name, if requested
	if [ -n "$SM_REMAP_PROG" ]; then
	    eval "PROG=$SM_REMAP_PROG"
	    unset SM_REMAP_PROG
	fi

	# Prepend args, if requested
	if [ -n "$SM_PREPEND_ARGS" ]; then
	    set -- $SM_PREPEND_ARGS "$@"
	fi

	# Set environment variable with command string, if requested
	if [ -n "$SM_CMD_VAR_NAME" ]; then
	    if [ -n "$SM_PREPEND_ARGS" ]; then
		eval $SM_CMD_VAR_NAME=\"$PROG ${SM_PREPEND_ARGS}\"
	    else
		eval $SM_CMD_VAR_NAME=$PROG
	    fi
	    export $SM_CMD_VAR_NAME;
	fi

	# Clear any lingering SM_PREPEND_ARGS
	if [ -n "$SM_PREPEND_ARGS" ]; then
	    unset SM_PREPEND_ARGS
	fi

	if [ "$SM_DEBUGGER" ]; then
		SM_DEBUG=1
	fi
	x=`type $PROG | awk '{print $3}'`
	SM_PROCESS_PATH=`dirname $x 2> /dev/null`
	export SM_PROCESS_PATH
	CMP_OSLS_PROCESS_PATH=$SM_PROCESS_PATH/$PROG
	export CMP_OSLS_PROCESS_PATH
	if [ "$SM_DEBUG" ]; then
		PATHEDPROG=$PROG
		if expr "$PROG" : '.*/.*' >/dev/null == 0; then
			OLDIFS="$IFS"
			IFS=":"
			for D in $PATH
			do
				if [ -x $D/$PROG ]; then
					if [ -z "$D" -o "$D" = "."  ]; then
						D=`PWD` 
					fi
					PATHEDPROG=$D/$PROG;
					break
				fi
			done
			IFS="$OLDIFS"
		fi

		# Note:  Each case may set SM_DEBUGGER, and a child might need
		# the value.  That's why the code setting DBG and unsetting
		# SM_DEBUG/SM_DEBUGGER is repeated.
		case $OS in
			"AIX")
			    if [ -z "$SM_DEBUGGER" ]; then
				SM_DEBUGGER=/opt/gnu/bin/gdb
			    fi
			    DBG="$SM_DEBUGGER"
			    if [ -z "$SM_DEBUG_CHILDREN" ]; then
				unset SM_DEBUG SM_DEBUGGER
			    fi
			    #
			    # Let the debugger run as a huge program
			    export LDR_CNTRL=MAXDATA=0x80000000
			    setup_lpvar
			    exec $DBG $PATHEDPROG "$@"
			;;

			"HP-UX")
			    #
			    # Work-around for HP dde/softdebug bug:  Debugger
			    # fails if CMA_HP_SCHED_OPT is set
			    unset CMA_HP_SCHED_OPT
			    if [ -z "$SM_DEBUGGER" ]; then
				echo "break main" >/tmp/$$.dbg
				echo "shell /usr/bin/rm /tmp/$$.dbg" >>/tmp/$$.dbg
				echo "run $ARGS" >>/tmp/$$.dbg
				SM_DEBUGGER="/opt/langtools/bin/gdb -x /tmp/$$.dbg"
			    fi
			    DBG="$SM_DEBUGGER"
			    if [ -z "$SM_DEBUG_CHILDREN" ]; then
				unset SM_DEBUG SM_DEBUGGER
			    fi
			    setup_lpvar
			    exec $DBG $PATHEDPROG
			;;

			"SunOS")
			    if [ -z "$SM_DEBUGGER" ]; then
				PATH=/opt/software/SunStudio11/SUNWspro/bin/:$PATH
				SM_DEBUGGER="dbx"
				SUFFIX="$ARGS"
			    else
				SUFFIX="$ARGS"
			    fi
			    DBG="$SM_DEBUGGER"
			    if [ -z "$SM_DEBUG_CHILDREN" ]; then
				unset SM_DEBUG SM_DEBUGGER
			    fi
			    # Dbx runs debugee immediately with parameters.  If
			    # a fault occurs, dbx reports the reason and waits
			    # for user action. Otherwise, dbx exits without error.
			    #    dbx -r debugee [<debugee parameter list>]
			    #
			    # Create dbx session without running debugee.  Wait
			    # for user action.  <debugee parameter list> causes
			    # an error since dbx takes the next parameter to be
			    # a core file.  Manual user action passes debugee
			    # parameters on dbx "run" or "runargs" commands.
			    #    dbx debugee
			    #
			    # Sunstudio is a gui on top of dbx, whose "-E"
			    # option passes a single arguement to the IDE -
			    # contrary to the manpage.
			    #    sunstudio -E "debugee [<debugee parameter list>]"
			    #
			    # Workshop, used by runcmd versions prior to Solaris
			    # 2.8 and SunStudio 9, took 2 parameters, debugee
			    # and "<parameter list>" containing semicolon
			    # deliminated subcommands.
			    #    workshop debugee "<parameter list>"
			    #
			    # The collect command and its options are prefixed
			    # to the debugee and its parameters.  But on Solaris
			    # 8 the T2 threading library must be used to avoid
			    # loosing profiling interrupts.  The user supplies
			    # -F, the follow children option and its parameter.
			    #    collect -F on debugee [<debugee parameter list>]
			    case $DBG in 
				dbx\ -r*)
			    	    setup_lpvar
				    exec $DBG $PATHEDPROG $SUFFIX
				;;
				dbx*)
				    echo "***** You need to run dbx command"
				    echo "*****     \"runargs $SUFFIX\" \"run" 
				    echo "***** before you"
				    echo "*****     \"run\" "
				    echo "***** or just use"
				    echo "*****     \"run $SUFFIX\"."
			    	    setup_lpvar
				    exec $DBG $PATHEDPROG
				;;
				sunstudio*)
			    	    setup_lpvar
				    exec $DBG "$PATHEDPROG $SUFFIX"
				;;
				collect*)
				    # The loader always chooses the correct 32/64 bit
				    # library independent of order in LD_LIBRARY_PATH.
				    LD_LIBRARY_PATH=/usr/lib/lwp/64:$LD_LIBRARY_PATH
				    LD_LIBRARY_PATH=/usr/lib/lwp/32:$LD_LIBRARY_PATH
				    echo "*****  The collect experiment is being created in \"`PWD`\"."
				    export LD_LIBRARY_PATH
			    	    setup_lpvar
				    exec $DBG $PATHEDPROG $SUFFIX
				;;
			    esac
			    setup_lpvar
			    exec $DBG $PATHEDPROG "$SUFFIX"
			;;

                        "Linux")
			    if [ -z "$SM_DEBUGGER" ]; then
				    SM_DEBUGGER='gdb'
			    fi

			    # Handle valgrind differently -- pass the args

			    if  expr "$SM_DEBUGGER" : valgrind >/dev/null; then
			        setup_lpvar
				exec $SM_DEBUGGER $PROG "$@"
			    fi

			    DBG="$SM_DEBUGGER"

			    if [ -z "$SM_DEBUG_CHILDREN" ]; then
				unset SM_DEBUG SM_DEBUGGER
			    fi
			    setup_lpvar
			    exec $DBG $PATHEDPROG
			;;    
		esac
	else
	    setup_lpvar
	    exec $PROG "$@"
	fi ;;
esac

# Local Variables:
# mode: shell-script
# comment-column: 0
# comment-start: "# "
# fill-column: 79
# fill-prefix: "# "
# End:
