#!/bin/sh

# Copyright INRIA
# Updated : Sylvestre Ledru 2006/2007/2008
# Updated : Simon Lipp 2008  - clean up (get rid of unnecessary sci_args)
#                            - accept arguments with spaces, e.g.
#                               -e "disp(1); disp(2)" (fix bug #2606)

#############################################################################
#                                                                           #
#                       DO NOT MODIFY BELOW THIS LINE                       #
#                                                                           #
#############################################################################

####
#
# Scilab can be installed/used in different ways :
# * ./configure; make install
#    => will install Scilab into /usr/local/ and split files to
#    /usr/local/bin, /usr/local/share/scilab/, /usr/local/lib/scilab/,
#    /usr/local/include/scilab/
# * ./configure --prefix=/my/dir/; make install
#    => will install Scilab into /my/dir/ and split files to
#    /my/dir/bin/, /my/dir/share/scilab/, /my/dir/lib/scilab/
#    /my/dir/include/scilab/
#    Scilab official binary uses this arch
# * ./configure; make install prefix=$(DESTDIR)/usr \
#				   bindir=$(DESTDIR)/usr/bin \
#				   datadir=$(DESTDIR)/usr/share/scilab ...
#    Solution used mainly by Linux packagers
#
## First, this script will look for scilab-bin in :
# * If specified, in the $SCI variable
# * Into the scilab/bin/ directory
# * Into the scilab/ directory (if the user is using a source version and
# scilab has been compiled in this directory)
# * if this file is a symlink to the real one. We browse symlink(s) until we
# find the real "scilab" script file and consider that it is the right
# directory
# * That is all. Don't hesitate to contact us if you see one missing.
#
###

if test ! -z "$SCIVERBOSE"; then
	SCIVERBOSE=1
else
	SCIVERBOSE=0
fi

if test -n "$SCI"; then
	if test ! -d "$SCI/modules"; then
		echo "Cannot find directory $SCI/modules/ !"
		echo "SCI should point to the root data directory of Scilab"
		exit -1
	fi
fi


start_electric_fence() {
	echo "Running Scilab with Electric Fence : "  LD_PRELOAD=libefence.so.0.0 "$SCILABBIN" "$@"
	LD_PRELOAD=libefence.so.0.0 "$SCILABBIN" "$@"
}

start_debug() {
	  if test -n "$DEVENV"; then
		  echo "Running debug of Scilab [gdb]  : " "$SCI"/libtool --mode=execute gdb --args "$SCILABBIN" "$@"
		  "$SCI"/libtool --mode=execute gdb --args "$SCILABBIN" "$@"
	  else
		  echo "Running debug of Scilab [gdb]  : " gdb --args "$SCILABBIN" "$@"
		  gdb --args "$SCILABBIN" "$@"
	  fi
}

start_debug_kdbg() {
	  if test -n "$DEVENV"; then
		  echo "Running debug of Scilab [kdbg]  : " "$SCI"/libtool --mode=execute kdbg "$SCILABBIN"
		  "$SCI"/libtool --mode=execute kdbg "$SCILABBIN"
	  else
		  echo "Running debug of Scilab [kdbg]  : " kdbg "$SCILABBIN"
		  kdbg "$SCILABBIN"
	  fi
}

start_profiling() {
	VALGRIND_OPTIONS=" --show-below-main=yes --num-callers=6 --demangle=no --leak-check=full --show-reachable=yes --smc-check=all --db-attach=yes --gen-suppressions=all --suppressions=$SCI/tools/profiling/valgrind.supp"
	  if test -n "$DEVENV"; then
		  echo "Running profiling of Scilab  : " "$SCI"/libtool --mode=execute valgrind $VALGRIND_OPTIONS "$SCILABBIN" "$@"
		  "$SCI"/libtool --mode=execute valgrind $VALGRIND_OPTIONS "$SCILABBIN" "$@"
	  else
		  echo "Running profiling of Scilab  : " valgrind $VALGRIND_OPTIONS "$SCILABBIN" "$@"
		  valgrind $VALGRIND_OPTIONS "$SCILABBIN" "$@"
	  fi

}

start_profiling_visu() {
	VALGRIND_VISU_OPTIONS=" --tool=callgrind --trace-children=yes --smc-check=all --trace-jump=yes --dump-line=yes --separate-threads=yes"
#--dump-instr=yes 
	if test -n "$DEVENV"; then
		echo "Running profiling visualization of Scilab  : " "$SCI"/libtool --mode=execute valgrind $VALGRIND_VISU_OPTIONS "$SCILABBIN" "$@"
		"$SCI"/libtool --mode=execute valgrind $VALGRIND_VISU_OPTIONS "$SCILABBIN" "$@"
	else
		echo "Running profiling visualization of Scilab  : " valgrind $VALGRIND_VISU_OPTIONS "$SCILABBIN" "$@"
		valgrind $VALGRIND_VISU_OPTIONS "$SCILABBIN" "$@"
	  fi
}

find_docbook_path() {
	if test -z "$DOCBOOK_ROOT"; then
		for dir in $SCI/thirdparty/docbook /usr/share/sgml/docbook/stylesheet/xsl/nwalsh /usr/share/docbook2X/xslt/man/ /usr/share/xml/docbook/stylesheet/nwalsh/ /usr/share/xml/docbook/stylesheet/nwalsh/current/ /sw/share/xml/xsl/docbook-xsl /usr/share/xml/docbook/xsl-stylesheets-*/ /usr/share/sgml/docbook/xsl-stylesheets-*/; do
			if test -r "$dir/javahelp/javahelp.xsl"; then
				if test -z "$DOCBOOK_ROOT"; then
					DOCBOOK_ROOT=$dir
					export DOCBOOK_ROOT
				fi
			fi
		done
	fi
	if test $SCIVERBOSE -ne 0; then
		echo "DOCBOOK : $DOCBOOK_ROOT"
	fi
}


SCILABBIN="scilab-bin"

OLDPWD=`pwd`

# Use scilab-bin in the current dir if it exists
# If not, then start resolving symlinks until we find scilab-bin
found=0
progname="$0"
curdir=`dirname "$progname"`
PATH="$curdir:$PATH"

progbase=`basename "$progname"`
run_sci="$curdir/$SCILABBIN"
if test -x "$run_sci"; then # scilab-bin is in the /bin/ directory
	cd "$curdir/../"
	SCI=`pwd`
	SCIBIN=$run_sci
	found=1
else
	run_sci="$curdir/../$SCILABBIN"
	if test -x "$run_sci"; then # scilab-bin is in the / directory
		# which is the case in a dev env
		cd "$curdir/../"
		SCI=`pwd`
		SCIBIN=$run_sci
		found=1
	else
		here=`/bin/pwd`
		while test -h "$progname"; do
			bn=`basename "$progname"`
			cd `dirname "$progname"`
			# Browse the symlink to the real one
			progname=`/bin/ls -l "$bn" | sed -e 's/^.* -> //' `
			if test ! -x "$progname"; then
				break
			fi
			curdir=`dirname "$progname"`
			if test -x "$curdir"; then
				cd "$curdir/../"
				SCI=`pwd`
				SCIBIN="$curdir/$SCILABBIN"
				found=1
				break
			fi
			# The current file ($0), probably scilab is a symlink to the real one and here, it is the dev env
			run_sci="$curdir/../$SCILABBIN"
			if test -x "$run_sci"; then
				cd "$curdir/../"
				SCI=`pwd`
				SCIBIN=$run_sci
				found=1
				break
			fi
		done
		cd "$here"
	fi
	if test $SCIVERBOSE -ne 0; then
		echo "I think I found Scilab here : $SCI"
	fi
fi


if test -x "$SCI/bin/$SCILABBIN"; then
# real env
	SCILABBIN=$SCI/bin/$SCILABBIN
	SCI=$SCI/share/scilab/
else
	if test -x "$SCI/$SCILABBIN"; then
		# dev env
		SCILABBIN=$SCI/$SCILABBIN
		DEVENV=1
		# add modelica in the path
		PATH="$PATH:$SCI/modules/scicos/"
	else
		echo "Cannot find $SCILABBIN ..."
		exit 1
	fi
fi

export SCI
PATH="$SCI:$SCI/bin:$PATH"

############# JAVA DETECTION ##############
#�Basic inspiration from Eclipse
#
# Scilab is looking for Java in various places with different ways :
# * if JAVA_HOME is specificed, use it
# * Check in 'standard' places we know Java could be installed
# if some are missing, please contact us
# * look in the PATH if there is a java binary
# if it is the case, resolve the symlink and set the JAVA_HOME from it
#
# Once we have JAVA_HOME, we check that native libraries (libjava.so and
# 2 others) are available
###

if test "${OS}" = ""; then
        OS=`uname -s` # Retrieve the Operating System                                                                                                         
fi
if test "${MODEL}" = ""; then
        MODEL=`uname -m` # Retrieve the model                                                                                                                 
fi

# Get the proc name matching to the one of the JVM
# Inspiration and data are from http://www.google.com/codesearch?hl=en&q=+java+ppc+libjava.so+show:a78sz0SP41k:zxNozD-vc0A:FWiIy7Hinmg&sa=N&cd=2&ct=rc&cs_p=http://fresh.t-systems-sfr.com/unix/src/misc/tclBlendSrc1.2.5.tar.gz&cs_f=tclBlend1.2.5/configure.in#a0
# For Mac OS X, we will get stuff like that:
# uname -s Power Macintosh
# uname -m Darwin

# If the user has the variable JAVA_HOME in the ENV
if test -n "$JAVA_HOME" ; then
	if test $SCIVERBOSE -ne 0; then
		echo "Using specified vm: $JAVA_HOME"
	fi
    if test ! -x "$JAVA_HOME/bin/java" ; then
		echo "Cannot find $JAVA_HOME/bin/java"
        exit 1
    fi
fi

if test -z "$JAVA_HOME"; then
            case $OS in
                *darwin* | *Darwin*)
                    # Seems to be always that under Mac OS X. Don't hesitate to submit a bug report if it is not the case.
		    JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Home/"
                    LD_LIBRARY_PATH="$JAVA_HOME/../Libraries:$LD_LIBRARY_PATH"
		    if test $SCIVERBOSE -ne 0; then
			echo "Using default Mac OS X vm: $JAVA_HOME"
			echo "And LD_LIBRARY_PATH: $LD_LIBRARY_PATH"
		    fi
		    ;;
                *)
					;;
			esac
fi

# Browse "default directory" (if it means anything under Unix/Linux) of Java
# to find where it could be !
if test -z "$JAVA_HOME"; then
	JAVA_DEFAULT_DIR="/usr/lib/jvm/java-6-openjdk/ /usr/lib/jvm/java/ /usr/lib/jvm/java-6-sun/ /usr/lib/j2se/1.6 /usr/java/jdk1.6.0*/ /usr/java/jdk1.5.0*/ /usr/lib/j2sdk1.6-ibm /usr/lib/jvm/java-1.5.0-sun /usr/java/ /usr/lib/j2se/1.5 /usr/lib/j2se/1.4 /usr/java/jre1.6.0*/ /usr/java/jre1.5.0*/ /usr/lib/j2sdk1.5-ibm /usr/lib/j2sdk1.4-ibm /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.4-sun /usr/lib/jvm/java-gcj /usr/lib/jvm/java-1.5.0-gcj/ /usr/lib/kaffe/pthreads /usr/lib/jvm/java-1.7.0-icedtea-*/ /usr/lib/jvm/jre/"
    for JAVA_HOME in $JAVA_DEFAULT_DIR ; do
		if test $SCIVERBOSE -ne 0; then
			echo "Trying to find Java in $JAVA_HOME "
		fi
		if test -x "${JAVA_HOME}/bin/java" ; then
            export JAVA_HOME
			if test $SCIVERBOSE -ne 0; then
				echo "found"
			fi
            break
        fi
	done
fi

# JAVA_HOME still haven't been found. Well, we can now try to find it in the path

if test -z "$JAVA_HOME"; then
    PATH_SEPARATOR=:
	as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
	if test $SCIVERBOSE -ne 0; then
		echo "Look the binary java in the PATH. If it is a symlink, try to resolve it"
	fi
	for DIR in $PATH; do
		if test -f $DIR/java; then

			_cur=$DIR/java
			# resolve symlink
			# Will probably bug if a file contains -> in the name
			while ls -ld "$_cur" 2>/dev/null | grep " -> " >/dev/null; do
				_cur=`ls -ld "$_cur" | sed 's/.* -> //'`
			done
			# symlink resolved to the real file

			# Now, create JAVA_HOME
			TMP=`dirname $_cur`
			JAVA_HOME=`dirname $TMP`
			if test ! -z "$JAVA_HOME"; then
				break;
			fi
		fi
	done
	IFS=$as_save_IFS
fi
if test ! -z "$JAVA_HOME"; then
	if test $SCIVERBOSE -ne 0; then
		echo "JAVA_HOME : $JAVA_HOME"
	fi

# Manage JRE & JDK because libjava.so and others are stored in the JRE
	if test -d $JAVA_HOME/jre; then
		JRE_HOME=$JAVA_HOME/jre
	else
		JRE_HOME=$JAVA_HOME
	fi

# Configuring LD_LIBRARY_PATH for libjava.so libhpi.so and libxxxx.so

JAVA_SHLIB="libjava.so"

case $OS in
	"Linux")
		case $MODEL in
			"x86_64")
				proc="amd64"
				;;
			i?86)

				if test -d ${JRE_HOME}/lib/`uname -m` ; then
					proc=`uname -m`
				else
					proc="i386"
				fi
				;;
			"ia64")
				proc="i64"
				;;
		    "ppc")
				proc="ppc"
				;;
			"alpha")  
				proc="alpha"
				;;
			*)
				echo "Could not find the Java configuration for the model <${MODEL}>. Please contact us."
				;;
			esac
		;;
	"HP-UX")
		JAVA_SHLIB="libjava.sl"
		proc="lib" # TODO : check if it is right or not ... seems not !
		;;
	"IRIX")
		proc="lib32"
		;;
    "SunOS")
    		case $MODEL in
			"i86pc") # solaris x86
				proc="i386"
				;;
				# check for the 64 bits syntax
			"sparc")
				proc="sparc"
				;;
			*)
				echo "Could not find the Java configuration for the model <${MODEL}>. Please contact us."
				;;
			esac
		;;
	*win32* | *WIN32* | *CYGWIN_NT*)
		proc="win32"
		JAVA_SHLIB="jvm.dll"
		;;
    *darwin* | *Darwin*) # MacOS X
	# For Mac OS X, Since path are different from the JVM normal tree, don't need to detect 
	# the CPU
	JAVA_SHLIB="libjava.jnilib"
	;;
	*)
		echo "Could not find the Java configuration for the OS <${OS}>. Please contact us or submit a bug report with your detailed configuration http://bugzilla.scilab.org/"
		;;
esac

# Check if the lib exists or not (we should manage system where .so is not the
# ext for library
	LIBJAVA="$JRE_HOME/lib/$proc/$JAVA_SHLIB"
	if test ! -f $LIBJAVA; then
		if test $SCIVERBOSE -ne 0; then
			echo "Cannot find $LIBJAVA"
		fi
	else
            CLASSPATH="$CLASSPATH:$SCI/modules/jvm/jar/org.scilab.modules.jvm.jar"
		# @TODO This is the default path of the official sun JVM. 
		# It is different for other implementation of the JVM....
		    LD_LIBRARY_PATH="$JRE_HOME/lib/$proc/:$JRE_HOME/lib/$proc/server/:$JRE_HOME/lib/$proc/native_threads/:$LD_LIBRARY_PATH"
	fi
else
	if test $SCIVERBOSE -ne 0; then
		echo "Have not been able to find any Java VM on this computer. Some features may be broken."
	fi
fi

####### END OF JAVA ENV DETECTION/SETTING ######

# See http://bugzilla.scilab.org/show_bug.cgi?id=3486
# Some Java stuff raises spurious SIGSEGV. The problem is that when bug-buddy
# is enabled, it catches the signal and terminate Scilab. We have to 
# desactivate bug-buddy.
# See also https://bugzilla.novell.com/show_bug.cgi?id=331618
# and: http://bugzilla.gnome.org/show_bug.cgi?id=479929
GTK_MODULES=`echo $GTK_MODULES | sed s/gnomebreakpad//g`
export GTK_MODULES

if test $SCIVERBOSE -ne 0; then
	echo "SCI : $SCI"
	echo "SCIBIN : $SCIBIN"
	echo "PATH : $PATH"
fi

# Returns to the original path
cd "$OLDPWD"

#if test "$DISPLAY" = ""; then
#  DISPLAY="unix:0.0"
#fi
#export DISPLAY

#if test "$PVM_ROOT" = ""; then
#  PVM_ROOT="@PVMROOTR@"
#fi
#export PVM_ROOT

#if test "$PVM_ARCH" = ""; then
#  PVM_ARCH=`$PVM_ROOT/lib/pvmgetarch`
#fi
#export PVM_ARCH

SCILIB=$SCI/bin:$SCI/lib/scilab/:$SCI/lib64/scilab/
LD_LIBRARY_PATH=$SCILIB${LD_LIBRARY_PATH+:$LD_LIBRARY_PATH}

case $OS in
    *darwin* | *Darwin*) # MacOS X
        # When using some packaging tools like fink which are storing the info in /sw/lib
        LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/sw/lib/"
	# Export the path to the Scilab lib when Scilab has been install ...
	# to a Mac os x specific variable used by the linker before LD_LIBRARY_PATH
        DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:$SCI/../../lib/scilab/
	export DYLD_LIBRARY_PATH
        ;;
    *)
esac


if test $SCIVERBOSE -ne 0; then
	echo "LD_LIBRARY_PATH : $LD_LIBRARY_PATH"
	if test ! -z "$DYLD_LIBRARY_PATH"; then
	    echo "DYLD_LIBRARY_PATH: $DYLD_LIBRARY_PATH"
	fi
fi
export LD_LIBRARY_PATH
export PATH

find_docbook_path

do_scilex()
{
    "$SCILABBIN" "$@"

}

do_help()
{
	echo "Usage:"
	echo     "scilab <options>"
	echo     " "
	echo     "      Possible options are:"
	echo     "      -display Display: for use under Xwindow systems to set a specific X server display."
	echo     "      -d Display      : equivalent to display Display."
	echo     "      -debug          : Start Scilab under gdb (Unix/linux only)."
	echo     "      -debug-kdbg     : Start Scilab under kdbg (Unix/linux only)."
	echo     "      -profiling      : Start Scilab under valgrind (Unix/linux only)."
	echo     "      -profiling-visu : Start Scilab under callgrind (Unix/linux only)."
	echo     "      -electric-fence : Start Scilab with the Electric Fence (Unix/linux only)."
	echo     "      -e Instruction  : execute the scilab instruction given in Instruction argument."
	echo     "                        -e and -f options are mutually exclusive."
	echo     "      -f File         : execute the scilab script given in File argument."
	echo     "                        -e and -f options are mutually exclusive."
	echo     "      -l Lang         : set the current language. Lang can be equal to fr or en."
	echo     "      -link <objects> : Is used under Unix/linux to produce a local executable code of Scilab"
	echo     "                        linked with the additional files given by the user in  <objects>."
	echo     "                        the -link option should be used without any other option."
	echo     "      -mem N          : set the initial stacksize, for use with -ns option."
	echo     "      -nb             : do not display the Scilab banner at starting time."
	echo     "      -ns             : do not execute scilab.start startup file."
	echo     "      -nouserstartup  : do not execute the user startup files SCIHOME/.scilab or SCIHOME/scilab.ini."
	echo     "      -nw             : start Scilab without specialized Scilab Window."
	echo     "      -nwni           : start Scilab without the GUI, graphic and help features (batch mode). This option disable the need of Java."
	echo     "      -nogui          : start Scilab without user GUI (batch mode)."
	echo     "      -version        : print product version and exit."
	echo     "      --texmacs       : reserved for TeXMacs."
        echo     " "
	echo     "      All these arguments can be retrieved by the Scilab function sciargs."
        echo     " "
	exit
}

do_compile()
{
	umask 002
	rm -f report
	name=`basename $1 .sci`
	echo generating $name.bin
	echo "predef();getf('$name.sci');save('$name.bin');quit"\
	      | $SCILABBIN -ns -nw | sed 1,8d 1>report 2>&1
	if (grep error report 1> /dev/null  2>&1);
	then cat report;echo " "
	   echo see `pwd`/report for more informations
	   grep libok report>/dev/null;
	else rm -f report;
	fi
	umask 022
	exit 0
}

do_lib()
{
	umask 002
	rm -f report
	echo "$1=lib('$2/');save('$2/lib',$1);quit"\
	      | $SCILABBIN -ns -nw |sed 1,/--\>/d 1>report 2>&1
	if (grep error report 1> /dev/null  2>&1);
	then cat report;echo " "
		echo see `pwd`/report for more informations
		grep libok report>/dev/null;
	else rm -f report;
	fi
	umask 022
	exit 0
}

# calling Scilab with no argument or special cases of calling Scilab
rest="no"
case $# in
    0) # No arg, run Scilab
		do_scilex
        ;;
    2) # Only two arg
        case $1 in
            -comp)
				do_compile $2
                ;;
            -link)
                shift
				$SCI/bin/scilink $SCI $*
                ;;
            -function)
				$SCI/bin/minfopr $SCI $2
				;;
            *)
				rest="yes"
                ;;
        esac
        ;;
    3)
        case $1 in
            -lib)
				do_lib $2 $3
                ;;
            -link)
                shift
				$SCI/bin/scilink $SCI $*
                ;;
            *)
				rest="yes"
                ;;
        esac
        ;;
    *)
        case $1 in
            -link)
                shift
				$SCI/bin/scilink $SCI $*
                ;;
            *)
				rest="yes"
                ;;
        esac
        ;;
esac

# really calling Scilab with arguments

if test "$rest" = "yes"; then

  debug=
  debug_kdbg=
  profiling=
  profiling_visu=
  electric_fence=
  prevarg=
  for sciarg in "$@"
  do

    # If the previous argument needs an argument, skip current one.
    if test -n "$prevarg"; then
      prevarg=
      continue
    fi

    case $sciarg in
      -nogui|-version|-ns|-nb|-nw|-nouserstartup|--texmacs|-nwni)
	      ;;
      -psn_*)
	    # Under Mac OS X, .app is adding the arg -psn_0_xxxx 
	    # (psn = ProcessSerialNumber). It is not used (but could be in the future)
	    ;;
      -display|-f|-l|-e|-d|-args|-mem)
	      prevarg=1
	      ;;
      -debug)
          DEBUG="-debug"
          ;;
      -debug-kdbg)
          DEBUG_KDBG="-debug-kdbg"
          ;;
      -profiling)
          PROFILING="-profiling"
          ;;
      -profiling-visu)
          PROFILING_VISU="-profiling-visu"
          ;;
      -electric-fence)
          ELECTRIC_FENCE="-electric-fence"
          ;;
      *)
          do_help
          ;;
    esac
  done

  if test -n "$DEBUG"; then
	  start_debug "$@"
  else
  if test -n "$DEBUG_KDBG"; then
	  start_debug_kdbg "$@"
  else
	if test -n "$PROFILING"; then
		start_profiling "$@"
	else
		if test -n "$PROFILING_VISU"; then
			start_profiling_visu "$@"
		else
			if test -n "$ELECTRIC_FENCE"; then
				start_electric_fence "$@"
			else
				do_scilex "$@"
			fi # not electric fense
		fi # not profiling visu
	fi # not profiling
  fi # not debug kdbg
  fi # not debug
fi # if rest
