#! /bin/sh
#
OS=`uname`
hostname=`hostname`
mydir=`dirname $0`
myname=$0

Usage()
{
   cat <<EOF >&2

Interactive usage:			$myname
Graphical Batch mode:			$myname [-o outputfile] inputfile
Non-graphical Batch mode:		$myname -n [-o outputfile] inputfile
Non-graphical Batch in the background:	$myname -b outputfile [-i] inputfile
For the development only:		$myname -d [any-other-options]
Do not move or resize the window:	$myname -noresize
Remove Cerius2 lock before running:	$myname -unlock [any-other-options]
Clean-up (deleting symbolic links):	$myname -clean

	-n - run non-graphically
	inputfile - execute script in the Batch mode
	outputfile - redirect output to this file
	-b - redirect output and run non-graphically in the background
	-i - can (but does not have to) preceed 'inputfile'
        -x - use a specified card deck configuration name
	-d - use a development version from obj/$MACHINE.$PLATFORM directory
	-clean - does NOT start Cerius2, but only deletes ALL the symbolic links,
		RUN.LOG, cerius2_lock and core
EOF
   exit 1
}

#
#	Parse arguments
#
inputfile=
outputfile=
myname=`basename $0`
NO_GRAPHICS=
background=
development=
cmdline_cdc=

Redirected()
{
   if [ -n "$outputfile" ]
   then $* >> $outputfile 2>&1
   else $*
   fi
}

lock=cerius2_lock
while [ -n "$1" ]
do
   case $1 in
      -n|-c) if [ $1 = "-c" ]
             then C2_COMMANDLINE=1; export C2_COMMANDLINE
             fi
             NO_GRAPHICS=1;;
      -b|-o) if [ $1 = "-b" ]
             then NO_GRAPHICS=1; background=yes
             fi
             if [ -n "$2" ]
             then outputfile=$2; shift
             else echo "$myname error: output file name missing" >&2; Usage
             fi;;
      -i)    if [ -n "$2" ]
             then inputfile=$2; shift
             else echo "$myname error: input file name missing" >&2; Usage
             fi;;
      -x)    if [ -n "$2" ]
             then C2_DEX=$2; export C2_DEX; shift
             else echo "$myname error: deck configuration name missing" >&2; Usage
             fi;;
      -d)    development=yes;;
      -noresize) C2_NOMOVE=yes; export C2_NOMOVE;;
      -nobanner) C2_NOBANNER=yes; export C2_NOBANNER;;
      -unlock)   rm -f $lock;;
      -clean) rm -f RUN.LOG cerius2_lock core Cerius2-Resources Cerius2-Models
#             echo "Deleting the following links:"
#             find . -type l -exec /bin/ls -l {} \; -exec /bin/rm {} \;
#             if [ -d autohelp ]
#             then
#                if [ -z "`/bin/ls autohelp`" ]
#                then rmdir autohelp
#                fi
#             fi
#             echo "Done."
             exit;;
      *)     if [ -z "$inputfile" ]
             then inputfile=$1
             else echo "$myname argument parsing error" >&2; Usage
             fi;;
   esac
   shift
done

if [ -f cerius2_lock ]
then
   echo "WARNING - Cerius2 may already be running in this directory."
   echo "If no other version is running, remove the Cerius2 lock file"
   echo "by adding option '-unlock' to your cerius2 command"
   exit 2
fi

if [ -n "$NO_GRAPHICS" ]
then
   if [ -z "$inputfile" -a -z "$C2_COMMANDLINE" ]
   then echo "Input file is required for non-graphical usage" >&2
        Usage
   fi
   export NO_GRAPHICS
fi
if [ -n "$outputfile" ]
then
   cat /dev/null > $outputfile
   if [ ! -w $outputfile ]
   then echo "$myname error: Cannot create $outputfile" >&2; Usage
   fi
   export outputfile
fi

if [ -z "$C2_DEX" ]
then
   C2_DEX=%MSIInstallDex%
   export C2_DEX
fi

autohelpmade=
if [ -n "$development" ]
then
   [ -z "$C2DIR" ] && C2DIR=%MSIInstallRoot%
   if [ ! -d "$C2DIR" ]
   then
      [ -z "$HOSTTYPE" ] && HOSTTYPE=`machine`
      [ -z "$MACHINE" ] && MACHINE=$HOSTTYPE
      [ -z "$PLATFORM" ] && PLATFORM=x11
      [ -z "$MSIROOT" ] && MSIROOT=/cx4
      C2DIR=$MSIROOT/release/$MACHINE.$PLATFORM/cerius2_c40
   fi
   #
   # create an autohelp directory, if the user does not have one. make links
   # to all of the users development help files.
   #
   if [ ! -d autohelp ]
   then
      mkdir autohelp
      cd autohelp
      if [ $? = 0 ]
      then
         for i in ../../*/auto/*.hlp
         do
            if [ -r $i ]
            then ln -s $i .
            fi
         done
         cd ..
         autohelpmade=1
      fi
   else
      echo "WARNING: autohelp directory already exists - some development help"
      echo "files may not be picked up during this run."
   fi
else
   C2DIR=%MSIInstallRoot%
fi
export C2DIR

#
# set up graphics driver based on display hardware
#  At this point, only Impact machines or R5000+ should be OpenGL
#
if [ "$OS" = "IRIX" -o "$OS" = "IRIX64" ]
then
#
# get the CPU type
#
    CPU=`hinv | sed -e '/^CPU:/!d'`
    R=`echo $CPU |
        awk '/^CPU:/ {if (substr($3,1,1)=="R") print substr($3,2,1)}'`
#
# get whether it has IMPACT Graphics or environment variables
# are set to override default mode.
#
#   If FORCEOPENGL is set, use OpenGL driver
#
    OPENGL=$FORCEOPENGL

# If Impact graphics, use OpenGL driver
    if [ "$OPENGL" = "" ]
    then
        OPENGL=`hinv | grep -i Impact`
    fi

# If R5000 or R8000 or R10000 CPU, use OpenGL driver
# unless we have Indy or Extreme graphics which can
# be found in R5K and R8K machines.

    if [ "$R" = "5" -o "$R" = "8" -o "$R" = "1" ]
    then
        GL=`hinv | grep -i Indy`
        if [ "$GL" = "" ]
        then
            GL=`hinv | grep -i Extreme`
        fi

        if [ "$GL" = "" ]
        then
            OPENGL=1
        fi
    fi 

# If FORCEGL is set, override the above checks and use GL mode
    if [ "$FORCEGL" != "" ]
    then
        OPENGL=""
    fi

    if [ "$OPENGL" != "" ]
    then
        LD_LIBRARY_PATH="$LD_LIBRARY_PATH":$C2DIR/libs/OpenGL
    else
        LD_LIBRARY_PATH="$LD_LIBRARY_PATH":$C2DIR/libs/GL
    fi
fi
#
# set up for shared library finding
#
if [ -d $C2DIR/libs ]
then
   if [ -z "$LD_LIBRARY_PATH" ]
   then
      LD_LIBRARY_PATH=$C2DIR/libs
   else
      LD_LIBRARY_PATH="$LD_LIBRARY_PATH":$C2DIR/libs
   fi
fi

#
# Prepend cat400so to library path to override any 
# previously installed cat400so in path (required by SBF and KEYS_3D) 
#
if [ ! -z "$LD_LIBRARY_PATH" -a -d "$C2DIR/libs/cat400so" ] 
then
    LD_LIBRARY_PATH=$C2DIR/libs/cat400so:"$LD_LIBRARY_PATH"
fi

#
# Oracle environmental variables
#
C2_ORACLE_HOME=%ORACLE_HOME%

if [ "$C2_ORACLE_HOME" != "%ORACLE_HOME%" ]; then
LD_LIBRARY_PATH=$C2_ORACLE_HOME/lib:"$LD_LIBRARY_PATH"
fi

#
# Daylight environmental variables are introduced in the following part
#    C2_OVRD_DY_ROOT - override variable for DY_ROOT
#    C2_DY_ROOT - DY_ROOT variable configured during installation
#    C2_OVRD_DY_LICDATA - override variable for Daylight license path
#    C2_DY_LICENSEDATA - Daylight license path configured during installation
#    MSI_DY_DEBUG - if it's set to 1, then
#                   DY_ROOT, LD_LIBRARY_PATH, etc. env variables are displayed
#
C2_DY_ROOT=%DY_ROOT%
C2_DY_LICENSEDATA=%DY_LICENSEDATA%

#if [ "$C2_DY_ROOT" != "%DY_ROOT%" ]; then
#DY_ROOT=$C2_DY_ROOT
#PATH=$PATH:$DY_ROOT/bin
#export DY_ROOT
#fi

# Use override variable C2_OVRD_DY_ROOT if it is set
#
if [ -n "$C2_OVRD_DY_ROOT" ]
then
   DY_ROOT=$C2_OVRD_DY_ROOT
   echo "ATTENTION: Override path for DY_ROOT"
   echo "           $DY_ROOT"
   echo "(indicated by C2_OVRD_DY_ROOT) is being used."
#
#  Use configured path if it is set
#
elif [ "$C2_DY_ROOT" != "%DY_ROOT%" ]
then
   if [ -n "$DY_ROOT" ]
   then
      if [ "$C2_DY_ROOT" != "$DY_ROOT" ]
      then
         echo "NOTE: Configured value of DY_ROOT"
         echo "         $C2_DY_ROOT"
         echo "differs from its current value"
         echo "         $DY_ROOT"
         echo "The configured value is being used."
         echo ""
      fi
   fi
   DY_ROOT=$C2_DY_ROOT
fi

if [ -n "$DY_ROOT" ]
then
   if [ ! -x "$DY_ROOT/bin/clogp" ]
   then
      echo "WARNING: It appears that Daylight installation has problems."
      echo "For instance,"
      echo "   $DY_ROOT/bin/clogp"
      echo "does not exist or is not executable."
      echo ""
   fi
   PATH=$PATH:$DY_ROOT/bin
   export DY_ROOT
   export PATH
fi

#if [ "$C2_DY_LICENSEDATA" != "%DY_LICENSEDATA%" ]; then
#DY_LICENSEDATA=$C2_DY_LICENSEDATA
#export DY_LICENSEDATA
#fi

# Use override variable C2_OVRD_DY_LICDATA if it is set
#
if [ -n "$C2_OVRD_DY_LICDATA" ]
then
   DY_LICENSEDATA=$C2_OVRD_DY_LICDATA
   export DY_LICENSEDATA
   echo "ATTENTION: Override path for DY_LICENSEDATA"
   echo "           $DY_LICENSEDATA"
   echo "(indicated by C2_OVRD_DY_LICDATA) is being used."
   echo ""
#
#  Use configured path if it is set
#
elif [ "$C2_DY_LICENSEDATA" != "%DY_LICENSEDATA%" ]
then
   if [ -n "$DY_LICENSEDATA" ]
   then
      if [ "$C2_DY_LICENSEDATA" != "$DY_LICENSEDATA" ]
      then
         echo "NOTE: Configured value of DY_LICENSEDATA"
         echo "         $C2_DY_LICENSEDATA"
         echo "differs from its current value"
         echo "         $DY_LICENSEDATA"
         echo "The configured value is being used."
         echo ""
      fi
   fi
   DY_LICENSEDATA=$C2_DY_LICENSEDATA
   export DY_LICENSEDATA
fi

#
# The following Cerius2 directories have links made to them, rather
# than using environment variables, so that they appear to look
# like normal directories to file browsers.
#
# First we do the directories that should appear in all copies of
# Cerius2.
#
RemoveLater=
havewarning=
dirmade="Cerius2-Models Cerius2-Resources"
for i in $dirmade
do
   nolink_reason=
   #
   # Does the system directory itself exist to be linked to ?
   #
   if [ -d $C2DIR/$i ]
   then
      #
      # Does the local directory exist already ?
      #
      if [ -d $i ]	# Check whether the directory is a link, pointing to the
      then		# place it should be linked anyway
         currlink=`ls -ld $i 2>/dev/null | awk '$(NF-1)=="->" {print $NF}'`
         if [ -z "$currlink" ]
         then nolink_reason="Directory $i already exists"
         elif [ $currlink = $C2DIR/$i ]
         then		# Link matches the correct path
            RemoveLater="$RemoveLater $i"
         else
            nolink_reason="Link $i already exists"
         fi
      elif [ -f $i ]    # Is there a file of this name already ?
      then nolink_reason="File of that name already exists"
      elif ln -s $C2DIR/$i $i   # Create the link and store the name
      then                      # for future removal
         RemoveLater="$RemoveLater $i"
      else
         nolink_reason="Unable to create link"
      fi
   else
      nolink_reason="System directory of that name is missing"
   fi
   #
   # If no link was made, print a warning message
   #
   if [ -n "$nolink_reason" ]
   then
      Redirected echo Warning - link to standard Cerius2 directory $i \
         could not be made.
      Redirected echo $nolink_reason
      havewarning=1
   fi
done
#
# If at least one of the links failed, print an extra warning
#
if [ -n "$havewarning" ]
then Redirected echo Some standard data files may be unavailable
fi

#
# The remainder use environment variables, because they refer to 
# fixed parts of Cerius2.
#
#
# Setup license pack variable (this location is configured at install time)
#
if [ -z "$LP_OVERRIDE" ]
then
   MSI_LIC_PACK_DIR=%MSI_License_Pack_Dir%
else
   MSI_LIC_PACK_DIR="$LP_OVERRIDE"
fi

if [ -d $MSI_LIC_PACK_DIR ]
then
   export MSI_LIC_PACK_DIR
   MSI_LIC_PLATFORM=`$MSI_LIC_PACK_DIR/bin/lmgetplat`
   export MSI_LIC_PLATFORM
   if [ ! -z "$LD_LIBRARY_PATH" ]
   then
      export LD_LIBRARY_PATH
      LD_LIBRARY_PATH=`$MSI_LIC_PACK_DIR/bin/lmgetldpath`
   fi
fi

if [ ! -z "$LD_LIBRARY_PATH" ]
then
   export LD_LIBRARY_PATH
fi

#     If LD_LIBRARYN32_PATH or LD_LIBRARY64_PATH are set,
#     prepend value of LD_LIBRARY_PATH to their pathes

if [ ! -z "$LD_LIBRARYN32_PATH" ]
then
   LD_LIBRARYN32_PATH="$LD_LIBRARY_PATH":$LD_LIBRARYN32_PATH
   export LD_LIBRARYN32_PATH
fi

if [ ! -z "$LD_LIBRARY64_PATH" ]
then
   LD_LIBRARY64_PATH="$LD_LIBRARY_PATH":$LD_LIBRARY64_PATH
   export LD_LIBRARY64_PATH
fi

#
# Print out DY_ROOT, LD_LIBRARY_PATH, etc. env variables
# if env variable MSI_DY_DEBUG is set to 1
#
if [ "$MSI_DY_DEBUG" = "1" ]
then
   [ -n "$DY_ROOT" ] && echo "DY_ROOT:		$DY_ROOT"
   [ -n "$DY_LICENSEDATA" ] && echo "DY_LICENSEDATA:		$DY_LICENSEDATA"
   [ -n "$LD_LIBRARY_PATH" ] && echo "LD_LIBRARY_PATH:	$LD_LIBRARY_PATH"
   [ -n "$LD_LIBRARYN32_PATH" ] && echo "LD_LIBRARYN32_PATH:	$LD_LIBRARYN32_PATH"
   [ -n "$LD_LIBRARY64_PATH" ] && echo "LD_LIBRARY64_PATH:	$LD_LIBRARY64_PATH"
fi

#
# Setup LM_LICENSE_FILE variable
#
if [ -z "$LM_OVERRIDE" ]
then
   if [ -d $MSI_LIC_PACK_DIR ]
   then
      LM_LICENSE_FILE=`$MSI_LIC_PACK_DIR/bin/lmgetpath`
   else
      LM_LICENSE_FILE=/etc/msilicense.dat:$C2DIR/license/msilicense.dat:$C2DIR/license/msilicense.demo
   fi
else
   LM_LICENSE_FILE="$LM_OVERRIDE"
fi

#location of release specific data(which is also defined in applcomm.db):
MSI_LIC_INFO_DIR=$C2DIR/CHECKSUM

if [ -z "$C2_APPLCOMM_DB" ]
then
   if [ -n "$development" -a -f applcomm.db ]
   then  APPLCOMM_DB=applcomm.db
   else
         APPLCOMM_DB=$C2DIR/libraries/applcomm.db
   fi
else APPLCOMM_DB=$C2_APPLCOMM_DB
fi

RES=$C2DIR/res
APP_RESOURCES=$RES
LIB=$C2DIR/libraries
CERIUSINITDIR=.:${HOME}:$C2DIR/db
XUSERFILESEARCHPATH=$C2DIR/db/%N
C2EXECS=$C2DIR/exec
export LM_LICENSE_FILE APPLCOMM_DB RES APP_RESOURCES CERIUSINITDIR XUSERFILESEARCHPATH MSI_LIC_INFO_DIR

if [ -n "$development" ]
then
   if [ -z "$C2_UI_RESOURCES" ]
   then UI_RESOURCES=../db:$C2DIR/db
   else UI_RESOURCES=$C2_UI_RESOURCES:$C2DIR/db
   fi
   if [ -z "$C2_APPLREG" ]
   then C2_APPLREG=.:$LIB
   fi
   if [ -z "$C2_HELP" ]
   then HELP=autohelp:$C2DIR/help
   else HELP=$C2_HELP:$C2DIR/help
   fi
   C2EXECS="$MYEXEDIR:obj/$MACHINE.$PLATFORM:$C2EXECS"
else
   UI_RESOURCES=$C2DIR/db
   C2_APPLREG=$LIB
   HELP=$C2DIR/help
fi

export UI_RESOURCES C2_APPLREG HELP

PATH=$C2EXECS:$PATH:.
export PATH

#
# set DDW environment variables
#
DDW_DATA=$C2DIR/DDWResources
DDW_RESOURCES=$C2DIR/Cerius2-Resources/RECEPTOR
QSAR_RESOURCES=$C2DIR/Cerius2-Resources/QSAR
ATMDAT=$QSAR_RESOURCES
CHEMDAT=$QSAR_RESOURCES
CHEMSTER=$QSAR_RESOURCES
MMFDAT=$QSAR_RESOURCES
export DDW_DATA DDW_RESOURCES QSAR_RESOURCES ATMDAT CHEMDAT CHEMSTER MMFDAT
CHM_DATA=$C2DIR/Cerius2-Resources/MMFF
export CHM_DATA

#
# set display if not set
#
if [ -z "$DISPLAY" ]
then DISPLAY=$hostname:0; export DISPLAY
fi
#
# set up FORCEX11
#
displayhost=`echo $DISPLAY | sed '/:/s/:.*.$//'`
DISPLAYREMOTE=

if [ -n "$displayhost" -a "$displayhost" != "$hostname" -a \
     "$displayhost" != "unix" -a "$displayhost" != "local" ]
then
# For remote display, force X11 for all machines except SGI and IBM.
# The driver will figure out whether it can use DGL on SGI's and IBM
    DISPLAYREMOTE=1
    export DISPLAYREMOTE
    if [ "$OS" != "IRIX" -a "$OS" != "IRIX64" -a "$OS" != "AIX" ] ; then
        FORCEX11=1; export FORCEX11
    fi
else
# For local display on SGI, must set hostname to "unix" in order for
# stereo to work (setmon call requires "unix").
  if [ "$OS" = "IRIX" -o "$OS" = "IRIX64" ]
  then
     if [ "$displayhost" = "$hostname" ]
     then
        DISPLAY=`echo $DISPLAY | sed -e "s/^$hostname:/unix:/"`
        export DISPLAY
     fi
  fi
fi

#
# Set font style for model and graphs windows. On HP, Courier
# is the "fast" font so always use it.
#
if [ $OS = 'HP-UX' ] ; then
    MODEL_FONT=Courier
    GRAPH_FONT=Courier
else
    MODEL_FONT=Helvetica
    GRAPH_FONT=Courier
fi
export MODEL_FONT GRAPH_FONT

if [ -z "$DISPLAYREMOTE" -a -z "$NO_GRAPHICS" ]
then
#
# Now some machine-specific server initializations
#
  if [ $OS = 'IRIX' ]
  then
     if [ -r color.map ]
     then mademap=
     else /usr/sbin/savemap color.map	# if user does not have color.map
          mademap=1			# create it
     fi
  elif [ $OS = 'HP-UX' ]
  then
     # Ensure F9/F10 are on the left pair of blank buttons
     /usr/bin/X11/xmodmap -e "keycode 45 = F9" -e "keycode 41 = F10"
  fi
fi

if [ $OS = 'OSF1' ]
then
   uac p 0
fi

#
if  [ ! -r core ]
then
# make a core file, write protected, to avoid core dumps.
   echo ' ' > core
   chmod 444 core
   coremade=1
   coreprotect=
else
   coremade=
   if [ -w core ]
   then
# write protect existing core file, to avoid core dump.
      chmod u-w core
      coreprotect=1
   else
      coreprotect=
   fi
fi

RunCerius2()
{
trap '' 2
if [ -n "$NO_GRAPHICS" ]
then exe=cerius2ns.exe
else exe=cerius2.exe
fi

if [ -r ./setcerius2.dev ]
then . ./setcerius2.dev
fi

Cerius2=
for exedir in `echo $PATH | sed -e 's/:/ /g'`
do
   if [ -x $exedir/$exe ]
   then Cerius2=$exedir/$exe; break
   fi
done
if [ -z "$Cerius2" ]
then echo "Cannot find executable $exe in $PATH" >&2
     exit 3
fi
[ -n "$development" ] && echo "Using $Cerius2"

cat < /dev/null > $lock		# creating lock
Redirected mstart.exe $Cerius2 $inputfile 
rm -f $lock			# deleting lock
#
if [ "$coremade" ]
then
# remove core file
   chmod 777 core
   /bin/rm -f core
elif [ "$coreprotect" ]
then
# remove the write protection
   chmod u+w core
fi
if [ "$autohelpmade" ]
then
   /bin/rm -rf autohelp
fi
#
# clean up graphics
#
if [ -z "$DISPLAYREMOTE" ]
then
   if [ "$OS" = 'IRIX' ]
   then
      if [ "$mademap" ]
      then
         /usr/sbin/loadmap color.map
         /bin/rm -f color.map
      fi
   fi
fi
#
# Remove whatever links were set up to data directories.
#
for i in $RemoveLater
do
   /bin/rm -f $i
done
}

if [ "$background" ]
then RunCerius2 &
     echo "Your job is running in the background"
else RunCerius2
fi
