#!/bin/ksh
# -----------------------------------------------------------------------------
# Copyright Dassault Systemes, 1999, 2011
# -----------------------------------------------------------------------------

# fiperenv - Set up Environment and shell variables needed to run Isight and SEE programs.
#
# The following environment variables may be set in the user's environment
# to get special processing.  All of these are optional.
#   SH_DEBUG       - set to any value to trace execution of this script
#   FIPER_JVMPARMS - extra flags for the Java command, such as '-verbose:gc'
#   FIPER_ADDPATH  - extra Jar files or directories to add to the Classpath
#                    Entries may be absolute paths to Jar files, or simple names to
#                    look up the file in the docs/java and docs/javacommon directories.
#   FIPER_TEMP     - directory for temporary files.  Defaults to $TMPDIR/fiper-$USER
#   FIPER_CONF     - location of configuration files.  Defauts to $FIPER_HOME/../config
#   FIPER_MEM      - Size of Java heap.   Defaults to 3000M, perhaps too large.
#   FIPER_PERM     - Size of Java Permanent Generation.   Defaults to 256M
#   CATInstallPath - directories to search for installation files. 
#                    Is only used in a development environment.
#   FIPER_ABAQUS   - location of Abaqus installation for the Abaqus component.
#   FIPER_JRE      - Java runtime to use for execution.
#   FIPER_ABAQUS   - directory for Abaqus when running Abaqus componet
#   MATLAB         - Location of MATLAB install for MATLAB component
#
# These variables can also be set in a per-user configuration script $HOME/.fiper.sh.
#
# This file must be called from each of the Fiper startup scripts, and by any
# user code that uses Fiper libraries.  The calling sequence is:
#    dir=/directory-containing-fiperenv-script
#    . $dir/fiperenv
#
# This is necessary because the "." command does not set $0, so variable
# $dir is used instead.
# If your script is in the same directory as fiperenv, the following also works:
#      dir=`command -v $0`
#      dir=`dirname $dir`
#      . $dir/fiperenv
#
############################################################################

# turn on debugging if user set environment variable SH_DEBUG to anything
if [ -n "$SH_DEBUG" ]; then 
    set -x; 
fi

############################################################################
# Find the fiper home directory from the value of $dir.

# get rid of CDPATH and a cd function if it is set - it causes 'cd' to misbehave below
unset CDPATH
unset cd

# Set $dir to the location of this script in case it wasn't set already
# This only works if fiperenv is called from a script in the FIPER/bin directory.
if [ -z "$dir" ]; then
    dir=`command -v $0`
    dir=`dirname $dir`
fi

# FIPER_HOME is the PARENT of the directory containing this file
# The following also resolves symlinks in the directory path.
FIPER_HOME=`cd "$dir/../.."; \pwd`
export FIPER_HOME

# Utility to print a message to stderr and exit
die() {
    echo "$1" >&2
    exit 2
}

# Function to look up a file on a path.
# usage: WhichDir RELPATH SEARCHPATH
WhichDir() {
    n=$1
    p=$2
    r=''
    IFS=':'
    for d in $p; do
        r="$d/$n"
        [ -e "$r" ] && break
    done
    unset IFS
    if [ ! -e "$r" ]; then
        die "Unable to find file '$n' in path '$p'"
    fi
    echo "$r"
}

##################
# Get the platform specification for the current machine
# sets ESI_ARCH to the directory name of the platform

os=`uname -s`
ver=`uname -r`
mach=`uname -m`

ESI_ARCH=""

case "${os}_${ver}_${mach}" in
    SunOS_5.1[0-9]_sun[45]*)
        ESI_ARCH=solaris_a64
        exampleBin=SunOS_5.8_sparc
        ;;

    AIX*)
        mainver=`uname -v`
        ver="$mainver.$ver"
        mach=`uname -p`
        case "${os}_${ver}_${mach}" in
            AIX_6.[0-9]*_powerpc)
                ESI_ARCH=aix_a64
                ;;
        esac
        exampleBin=AIX_5.2_ppc
        ;;

    Linux_2.[67]*_*64 | Linux_3.[012]*_*64 | Linux_4.[0-9]*_*64)
        # Linux 64. 
        ESI_ARCH=linux_a64
        exampleBin=Linux_x64
        ;;
esac

if [ -z "$ESI_ARCH" ]; then
    die "Fiper does not support version <$ver> of platform $os  $mach" 
fi
export ESI_ARCH

# Check that the execution platform matches the execution directory.
rtvdir=`basename "$FIPER_HOME"`
if [ "$ESI_ARCH" = "$rtvdir" ]; then
    : OK
elif [ "$ESI_ARCH" = 'linux_a64' -a "$rtvdir" = 'linux_b64' ]; then
    : this is also OK
else
    echo "WARNING: You are running on platform $ESI_ARCH from an install for platform $rtvdir" >&2
    echo "     This is unlikely to work!" >&2
fi

##################
# Read overrides from override file ~/.fiper.sh.
# The precidence for settings is: .fiper.sh, ENV, default in this file

# Read overrides of FIPER_ variables from file in user's home directory.
if [ -f "$HOME/.fiper.sh" ]; then
   . "$HOME/.fiper.sh"
fi

##################
# Default variables not already set.

# Maximum Java heap size
if [ -z "$FIPER_MEM" ]; then
    FIPER_MEM=3000M
fi
if [ -z "$FIPER_PERM" ]; then
    FIPER_PERM=256M
fi

# Figure out temp directory and TEMPLIB directory if not set in env or .fiper.sh.

if [ -z "$FIPER_TEMP" ]; then
    # get the real user name.  $USER is wrong after 'su'
    if [ "$ESI_ARCH" = 'solaris_a64' ]; then
        USER=`/usr/ucb/whoami`
    else
        USER=`/usr/bin/whoami`
    fi
    # default to $TMPDIR/fiper_$USER with fallbacks if these are unset
    FIPER_TEMP="${TMPDIR:-/usr/tmp}/fiper_$USER"
fi
mkdir -p "$FIPER_TEMP"
if [ $? -ne 0 ]; then
    die "Failed to create temporary directory $FIPER_TEMP.  Cannot continue."
fi
export FIPER_TEMP

# Find a UNIQUE directory in FIPER_TEMP to use to cache shared libs and executables
# This file must be on PATH and LD_LIBRARY_PATH so it has to be created
# before Java is started.  Note that $$ is the shell process ID.
# Try only 100 times to get a unique name, then fail.
# mkdir returns 0 if it creates the directory and non-zero if it exists or fails to create
n=$$
nx=`expr $n + 100`
until FIPER_TEMPLIB="$FIPER_TEMP/templib$n"; mkdir "$FIPER_TEMPLIB" 2>/dev/null
  do
    n=`expr $n + 1`
    if [ $n -gt $nx ]; then
        die "Unable to create unique directory $FIPER_TEMPLIB in 100 tries.  Cannot continue."
    fi
  done
export FIPER_TEMPLIB

##################
# See if we are running in a development environment (CATInstallPath is set).
# If we are, certain operations are different.

if [ -n "$CATInstallPath" ]; then
    # In development environment.  Search CATInstallPath for files.
    
    if [ -z "$FIPER_JRE" ]; then
        FIPER_JRE=`WhichDir "code/jre8" "$CATInstallPath"`
    fi
    LaunchpadJar=`WhichDir docs/java/SMAFIPlaunchpad.jar $CATInstallPath`
    export LaunchpadJar

    # Expand CATInstallPath into a path to bin directories
    IFS=:
    FiperPath=''
    for p in $CATInstallPath; do
        if [ -n "$FiperPath" ]; then
            FiperPath="$FiperPath:$p/code/bin:$p/code/command"
        else
            FiperPath="$p/code/bin:$p/code/command"
        fi
    done
    unset IFS
    FiperPath="$FiperPath:$FIPER_JRE/bin"

    # Sanity test - does CATInstallPath home contain a critical set of jar files
    WhichDir docs/java/SMAFIPsdk.jar "$CATInstallPath" >/dev/null
    WhichDir docs/javacommon/stax-api-1.0.1.jar  "$CATInstallPath" >/dev/null

else
    # In production environment.  Everything is relative to FIPER_HOME.

    CATInstallPath="$FIPER_HOME"
    if [ -z "$FIPER_JRE" ]; then
        FIPER_JRE="$FIPER_HOME/code/jre8"
    fi
    LaunchpadJar="$FIPER_HOME/docs/java/SMAFIPlaunchpad.jar"
    export LaunchpadJar

    # Sanity test - does fiper home contain a critical library
    if [ ! -f "$FIPER_HOME/docs/java/SMAFIPsdk.jar" -o \
        ! -f "$FIPER_HOME/docs/javacommon/stax-api-1.0.1.jar" ]; then
        die "Unable to locate FIPER_HOME, unable to continue.  Best guess was $FIPER_HOME"
    fi

    FiperPath="$FIPER_HOME/code/bin:$FIPER_HOME/code/command:$FIPER_JRE/bin"
fi

export FIPER_JRE

# Now have CATInstallPath (perhaps a single directory) and FIPER_JRE.
# Confirm that JRE is usable
#$FIPER_JRE/bin/java -version 2>"$FIPER_TEMP/javaversion"
#egrep '1\.[678]' "$FIPER_TEMP/javaversion" >/dev/null
$FIPER_JRE/bin/java -version 2>&1 | egrep '1\.[678]' >/dev/null
st=$?
#rm -f "$FIPER_TEMP/javaversion"
if [ $st -ne 0 ]; then
    die "Java in '$FIPER_JRE' will not run or has wrong version."
fi

##################
# Configuration settings.  These are used by script 'launch'

# Base classpath for all Fiper programs. Names are searched in FIPER_HOME/docs/java
# and FIPER_HOME/docs/javacommon (and for each directory in CATInstallPath)
FiperJars="SMAFIPsdk.jar:SMAFIPdesktopSDK.jar:SMAFIPsystemsdk.jar:SMAFIPfrapisdk.jar:\
SMAFIPfrapi.jar:SMAFIPfrapi-client.jar:SMAFIPsdk-generator.jar:SMAFIPutiljni.jar:SMAFIPpse.jar:SMAFIPpse-client.jar:SMAFIPlibrary.jar:SMAFIPlibrary-client.jar:\
SMAFIPcommon.jar:SMAFIPdatabase.jar:SMAFIPvschema.jar:SMAFIPdatatypes.jar:SMAFIPmev.jar:\
SMAFIPdesigndrivers.jar:SMAFIPstation.jar:SMAFIPejbcommon.jar:SMAFIPdb_monitor.jar:\
SMAFIPfiper-common-approx.jar:SMAFIPdev-visual-util.jar:SMAFIPfrapiutil.jar:\
SMAFIPvisual-sitraka.jar:SMAFIPvisual-avs.jar:SMAFIPpersistence.jar:SMAFIPisightnet.jar:\
jgraphx.jar:dynamicjava.jar:jakarta-regexp.jar:truezip-6.7beta2.jar:\
xstream.jar:SMAFIP-xmlpull-1.1.3.1.jar:commons-net-1.4.0.jar:jython.jar:castor-0.9.3.9-xml.jar:axis.jar:\
commons-logging-1.0.1.jar:dom4j.jar:jaxr-api.jar:jaxrpc-ri.jar:javaee-api7.jar:johnzon-core.jar:\
jaxr-ri.jar:saaj-api.jar:saaj-ri.jar:activation.jar:DatePicker-V0.99-2006.09.01.jar:\
stax-api-1.0.1.jar:stax-1.2.0_rc2-dev.jar:jcchart.jar:jcchart3dj2d.jar:vecmath.jar:\
soap.jar:j2ee.jar:jniwrap.jar:comfyj.jar:winpack.jar:mail.jar:openviz3.jar:\
SMAFIPvisual-avs-component.jar:SMAFipAntiSamy.jar:SMAFipGson2.3.1.jar:SMAFip-gluegen-rt.jar:\
gluegen-rt-natives-linux-amd64.jar:jogl-all.jar:jogl-all-natives-linux-amd64.jar:slf4j-api.jar:SMAFIP-slf4j-simple-1.7.21.jar:py4j.jar"

FiperExampleBin="$FIPER_HOME/examples/models/simcodes/bin/$exampleBin"

# If MATLAB is defined, must add it to the path also
if [ -n "$MATLAB" ]; then
    FiperPath="$FiperPath:$MATLAB:$MATLAB_SHLIB"
fi

# If FIPER_ABAQUS is set, add it to the path also.  Allow override by installer.
if [ -z "$FIPER_ABAQUS" ]; then
     # following line can be edited by installer to set a real path
     FIPER_ABAQUS=
fi
if [ -n "$FIPER_ABAQUS" ]; then
     export FIPER_ABAQUS
     FiperPath="$FiperPath:$FIPER_ABAQUS/Commands"
fi

if [ -z "$FIPER_CONF" ]; then
    FIPER_CONF="$FIPER_HOME/../config"
fi

# Must set env variable DSLS_CONFIG if using DSLS and have local DSLicSrv.txt file
if [ "$DSLS_CONFIG" = '' ] ; then
    fls="$FIPER_LICENSE_SYTSTEM"
    if [ "$fls" = '' -a -e "$FIPER_CONF/licenseSystem.dat" ]; then
        fls=$(head -n 1 "$FIPER_CONF/licenseSystem.dat")
    fi
    if [ "$fls" = 'DSLS' -a -e "$FIPER_CONF/DSLicSrv.txt" ]; then
        # Need to set DSLS_CONFIG
        DSLS_CONFIG="$FIPER_CONF/DSLicSrv.txt"
        export DSLS_CONFIG
    fi
fi

#  Note the large memory allocation
JVMParms="-Xms32M '-Xmx${FIPER_MEM}' '-Dfiper.system.installpath=${CATInstallPath}' \
'-Dfiper.system.temp=${FIPER_TEMP}' '-Dfiper.system.templib=${FIPER_TEMPLIB}' \
'-Dfiper.system.configpath=${FIPER_CONF}'"

#-- WebSphere client tracing.  Uncomment to see connection messages.
#JVMParms="$JVMParms -DtraceSettingsFile=WASTrace.properties"

##############################################################################################
# WEBSPHERE 7 DOES NOT NEED THIS, AND IT CAUSES PERFORMANCE PROBLEMS:
##############################################################################################
# Set up extension path for WebSphere.  Also works for WebLogic.
#wasClient=`WhichDir reffiles/ejbclient/websphere7 "$CATInstallPath"`
#JVMParms="$JVMParms \
#'-Djava.ext.dirs=$FIPER_JRE/lib/ext:$wasClient/lib:$wasClient/plugins:$wasClient/lib/WMQ/java/lib' \
#'-Djava.endorsed.dirs=$wasClient/endorsed:$FIPER_JRE/lib/endorsed'"
##############################################################################################

# Set the path to include Fiper, Java, the Fiper examples, and the external programsP
PATH="${FIPER_TEMPLIB}:${FiperPath}:${PATH}:${FiperExampleBin}"
export PATH


##################
# Set up platform-specific paths and environment variables
# Also, add the WebSphere pluggable client libs to the extension class path

case ${ESI_ARCH} in

    solaris_a64)
        LD_LIBRARY_PATH="${FIPER_TEMPLIB}:${FiperPath}:${MATLAB_SHLIB}:${LD_LIBRARY_PATH}"
        export LD_LIBRARY_PATH

        #FIXME temporary add Intel FORTRAN files to LD_LIBRARY_PATH
        LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:$(WhichDir code/SMAFIPfortran "$CATInstallPath")"

        # Force 64-bit mode in the JVM
        JVMParms="-d64 ${JVMParms}"

        # Increase ulimit for open files if needed.
        a=`ulimit -nS`
        if [ "$a" != 'unlimited' -a "$a" -lt 2048 ]; then
            ulimit -nS 2048
        fi
        ;;

    linux_a64)
        # 64-bit Linux requires extra flag in JVMparms
        JVMParms="${JVMParms} -XX:-ReduceInitialCardMarks"
        LD_LIBRARY_PATH="${FIPER_TEMPLIB}:${FiperPath}:${MATLAB_SHLIB}:${LD_LIBRARY_PATH}"
        export LD_LIBRARY_PATH

		typeset -u osName
		osName="RHEL"
		if [ -f /etc/os-release ]; then
			osName=$(cat /etc/os-release | grep 'NAME')
		fi
		
		# ksh in Suse 12.*, 15.1 does not support -u flag of ulimit, so handle it by running ulimit using bash
		if [[ "$osName" == *"SUSE"* ]]; then
			# Increase ulimit on number of processes if needed.
			a=$(bash -c "ulimit -S -u")
			b=$(bash -c "ulimit -H -u")
			if [ $a = 'unlimited' -o $a -ge 30000 ]; then
				: Do nothing, we are OK.
			elif [ $b = 'unlimited' -o $b -ge 30000 ]; then
				# We have room to increase ulimit.
				$(bash -c "ulimit -S -u 30000")
			elif [ $b -gt $a ]; then
				$(bash -c "ulimit -S -u $b")
			fi
			a=$(bash -c "ulimit -S -u")
			if [ $a != 'unlimited' -a $a -lt 5000 ]; then
				echo "Warning: Insufficient threads to execute some programs."
				echo "         Current 'ulimit -u' is $a; need at least 5000."
			fi
		else
			# non SUSE Linux like RHEL
			# Increase ulimit on number of processes if needed.
			a=`ulimit -S -u`
			b=`ulimit -H -u`
			if [ $a = 'unlimited' -o $a -ge 30000 ]; then
				: Do nothing, we are OK.
			elif [ $b = 'unlimited' -o $b -ge 30000 ]; then
				# We have room to increase ulimit.
				ulimit -S -u 30000
			elif [ $b -gt $a ]; then
				ulimit -S -u $b
			fi
			a=`ulimit -S -u`
			if [ $a != 'unlimited' -a $a -lt 5000 ]; then
				echo "Warning: Insufficient threads to execute some programs."
				echo "         Current 'ulimit -u' is $a; need at least 5000."
			fi
		fi
	
        ;;


    aix_a64)
        LIBPATH="${FIPER_TEMPLIB}:${FiperPath}:${MATLAB_SHLIB}:${LIBPATH}"
        export LIBPATH
        # AIX does not need java.ext.dirs since it uses the IBM JVM.

        # Suppress dump on an OutOfMemoryError.  Such errors are recoverable
        # and the dumps are large.  Comment out these lines to get a dump
        # on an OutOfMemmoryError
        # See http://download.boulder.ibm.com/ibmdl/pub/software/dw/jdk/diagnosis/diag142.pdf for more information.
        IBM_JAVADUMP_OUTOFMEMORY=FALSE
        export IBM_JAVADUMP_OUTOFMEMORY
        IBM_HEAPDUMP_OUTOFMEMORY=FALSE
        export IBM_HEAPDUMP_OUTOFMEMORY
        ;;
esac

