#!/bin/sh 

echo $java.endorsed.dirs

# Result:
# Run JobEditor's Java-programs
JOBEDITOR_HOME=`dirname $0`
APPLI_NAME=`basename $JOBEDITOR_HOME`
export APPLI_NAME
APPLI_LIB=`$JOBEDITOR_HOME/scripts/localsync.sh $JOBEDITOR_HOME/lib/`
#APPLI_LIB=$JOBEDITOR_HOME/lib/
export JOBEDITOR_HOME

applix=`dirname $JOBEDITOR_HOME`
groupsdir="$applix/GPS/Planner"
end_of_list=false
shutdown=false
nodbus=false
nochange=false
pref="default"
LEVEL_OPT=""
if [ "$APPLI_NAME" = "JOBEDITOR" ]; then
	current_release=`/usr/bin/readlink $APPLI_NAME`
else
	current_release=$APPLI_NAME
fi	
current_version=${current_release#JOBEDITOR-}
current_date=`date -r $JOBEDITOR_HOME '+%d.%m.%Y-%H:%M'`
export current_date
export current_release

while test $# -gt 0; do

case "$1" in
   -version*)
   	echo "======================================================================="
	echo "*** Current version : $current_version released on the $current_date***"
	for ver in `/bin/ls $APPLIROOT | grep JOBEDITOR-` ; do
  		versions="$versions \n ${ver#JOBEDITOR-} " 
   done  
   echo "*** Available versions : $versions ***"
   echo "======================================================================="
   exit 1
   ;;

  -shutdown*)
    shutdown=true
    ;;

  -nodbus*)
    nodbus=true
    ;;

  -nochange*)
    nochange=true
    ;;

  -pref=*)
    pref=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` 
    ;;

  -level=*)
    level=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` 
    LEVEL_OPT=-Dcluster.level=$level
    export LEVEL_OPT
    ;;

  -help*)
   echo "======================================================================="
   echo "Usage:" 
   echo "------"
   echo "jobeditor [--version=3.2] [-shutdown|-nodbus] [-pref=fast] [-level=6400] jobs.gsl "
   echo " "
   echo " "
   echo "		--version=3.2	=> force using the version 3.2 of jobeditor"
   echo "		-level=XXXX	=> to force using a level"
   echo "		-pref=fast	=> to use another setting file" 
   echo "	(if first time the file $HOME/.jobeditor/.jobeditor_fast.xml will be created)"
   echo "		-shutdown		=> kill the current instance of jobeditor"
   echo "		-nodbus		=> jobeditor can have several instances"
   echo "		-help		=> display help"
   echo "		-version		=> display the default jobeditor version and all available versions" 
   echo " "
   echo " "   
   echo "======================================================================="
   exit 1
    ;;

  *)
   args="${args} ${1}"
#    end_of_list=true
    ;;
    esac
#
# If the end of list has been encountered, breaks the loop
# without shifting to the next argument.
#
if [ ${end_of_list} = true ] ; then
  break
fi
#
# Remove the argument from argument list, in order to
# pass the remaining arguments to compilation command.
shift
done
echo "settings used : $pref"
echo "job files $args"
trim() { echo $1; }

exec_jobeditor(){
 
 if [ "E$JOBEDITOR_HOME" = "E" ]; then
  JOBEDITOR_HOME="."
 fi
 JAVA_HOME=`$JOBEDITOR_HOME/scripts/find-java-home.sh -min 1.8`

 if [ -z "$JAVA_HOME" ]; then
     exec 1>&2
     echo "Failed to find a java 1.8 virtual machine. You can help me if you set your JAVA_HOME or PATH environment variables"
     exit 1
 fi

  export JAVA_HOME
  PATH=$JAVA_HOME:$PATH
  export PATH

 if [ ! -z "$LM_LICENSE_FILE_JAVA" ] ; then
     LM_LICENSE_FILE=${LM_LICENSE_FILE_JAVA}
     export LM_LICENSE_FILE
 else
     echo "Warning : could not find a license file definition (in environnement variable LM_LICENSE_FILE_JAVA )"
 fi
 echo LM_LICENSE_FILE = $LM_LICENSE_FILE 
 
JARS=""
##############################################
#XPS Environment variable                    #
##############################################
if [ -z "$XPSROOT" ]; then
      XPSROOT=$alt_root/xps
      export XPSROOT
fi
echo XPSROOT = $XPSROOT

##############################################
#SDS Environment variable                    #
##############################################
if [ -z "$SDSROOT" ]; then
      SDSROOT=$alt_root/jobmgr/bin
      
      export SDSROOT
fi
echo SDSROOT = $SDSROOT

###############################################
#Get APPLISITE path                           #
###############################################

if [ -z "$SITE" ]; then
  	if [ -z "$LOGGER" ]; then
    	if [ -z "$CSH_TRICK" ]; then
    		export CSH_TRICK=true
    		echo "Warning: it looks like you do not have an appropriate GCT environment (no LOGGER variable is set)"
    		echo "         Let's try and load a csh..."
    		myself="$0"
    		exec /bin/csh -c "/bin/sh $myself ${1+$@}"
  		else
      		echo "Your environment is not set properly: \$SITE and \$LOGGER are not set)"
      		exit 1
  		fi
	else
		cdir="$groupsdir/Planner_$LOGGER"
	fi
else	
	cdir="$groupsdir/Planner_$SITE"
fi

if [ -d "$cdir" ]; then
  # ensure $USER is set to something useful for the log files name pattern
  if [ -z "$USER" ]; then
    if [ -z "$LOGNAME" ]; then
        USER=`basename "$HOME"`
      else
        USER="$LOGNAME"
    fi
  fi
  # clean-up old log files
else
  exec 1>&2
  echo "Error: cannot find or read configuration directory"
  echo "   Please contact the administrator to set a directory Planner_$SITE"
  echo "   Configuration directory = $cdir"
  exit 1
fi
SITEPATH="$cdir" 
export SITEPATH
if [ -z "$SITEPATH" -o ! -d "$SITEPATH" ]; then
	echo "The site path is not valid: \"$SITEPATH\""
	exit 1
fi
GPSDIR=$APPLI_DISTRIB/../GPS
echo "site path = $SITEPATH"
echo "JAVA_HOME = $JAVA_HOME"


if [ -z "$MAXMEM" ]; then
	MAXMEM=1024
	export MAXMEM
fi
if [ -z "$WITHCOMMENT" ]; then
	WITHCOMMENT="no"
	export WITHCOMMENT
fi
# Detect Exceed, and disable anti-aliasing if needed
xdpyinfo | egrep '^vendor string:.*(Hummingbird|Open Text)' > /dev/null
if [ $? = 0 ]; then
  aa="false"
else
  aa="on"
fi

for ajar in `/bin/ls $APPLI_LIB | egrep '(jar|zip)$'` ; do
  JARS=$APPLI_LIB/$ajar:$JARS
done
export CLASSPATH="$JOBEDITOR_HOME/PVR_JobEditor.jar:$JARS"
ORACLE_OPT=""
if [ ! -z "$TNS_ADMIN" ]; then
	ORACLE_OPT=-Doracle.net.tns_admin=$TNS_ADMIN
fi
export ORACLE_OPT

echo "TNS_ADMIN = $TNS_ADMIN"

$JAVA_HOME/bin/java -Xmx10G -Dcom.sun.management.jmxremote \
-Dcluster.appliroot=$APPLIROOT \
-Dcluster.unique=$ISUNIQUE \
-Dcluster.dir=$JOBEDITOR_HOME \
-Dcluster.settings=$pref \
-Dcluster.alt_root=$alt_root  \
-Dcluster.proj_root=$proj_root $LEVEL_OPT \
-DXPSROOT=$XPSROOT \
-DLM_LICENSE_FILE=$LM_LICENSE_FILE\
-Dcluster.withComment=$WITHCOMMENT \
-DAPPLISITE=$SITEPATH \
-DAPPLIDISTRIB=$JOBEDITOR_HOME \
-DPLANNER_HOME=$APPLIROOT/PLANNER \
-Dgaia.io.protocols.sds.cli_version="1" \
-Dgaia.io.protocols.wz.cli_version="2_nometa" \
-Duser.language=ru \
-Duser.region=RU \
-Dgaia.jnilibpath=$JOBEDITOR_HOME/lib/jnilib  $ORACLE_OPT \
ru.cluster.xjob.main.XjobMain $args
}
#echo $DISPLAY | egrep ':[0-9]+\.' > /dev/null 
#if [ $? -ne 0 ]; then
	# Explicitly set the display screen to 0
	# This avoids possible compatibility problems with older versions of GaiaRing
#export DISPLAY=$DISPLAY.0
#fi

if [ ${shutdown} = true ]; then
  corering -call ru.sovfransgeo.jobeditor /JobEditor shutdown
  exit $?
fi
ISUNIQUE="yes"
if [ ${nodbus} = true ]; then
  ISUNIQUE="no"
  echo "Launching new JobEditor service"
  exec_jobeditor "$@" &
  exit 0
fi

# ensure availability of dbus session
corering -check

# No args

if [ -z "$args"  ]; then
   echo "Trying to show available frame"
   corering -call ru.sovfransgeo.jobeditor /JobEditor showFrame "string:$pref"> /dev/null 2>&1
   if [ $? -ne 0 ]; then
      echo "No available frame."
      echo "Launching new JobEditor service"
      exec_jobeditor "$@" &
      exit 0
   fi
   exit 0
fi

# Special case for external applications that need to know when JobEditor returns
if [ ${nochange} = true ]; then
  # No fork (no ampersand), the shell will be replaced by the java command
  exec_jobeditor "$@"
fi
corering -call ru.sovfransgeo.jobeditor /JobEditor checkPresence
if [ $? -ne 0 ]; then
  echo "Launching new JobEditor service"
  exec_jobeditor "$@" &
else
  for f in "$args"
  do
    echo "Sending file: $f ..."
    # need to get the absolute path for the remote application
    fdir=`dirname "$(trim $f)"`
    fdir=$(cd $fdir && pwd)
    fname=`basename "$(trim $f)"`
    f="$fdir/$fname"
    corering -call ru.sovfransgeo.jobeditor /JobEditor openFile "string:$f" "string:$pref" > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      echo "Communication with JobEditor service failed. Trying to launch a fresh instance"
      exec_jobeditor "$@" &
      exit 0;
    fi
  done
  corering -call ru.sovfransgeo.jobeditor /JobEditor showFrame > /dev/null 2>&1
fi
