#!/bin/sh
#
#			Copyright (c) 1994 by
#			Advanced Visual Systems Inc.
#			All Rights Reserved
#	
#	This software comprises unpublished confidential information of
#	Advanced Visual Systems Inc. and may not be used, copied or made
#	available to anyone, except in accordance with the license
#	under which it is furnished.
#	
#	This file is under Perforce control at AVS in:
#	$Id: //depot/express/fcs70/bin/xp_dbg#1 $
#	

# use the '-id' flag as your first argument if you want to debug the 
# id call of the module as well as the real invocation.

# if AVS is trying to start us as an external module, ignore it.

id=no
mod=no
modname=""
command="UNSET___"

argname=$0
arglist=$*

while [ $# -gt 0 ] ; do
   case $1 in
     -id)       id=yes
		;;
     -debug)	AVS_DEBUG=$2
		shift
		;;
      -*)	echo "Unrecognized option: $1 to $0"
		exit 1
		;;
      *)	command=$1
		;;
   esac
   shift
done

if [ "$AVS_DEBUG" = "" ] ; then
   if [ -x /usr/bin/xdb ] ; then
      echo "Debugging using 'xdb'"
      AVS_DEBUG=xdb
   else if [ -x /usr/bin/dbx ] || [ -x /usr/ucb/dbx ] || [ -x /usr/lang/dbx ] ; then
      echo "Debugging using 'dbx'"
      AVS_DEBUG=dbx
   else 
      echo "Please enter debugger to use: \c"
      read AVS_DEBUG
   fi
   fi
fi

if [ "$command" = "UNSET___" ] ; then
   echo "Enter module file name to debug: \c"
   read command
fi

if [ -r $command ] ; then
   : 
else
   echo "Unable to find executable file: $command".
   exit 1;
fi

AVS_ENV_FILE=/tmp/avsenv$$
export AVS_ENV_FILE

tty=`tty`
if mv -f $command $command.real ; then
  trap '
      /bin/mv $command.real $command
      /bin/rm -f $AVS_ENV_FILE
      exit 0
  ' 1 2 3 15
else
   echo "Unable to execute: mv $command $command.real"
   exit 1
fi
   
cat << EOF > $command 
#!/bin/sh
argname=\$0
arglist=\$*
if [ "\$1" = "-dbid" ] && [ "$id" = "no" ] ; then
	\$0.real \$*
	exit 0
fi

echo "OM_ROOT_OBJ=\$OM_ROOT_OBJ" > $AVS_ENV_FILE
echo "OM_BOSS=\$OM_BOSS" >> $AVS_ENV_FILE
echo "OM_BOSS_2=\$OM_BOSS_2" >> $AVS_ENV_FILE
echo "OM_PROC_OBJ=\$OM_PROC_OBJ" >> $AVS_ENV_FILE
echo "OM_INIT_STACK_LEVEL=\$OM_INIT_STACK_LEVEL" >> $AVS_ENV_FILE

echo "$command instance waiting, fire when ready..." > $tty
EOF

chmod +x $command

$AVS_DEBUG $command.real

/bin/rm -f $AVS_ENV_FILE

# 
# Want to try and figure out if the command is still our shell script
# or whether the user has relinked the program.  If the user has relinked,
# we simply want to remove the ".real" command.  Otherwise we want to
# replace it.
# 
# Since we know that the shell script is small, we use the size in blocks
# of the shell script and compare that to "5".
#
if [ -r $command ] ; then
   output=`ls -s $command`
   for size in $output 
   {
      if [ $size -lt 5 ] && [ "$size" != "$command" ] ; then
	 echo "$argname: restoring $command"
         /bin/mv $command.real $command
	 exit 0
      fi
   }
fi

echo "$argname: not restoring $command (assuming it has changed)"

exit 0
