#!/bin/sh

# This script locates the directory it is installed in, and sets up
# environment variables to point to that directory.  Winelib-based
# applications will reference this environment variable in the
# wine config file.  

# locate the directory in which we are installed
mypath=
case $0 in
    /*) mypath=$0;;
    */*) mypath=$0;;
    *)  old_ifs=$IFS
        IFS=:
        # normalize the path
        # (there's a special case where, if the path begins or ends
        # with a colon, it is equivalent to the path beginning or
        # ending with a "."
        search_path=`echo $PATH | sed 's/::/:.:/g;s/^:/.:/;s/:$/:./'`
        for sp in $search_path; do
          if [ -x "$sp/$0" ]; then
            mypath="$sp/$0"
            break
          fi
        done
        IFS=$old_ifs
        ;;
esac

if [ x$mypath = x ]; then
    echo "Error -- unable to determine the directory in which $0 is installed"
    exit 1
else
    # mypath is now the name of the executable
    # we want to strip off the executable name and the 'bin' directory
    # to get the top-level directory we're installed in
    mypath=`dirname $mypath`
    mypath=`cd $mypath; pwd`
    myimmediatedir=`basename $mypath`
    if [ x$myimmediatedir != xbin ]; then
      echo "Error -- I was expecting to be installed in a directory named 'bin'"
      exit 1
    fi
    mypath=`dirname $mypath`
    # by this point, mypath has to be valid, even if it is /
fi

if [ X`uname -s` = XLinux ]; then
	if [ -x /lib/libc.so.6 ]; then
		glibc_version=`/lib/libc.so.6 |head -1 | sed 's/.*version '//g | cut -f1 -d,`
		case "$glibc_version" in
			*2.2.93*)
				echo "Warning: SynaptiCAD products will not run correctly with glibc version 2.2.93"
				echo "which you appear to have installed.  You must upgrade to a newer version."
				echo "See details in the README file"
				;;
			*);;
		esac
	fi
fi

# We have encountered a few systems where the default stack size is set to
# a remarkably large value, like 2GB.  Our process typically creates three
# threads, and super-large stack sizes prevent us from creating these helper
# threads because it would require at least 6GB of memory, and that's not 
# possible in a 32-bit process.  Ensure the stack size is something
# reasonable here.  Limits are in kilobytes, Linux default is ~10MB
current_stack_limit=`ulimit -s`
# if current limit is above 20MB, try to reduce it
if [ $current_stack_limit = unlimited ] || [ $current_stack_limit -gt 20480 ]; then
    ulimit -s 10240
    current_stack_limit=`ulimit -s`
    # if it's still above 100MB, warn
    if [ $current_stack_limit -gt 102400 ]; then
	echo "Warning: the current default stack size on this system ($current_stack_limit kB)"
	echo "is considerably larger than the default value of ~10240, and extremely"
	echo "large values will reduce the number of threads an application can create."
	echo "Please lower the limit to around 10MB using the 'ulimit' command"
	echo "before launching SynaptiCAD products to prevent errors."
    fi
fi

SYNCAD_HOME="$mypath"
export SYNCAD_HOME
#SYNCAD_TIMEOUT=10
#export SYNCAD_TIMEOUT
WINE_ROOT="$SYNCAD_HOME"
export WINE_ROOT

SYNCAD_VERSION=19.00c
export SYNCAD_VERSION

DOTSYNCAD=$HOME/.SynaptiCAD/19.00
export DOTSYNCAD

TCL_LIBRARY="$SYNCAD_HOME/tcl/lib/tcl8.5"
export TCL_LIBRARY

if [ "X$DISPLAY" = "X" ]; then
    # emulate the usual error message people get when they don't have their
    # DISPLAY environment variable set.  We need to test the DISPLAY variable
    # to see if ssh tunneling is in effect, but nothing will actually fail
    # if it isn't set until we launch the main program.
    echo "Error: Can't open display:" 1>&2
    exit 1
fi

if [ "X$SSH_CLIENT" != "X" -o "X$SSH2_CLIENT" != "X" -o "X$SSH_CONNECTION" != "X" ]; then
    # The user is very probably logged in with ssh.  If the user is using
    # ssh to forward their X connection, TestBencher will take a big 
    # performance hit.
    host_part=`echo $DISPLAY | cut -d: -f1`
    other_part=`echo $DISPLAY | cut -d: -f2`
    display_number=`echo $other_part | cut -d. -f1`
    my_host_name=`hostname`
    my_short_host_name=`echo $my_host_name | cut -d. -f1`
    if [ "X$host_part" = "Xlocalhost" -o "X$host_part" = "X$my_host_name" -o "X$host_part" = "$my_short_host_name" ]; then
	if [ "$display_number" -gt 9 ]; then
	    if [ ! -f $DOTSYNCAD/suppress-ssh-warning ]; then
		echo "------------------------------------------------------------------------------"
		echo "Warning!"
		echo "It looks like you may be using secure shell to forward your X display to a"
		echo "remote computer.  This has a noticable impact on the speed of SynaptiCAD"
		echo "products, and may cause this application to appear sluggish."
		echo "We recommend avoiding secure shell forwarding for maximum performance,"
		echo "unless security or firewall considerations require you to use it."
		echo ""
		echo "If you would like to prevent this message from appearing in the future, run:"
		echo "    touch $DOTSYNCAD/suppress-ssh-warning"
		echo "------------------------------------------------------------------------------"
	    fi
	fi
    fi
fi

[ -d "$DOTSYNCAD" ] || mkdir -p "$DOTSYNCAD"

WINEPREFIX="$DOTSYNCAD/wine_conf-$DISPLAY"
export WINEPREFIX
WINESERVER="$WINE_ROOT/bin/wineserver"
export WINESERVER
WINELOADER=$WINE_ROOT/bin/wine64
export WINELOADER
SYNCAD_WINELOADER=$WINE_ROOT/bin/wine64
WINEDLLPATH=$SYNCAD_HOME/bin/x86_64:$SYNCAD_HOME/bin:$WINE_ROOT/lib64/wine
export WINEDLLPATH
unset WINEDLLOVERRIDES || true

# save original PATH and LD_LIBRARY_PATH so we can restore them when launching
# external applications like web browsers
if [ "X$SYNCAD_SAVED_LD_LIBRARY_PATH" = "X" ]; then
    SYNCAD_SAVED_LD_LIBRARY_PATH="$LD_LIBRARY_PATH"
    export SYNCAD_SAVED_LD_LIBRARY_PATH
fi
if [ "X$SYNCAD_SAVED_PATH" = "X" ]; then
    SYNCAD_SAVED_PATH="$PATH"
    export SYNCAD_SAVED_PATH
fi


LD_LIBRARY_PATH=$SYNCAD_HOME/bin/x86_64:$SYNCAD_HOME/bin:$SYNCAD_HOME/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH
PATH=$SYNCAD_HOME/bin:$PATH
export PATH

if [ ! -d "$WINEPREFIX" -a -x "$WINE_ROOT/bin/wineboot" ]; then
     mkdir -p "$DOTSYNCAD/printers"
     cp "$SYNCAD_HOME/share/wine/wine.inf" "$DOTSYNCAD/"
     cp "$SYNCAD_HOME"/etc/printers/*.ppd "$DOTSYNCAD/printers"

     for ppd in "$DOTSYNCAD"/printers/*.ppd; do
         ppdname=`basename "$ppd" .ppd`
         echo "HKCU,Software\\Wine\\Printing\\PPD Files,\"$ppdname\",,\"$ppd\"" >> "$DOTSYNCAD/wine.inf"
     done

     WINEDLLOVERRIDES="mscoree,mshtml=" "$WINE_ROOT/bin/wineboot" -i > /dev/null 2>&1
     # remove 'My Documents' from the file dialog's "Desktop" directory
     WINEDLLOVERRIDES="mscoree,mshtml=" "$WINE_ROOT/bin/wine64" "$WINE_ROOT/lib64/wine/regedit.exe.so" /D 'HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\Namespace\{450D8FBA-AD25-11D0-98A8-0800361B1103}'
     # remove 'Trash' from the file dialog's "Desktop" directory
     WINEDLLOVERRIDES="mscoree,mshtml=" "$WINE_ROOT/bin/wine64" "$WINE_ROOT/lib64/wine/regedit.exe.so" /D 'HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\Namespace\{645FF040-5081-101B-9F08-00AA002F954E}'
fi

[ -d "$WINEPREFIX/drive_c/windows/fonts" ] || mkdir -p "$WINEPREFIX/drive_c/windows/fonts"

if [ ! -x "$WINEPREFIX/drive_c/windows/fonts/marlett.ttf" ]; then
    (cd "$SYNCAD_HOME/fonts" && tar cf - .) | (cd "$WINEPREFIX/drive_c/windows/fonts" && tar xf -)
    # cp "$SYNCAD_HOME"/fonts/* "$WINEPREFIX/drive_c/windows/fonts/"
fi

# if REQUIRESGCC is set, we will put the path to our copy of gcc
# at the beginning of the PATH to force our software to use the version
# of gcc we ship with.  This should be true for our simulator.
# If false, we'll put our copy of gcc at the end of the PATH so we'll
# default to using the system's gcc unless it's missing. This should be
# the case for the GUI and simwrap, to allow SystemC and sugar
# compilations to use the builtin gcc.
REQUIRESGCC=false

if [ -d "$SYNCAD_HOME/gcc-x86_64" ]; then
    LD_LIBRARY_PATH="$SYNCAD_HOME/gcc-x86_64/lib:$LD_LIBRARY_PATH"
    export LD_LIBRARY_PATH
    if [ X$REQUIRESGCC = Xtrue ]; then
      PATH=$SYNCAD_HOME/gcc-x86_64/bin:$PATH
    else
      PATH=$PATH:$SYNCAD_HOME/gcc-x86_64/bin
    fi
fi

PATH=$SYNCAD_HOME/bin:$PATH
export PATH

#if [ `uname -s` = Linux ]; then
#    LD_ASSUME_KERNEL=2.2.5
#    export LD_ASSUME_KERNEL
#fi

if [ "X$LANG" = "X" -a "X$LC_ALL" = "X" ]; then
    LC_ALL=en_US
    export LC_ALL
fi

# determine the app Winelib library name
appname=$SYNCAD_HOME/bin/x86_64/syncad.exe.so
apparg=

if [ -x "$SYNCAD_WINELOADER" ]; then
  if [ "X$1" = "X--debugenv" ]; then
    SYNCAD_INSIDE_DEBUG_ENVIRONMENT=1
    export SYNCAD_INSIDE_DEBUG_ENVIRONMENT
    echo "Launching a new shell with the environment configured for SynaptiCAD products."
    echo "Type 'exit' to leave this debugging environment and return to your "
    echo "normal environment"
    $SHELL
    echo "Leaving SynaptiCAD environment"
    exit 0
  elif [ "X$1" = "X--debugcmd" ]; then
    if [ "X$2" = "X" ]; then
      echo "You must give a command to run with --debugcmd"
      exit 1
    else
      SYNCAD_INSIDE_DEBUG_ENVIRONMENT=1
      export SYNCAD_INSIDE_DEBUG_ENVIRONMENT
      echo "Launching command \"$2\" in the SynaptiCAD environment"
      $2
      echo "Done running command \"$2\", leaving SynaptiCAD environment"
      exit 0
    fi
  fi
  WINEDLLOVERRIDES="mscoree,mshtml="
  export WINEDLLOVERRIDES
  exec $SYNCAD_HOME/bin/syncad_wrapper "$SYNCAD_WINELOADER" "$appname" $apparg "$@"
fi

echo "Error -- Unable to find a complete installation"
exit 1



