#!/bin/sh -f
# Run the pointwise machine-specific version indicated by uname
# including keyboard mapping and environment variable setting
#
##############################################################################

##############################################################################
##############################################################################
##
## This script sets the following environment variables for use in
## Pointwise:
##
##	PWI_HOME:  the base installation directory.  All other
##		variables are calculated relative to this setting
##		if they are not set.  If PWI_HOME is not set, it
##		is calculated from the location of this script.  If you
##		copy this script (for example, to place in your path), you
##		will need to modify the copy of this script and explicitly
##		set the value of PWI_HOME.
##
##	PWI_HELP_DIR:  the location of the "map.txt" file.  The
##		default value is $PWI_HOME/doc/Help.  It
##		must be a full path in order for the help pages to
##		be displayed properly.
##
##	PWI_DEMODIR:  the location of the examples directory.  The
##		default value is $PWI_HOME/examples.
##
##	PWI_TCL_LIBRARY:  the location of the Pointwise Tcl/Tk files.  The
##		default value is $PWI_HOME/lib/tcl8.4.
##
##	PWID_LICENSE_FILE:  the location of the FLEXnet license file
##		or the name of the Pointwise license server.  If this
##		value is not set, this script looks to see if it is
##		defined in ~/.flexlmrc.  If not, the license file is
##		looked for in $PWI_HOME/licenses.  If still not
##		successful, the user is prompted for the location.
##
##	PWI_BINDIR:  the name of the directory containing the
##		machine-specific executable and shared object files.  The
##		default value is $PWI_HOME/$hw/bin (where $hw is calculated
##		based on the machine type).
##
##	SHLIB_PATH (HP only):
##	LD_LIBRARYN32_PATH (IRIX 6.5/32-bit only):
##	LD_LIBRARY_PATH (all others):
##		a list of paths to search for shared object files.  The
##		default value of $PWI_BINDIR is appended to any existing
##		value.
##
##
## It is strongly recommended that you use this script to define all
## environment variables and that none of the above environment variables
## be set externally.  If you have changed the default installation
## directory structure and need to override the default environment
## variables, it is recommended that you create a copy of this script
## and explicitly define the necessary variables there.  By following
## this procedure, you will be able to run multiple versions of Pointwise
## without experiencing conflicts due to shared environment variables.
##
##############################################################################
##############################################################################

unalias basename > /dev/null 2>&1
unalias dirname > /dev/null 2>&1
unalias pwd > /dev/null 2>&1
unalias echo > /dev/null 2>&1
unalias grep > /dev/null 2>&1
unalias sed > /dev/null 2>&1
unalias wc > /dev/null 2>&1
unalias find > /dev/null 2>&1
unalias cd > /dev/null 2>&1
unalias hostname > /dev/null 2>&1

OS_NAME=`uname`

theExecPath=\"`echo $PATH | sed -e 's/:/" "/g'`\"

if [ -z "${PWI_HOME:-""}" ]; then
  #
  # Determine the full path to this script
  #
  THIS_SCRIPT=""
  for prg in "$0"
  do
    baseprg=`basename "$prg"`
    if [ "$baseprg" != "$prg" ]; then
      test -f "$prg" || break
      THIS_SCRIPT=`(cd "\`dirname "$prg"\`"; echo "\`pwd\`/$baseprg")`
      break
    fi
    for d in $theExecPath
    do
      if [ -x "$d/$prg" -a ! -d "$d/$prg" ]; then
	THIS_SCRIPT="`(cd "$d"; echo "\`pwd\`/$baseprg")`"
	break
      fi
    done
  done
  if [ -z "$THIS_SCRIPT" ]; then
    echo "ERROR:  Problem determining the location of Pointwise files."
    echo " "
    echo "       Set PWI_HOME to the directory containing the"
    echo "       Pointwise executables.  For example:"
    echo
    echo "       setenv PWI_HOME /usr/local/pointwise"
    echo
    exit 1
  else
    PWI_HOME="`dirname "$THIS_SCRIPT"`"
    export PWI_HOME
  fi
fi
if [ -z "$PWI_HOME" -o ! -d "$PWI_HOME" ]; then
  echo "Environment variable PWI_HOME is not set properly."
  echo " "
  echo "       Set PWI_HOME to the directory containing the"
  echo "       Pointwise executables.  For example:"
  echo
  echo "       setenv PWI_HOME /usr/local/pointwise"
  echo
  exit 2
fi

# Find the location of xmodmap (not needed by all platforms)
MOD_MAP=""
prg="xmodmap"
for d in $theExecPath
do
  if [ -x "$d/$prg" -a ! -d "$d/$prg" ]; then
    MOD_MAP=`(cd "$d"; echo "\`pwd\`/"$prg"")`
    break
  fi
done

if [ -z "$MOD_MAP" ]; then
  MOD_MAP_CHOICES="/usr/bin/X11 /usr/X/bin /usr/openwin/bin"
  for X_MOD_MAP_DIR in $MOD_MAP_CHOICES
  do
    MOD_MAP="$X_MOD_MAP_DIR/xmodmap"
    if [ -x "$MOD_MAP" ]; then
      break
    fi
  done
  if [ ! -x "$MOD_MAP" ]; then
    MOD_MAP=""
  fi
fi

#
# PWI_HELP_DIR should point to location of help library
#
if [ -z "${PWI_HELP_DIR:-""}" ]; then
  PWI_HELP_DIR="$PWI_HOME/doc/Help"
  export PWI_HELP_DIR
fi

#
# PWI_DEMODIR should point to location of sample directory
#
if [ -z "${PWI_DEMODIR:-""}" ]; then
  PWI_DEMODIR="$PWI_HOME/examples"
  export PWI_DEMODIR
fi

########################################################################
# handle command line arguments
# set default name for executable

pointwise_exe="pointwise"
DEBUG_MODE=0
BIT_MODE_32=0
CMD_ARGS=""
BATCH_MODE=0

while [ $# -gt 0 ]
do
   if [ "$1" = "-d" ]; then
      pointwise_exe="pointwise_dbg"
      DEBUG_MODE=1
   elif [ "$1" = "-b" ]; then
      BATCH_MODE=1
   elif [ "$1" = "-32" ]; then
      BIT_MODE_32=1
   else
      # Pass args down to the app
      if [ -z "${CMD_ARGS}" ]; then
	CMD_ARGS="$1" 
      else
	CMD_ARGS="${CMD_ARGS} $1" 
      fi
   fi
   shift
done

########################################################################
# Check the ~/.flexlmrc file to make sure there is a carriage return
# at the end
#
if [ -z "${HOME:-""}" ]; then
  HOME=`(cd; pwd)`
fi
if [ -r "${HOME}/.flexlmrc" ]; then
  LICFILE="${HOME}/.flexlmrc"
  if [ $OS_NAME != Darwin ]; then
    LASTBYTE=`od -to1 "${LICFILE}" | tail -2 | head -1 | sed -e 's/^.* \([0-9]*\)$/\1/'`
  else
    LASTBYTE=`hexdump -e '1/1 "%03o\n"' "${LICFILE}" | tail -1`
  fi

  if [ $LASTBYTE != "012" ]; then
    echo
    echo "The license manager resource file does not end with a newline"
    echo "character.  This causes problems when trying to obtain a license."
    echo
    if [ -w "${LICFILE}" ]; then
      echo "" >> "${LICFILE}"
      echo "A newline was added automatically to the resource file."
      echo
    else
      echo "Pointwise can not write to"
      echo
      echo "    ${LICFILE}"
      echo
      echo "Please correct the problem by adding a newline to the file and"
      echo "running Pointwise again."
      exit 7
    fi
  fi
fi

########################################################################
# Set PWID_LICENSE_FILE if needed.  First see if set explicitly or
# implicitly via ~/.flexlmrc file.
#
KNOW_LICENSE=""
if [ -z "${PWID_LICENSE_FILE:-""}" ]; then
  if [ -z "${HOME:-""}" ]; then
    HOME=`(cd; pwd)`
  fi
  if [ -r "${HOME}/.flexlmrc" ]; then
    if [ `grep "PWID_LICENSE_FILE" "${HOME}/.flexlmrc" | wc -l` -gt 0 ]; then
      KNOW_LICENSE="flexlmrc"
    fi
  fi
else
  KNOW_LICENSE="envvar"
fi
#
# See if the license is in the preferred location of $PWI_HOME/licenses
#
PREF_LIC_DIR="${PWI_HOME}/licenses"
if [ -z "${KNOW_LICENSE}" ]; then
  if [ -d "${PREF_LIC_DIR}" ]; then
    if [ `find "${PREF_LIC_DIR}" -name \*.lic -print | wc -l` -gt 0 ]; then
      PWID_LICENSE_FILE="${PREF_LIC_DIR}"
      export PWID_LICENSE_FILE
      KNOW_LICENSE="deflicfile"
    fi
  fi
fi
#
# Can't locate a license, so prompt the user
#
if [ -z "${KNOW_LICENSE}" ]; then
  echo
  echo "The license could not be located via standard mechanisms.  Please"
  echo "choose an option:"
  while [ -z "${KNOW_LICENSE}" ]; do
    echo
    echo "   1.  Specify a license server"
    echo "   2.  Specify the license file path"
    if [ ! -z "${LM_LICENSE_FILE:=""}" ]; then
      echo "   3.  Use the value of LM_LICENSE_FILE"
    fi
    echo "   0.  Exit"
    echo
    echo "Enter an option (0):"
    read OPTION
    if [ -z ${OPTION:=""} ]; then
      OPTION=0
    fi
    if [ $OPTION -eq 0 ]; then
      exit 3
    fi
    if [ $OPTION -eq 1 ]; then
      echo "Enter the license server hostname (leave blank to re-select the license option):"
      read LIC_HOST
      if [ ! -z ${LIC_HOST:=""} ]; then
        PWID_LICENSE_FILE="@${LIC_HOST}"
        export PWID_LICENSE_FILE
	KNOW_LICENSE="host"
      fi
    elif [ $OPTION -eq 2 ]; then
      echo "Enter the license file path (leave blank to re-select the license option):"
      read LIC_PATH
      if [ ! -z "${LIC_PATH:=""}" ]; then
        if [ -d "${LIC_PATH}" ]; then
	  if [ `find "${LIC_PATH}" -name \*.lic -print | wc -l` -gt 0 ]; then
	    PWID_LICENSE_FILE="${LIC_PATH}"
            export PWID_LICENSE_FILE
	    KNOW_LICENSE="dirpath"
	  else
	    echo
	    echo "No license files (*.lic) were found in the given directory."
	    echo "If the license file has a different extension, then enter the full"
	    echo "path to the license file, including the filename."
	    echo
	  fi
	elif [ -f "${LIC_PATH}" ]; then
	  PWID_LICENSE_FILE="${LIC_PATH}"
	  export PWID_LICENSE_FILE
	  KNOW_LICENSE="filepath"
	else
	  echo
	  echo "The license file path does not exist."
	  echo
	fi
      fi
    elif [ $OPTION -eq 3 -a ! -z "${LM_LICENSE_FILE:=""}" ]; then
      PWID_LIENSE_FILE="${LM_LICENSE_FILE}"
      export PWID_LICENSE_FILE
      KNOW_LICENSE="lmvar"
    else
      echo "Invalid option."
      echo
    fi
    if [ -z "${KNOW_LICENSE}" ]; then
      echo
      echo "Please choose an option:"
    fi
  done
fi

########################################################################
# locate executable

if [ $OS_NAME = IRIX -o $OS_NAME = IRIX64 ]; then

#..Silicon Graphics
  OS_VER=`uname -r`
  OS_MAJ=`echo $OS_VER | sed -e 's/\([0-9]*\).*/\1/'`
  OS_MIN=`echo $OS_VER | sed -e 's/[0-9]*.\([0-9]*\).*/\1/'`

  if [ 0 == $BATCH_MODE ]; then
    if [ -z "$MOD_MAP" ]; then
      echo "ERROR: Cannot find xmodmap command."
      echo "Please add xmodmap location to your path"
      echo "and try again."
      exit 4
    fi
    "$MOD_MAP" -e "remove mod2 = Num_Lock"
  fi

  if [ $OS_MAJ -gt 6 ]; then
    hw="sgi65"
  elif [ $OS_MAJ -eq 6 -a $OS_MIN -ge 5 ]; then
    if [ $OS_NAME = "IRIX64" ] && [ $BIT_MODE_32 -ne 1 ]; then
      hw="sgi65"
    else
      hw="sgi65_32"
    fi
  else
    echo "ERROR: Pointwise requires IRIX v6.5 or higher."
    exit 1;
  fi

  if [ $OS_VER = "IRIX_64" ] && [ ! -x "PWI_HOME/$hw/bin/$pointwise_exe" ]; then
    echo "NOTICE:  The 64 bit version of Pointwise does not appear to be"
    echo "installed.  The 32 bit version will be used instead."
    echo ""
    hw="sgi65_32"
  fi
elif [ $OS_NAME = HP-UX ]; then
#..Hewlett-Packard
    hw="hp"
elif [ $OS_NAME = Linux ]; then
#..Linux
  HW_ARCH=`uname -m`
  if [ $HW_ARCH = "x86_64" ] && [ $BIT_MODE_32 -ne 1 ]; then
#..Linux/64
    hw="linux_x86_64"
    #.. Check to see if 64 bit version is installed.  If not, fall back to
    #.. 32 bit version.
    if [ ! -x "$PWI_HOME/$hw/bin/$pointwise_exe" ]; then
      echo "NOTICE:  The 64 bit version of Pointwise does not appear to be"
      echo "installed.  The 32 bit version will be used instead."
      echo ""
      hw="linux"
    fi
  else
#..Linux/32
    hw="linux"
  fi
elif [ $OS_NAME = SunOS ]; then

#..Solaris

# check for xmodmap

  if [ 0 = $BATCH_MODE ]; then
    if [ -z "$MOD_MAP" ]; then
      echo "ERROR: Cannot find xmodmap command."
      echo "Please add xmodmap location to your path"
      echo "and try again."
      exit 4
    fi

    #
    # capture current keyboard definitions
    #

    keyKP_Up=`"$MOD_MAP" -pke | grep KP_Up`
    keyKP_Down=`"$MOD_MAP" -pke | grep KP_Down`
    keyKP_Right=`"$MOD_MAP" -pke | grep KP_Right`
    keyKP_Left=`"$MOD_MAP" -pke | grep KP_Left`
    keyKP_Delete=`"$MOD_MAP" -pke | grep KP_Delete`

    "$MOD_MAP" -e "remove mod3 = Num_Lock"
    "$MOD_MAP" -e "keycode 76 = KP_Up"
    "$MOD_MAP" -e "keycode 120 = KP_Down"
    "$MOD_MAP" -e "keycode 100 = KP_Right"
    "$MOD_MAP" -e "keycode 98 = KP_Left"
    "$MOD_MAP" -e "keycode 57 = KP_Delete"
  fi

  hw="sun"

else

  echo "ERROR: unrecognized hardware type from uname: $OS_NAME"
  exit 5

fi

#
# IMPORTANT: This must be set to point to the Tcl/Tk libraries
# that came with Pointwise.
#
PWI_TCL_LIBRARY="$PWI_HOME/$hw/lib/tcl8.4"
export PWI_TCL_LIBRARY

########################################################################
# run executable

PWI_BINDIR="$PWI_HOME/$hw/bin"
PWI_LIBDIR="$PWI_HOME/$hw/lib"
export PWI_BINDIR

if [ $hw = "sgi65_32" ]; then
  if [ -z "${LD_LIBRARYN32_PATH:-""}" ]; then
    LD_LIBRARYN32_PATH="${PWI_LIBDIR}:${PWI_BINDIR}"
  else
    LD_LIBRARYN32_PATH="${PWI_LIBDIR}:${PWI_BINDIR}:${LD_LIBRARYN32_PATH}"
  fi
  export LD_LIBRARYN32_PATH
elif [ $hw = "hp" ]; then
  if [ -z "${SHLIB_PATH:-""}" ]; then
    SHLIB_PATH="${PWI_LIBDIR}:${PWI_BINDIR}"
  else
    SHLIB_PATH="${PWI_LIBDIR}:${PWI_BINDIR}:${SHLIB_PATH}"
  fi
  export SHLIB_PATH
else
  if [ -z "${LD_LIBRARY_PATH:-""}" ]; then
    LD_LIBRARY_PATH="${PWI_LIBDIR}:${PWI_BINDIR}"
  else
    LD_LIBRARY_PATH="${PWI_LIBDIR}:${PWI_BINDIR}:${LD_LIBRARY_PATH}"
  fi
  export LD_LIBRARY_PATH
fi

if [ 0 = $BATCH_MODE ]; then
  EXEC="$PWI_BINDIR/$pointwise_exe"
else
  EXEC="$PWI_BINDIR/tclsh"
fi

if [ -x "$EXEC" ]; then
  if [ 0 != $BATCH_MODE -a 0 != $DEBUG_MODE ]; then
    "$EXEC" << EOF
    global tcl_platform
    set tcl_platform(debug) 1
    source {$CMD_ARGS}
EOF
  else
    "$EXEC" "${CMD_ARGS}"
  fi
  EXIT_ST=$?
  if [ $EXIT_ST = 3 ]; then
    echo
    echo
    echo "****************************************************************************"
    echo
    echo "A Pointwise license could not be obtained.  The above error message indicates"
    echo "the reason.  In the event of the wrong license server being used, the"
    echo "location of the license was determined as follows:"
    echo
    case "${KNOW_LICENSE}" in
      flexlmrc)
        echo "The location of the license file was obtained automatically from"
	echo "the value of PWID_LICENSE_FILE in ~/.flexlmrc.  Verify that"
	echo "the location specified in the file is correct and that the license"
	echo "server is running on the server specified either explicitly or in"
	echo "the license file.  If the ~/.flexlmrc file contains invalid data,"
	echo "delete the PWID_LICENSE_FILE line and rerun Pointwise."
	;;
      envvar)
        echo "The location of the license file was obtained automatically from"
	echo "the value of the environment variable PWID_LICENSE_FILE.  Verify"
	echo "that the location specified in the variable is correct and that the"
	echo "license server is running on the server specified either explicitly"
	echo "or in the license file.  If the variable is incorrect, unset it"
	echo "and rerun Pointwise."
        ;;
      deflicfile)
        echo "A license file was found in the default license location:"
	echo
	echo "   $PREF_LIC_DIR"
	echo
	echo "Contact your system administrator to verify that the license is correct"
	echo "and that the license server is running.  If you need to use a different"
	echo "license, set the environment variable PWID_LICENSE_FILE to either"
	echo "the path of the correct license file or the hostname of the license"
	echo "server (with the form \"@server_host\")."
        ;;
      host)
        echo "The hostname you entered for the license server is invalid, unreachable,"
	echo "or down.  Contact your system administrator for the proper server"
	echo "name and license server status."
        ;;
      dirpath)
        echo "The directory you entered for the location of the license file either"
	echo "contains no available licenses or the license servers are down."
	echo "Contact your system administrator for the proper directory and "
	echo "license server status."
        ;;
      filepath)
        echo "The location you entered for the license file either contains no"
	echo "available licenses or the license server is down.  Contact your system"
	echo "administrator for the proper license file and license server status."
        ;;
      lmvar)
        echo "The location was obtained from the environment variable LM_LICENSE_FILE."
	echo "Either the value is incorrect, or the server is unavailable.  Contact"
	echo "your system administrator for the correct license location.  To override"
	echo "the value in LM_LICENSE_FILE, set PWID_LICENSE_FILE."
	;;
      *)
        echo "The location of the license file was obtained in an unknown way."
	echo "Contact your system administrator."
        ;;
    esac
  fi
else
  if [ 0 -lt $DEBUG_MODE ]; then
     echo "The debug version of Pointwise is not installed.  It is not provided by default"
     echo "and is only made available as needed.  Please contact your Pointwise distributor"
     echo "if you feel the debug version is needed."
     exit 8
  fi
  echo "ERROR: Cannot find the executable file:"
  echo "       $EXEC"
  echo " "
  echo "Unset all Pointwise environment variables and try again."
  echo " "
  echo "If you have modified the directory structure of the Pointwise"
  echo "installation, refer to the comments included in the top of"
  echo "this script on how to set the variables within a script."
  echo " "
  exit 6
fi

########################################################################
# done
# restore previous keyboard settings

if [ $OS_NAME = IRIX -o $OS_NAME = IRIX64 ]; then

  if [ 0 == $BATCH_MODE ]; then
    "$MOD_MAP" -e "add mod2 = Num_Lock"
  fi

elif [ $OS_NAME = SunOS ]; then

  if [ 0 == $BATCH_MODE ]; then
    "$MOD_MAP" -e "add mod3 = Num_Lock"
    "$MOD_MAP" -e "$keyKP_Down"
    "$MOD_MAP" -e "$keyKP_Right"
    "$MOD_MAP" -e "$keyKP_Left"
    "$MOD_MAP" -e "$keyKP_Delete"
  fi

fi

exit $EXIT_ST

