#!/bin/bash
###################################################
#  Wineskin code for Wineskin and WineskinSC wrappers
#  Made by doh123 (doh123@doh123.com)
#
#  Version 4.9
#  Supports WS4 and WS3 engines
#  Will NOT run WS1 or WS2
#
#  This code is Open Source and licensed under the
#  terms of the GNU Lesser General Public License.
#  If the License file is not with this script, the
#  full license can be read at the following URL
#
#  http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
#
#  For Wineskin information, see the project website at
#  http://wineskin.sourceforge.net
#
####################################################
############## Set osascript for OSX version correct
# need to force 32 bit, except on 10.4, it causes errors
# 64 bit may cause issues with osascript with some 3rd party unpatches software, mainly adobe
function fixforosascript {
if [ "$THEOSVERSION" == "10.4" ]
then
  export OSASCRIPTRUNLINE="/usr/bin/osascript"
else
  export OSASCRIPTRUNLINE="/usr/bin/arch -i386 /usr/bin/osascript"
fi
}

############## get from Info.plist
function GetFromInfoPlist {
exec < "$1"
while read LINE
do
if [ "$OLDLINE" == "<key>$2</key>" ]
then
  if [ "$3" == "string" ]
  then
    TEMPVAR=${LINE#<string>}
    TEMPVAR=${TEMPVAR%</string>}
  fi
  if [ "$3" == "boolean" ]
  then
    TEMPVAR=${LINE#<}
	TEMPVAR=${TEMPVAR%/>}
  fi
fi
OLDLINE="$LINE"
done
echo "$TEMPVAR"
}

############## Set the Display
function SetDisplay {
export DISPLAY=:$[ ( $RANDOM % 100000 )  + 5 ]
}

############## get pid from process name
function getpidof {
ps axc|awk "{if (\$5==\"$1\") print \$1}";
}

############## Set the user folders for wine


############## Start up X11
function StartX11 {
  # Copy plist over
  cp -f "$WSX11PREFSPLIST" "$HOME/Library/Preferences/$PREFFILENAME.plist"
  #need to read X11 config file for install path and version
	exec < "$WINESKINENGINEFOLD/X11/WSConfig.txt"
	i=1
    while read LINE
    do
      if [ $i == 1 ]
	  then
	    X11VERSION="$LINE"
	  elif [ $i == 2 ]
	  then
	    X11INSTALLPATH="$LINE"
	  fi
	  ((i++))
    done
  # new code for handling XKB different in WS4+ engines.  If WS3 need to use old code
  if [ "$X11VERSION" == "WS1" -o "$X11VERSION" == "WS2" -o "$X11VERSION" == "WS3" ]
  then
    if [ "$X11VERSION" == "WS1" -o "$X11VERSION" == "WS2" ]
    then
      #prompt warning that WS1 and WS2 will not work.
	  echo "Wineskin: WS1 or WS2 engine used and not supported!"
      $OSASCRIPTRUNLINE -e "tell application \"System Events\" to activate" -e "tell application \"System Events\" to display dialog \"ERROR! You are using a WS1 or WS2 based engine, and these are not supported in Wineskin 1.2+\" buttons {\"OK\"} default button \"OK\" with icon 0"
    else
      if [ "$SELFCONTAINED" == "true" ]
      then
  	    #need to see if Wineskin already has proper X11 installed on the machine
  	    if [ ! -d "/Library/Wineskin/${X11VERSION}X11.bundle" ]
  	    then
  	      rm "$X11INSTALLPATH" > /dev/null 2>&1
	      ln -s "$WINESKINENGINEFOLD/X11" "$X11INSTALLPATH" > /dev/null 2>&1
	    else
          rm "$X11INSTALLPATH" > /dev/null 2>&1
          ln -s "/Library/Wineskin/${X11VERSION}X11.bundle/X11" "$X11INSTALLPATH" > /dev/null 2>&1
	    fi
      else
        #need to try to set symlink again, in case an old Wineskin wrapper has messed it up.
	    #it could only mess it up if it was running on an admin account, so usually this fix should work...
        #if not running on an admin account, this will fail, but it should already exist from Engine installs.
        rm "$X11INSTALLPATH" > /dev/null 2>&1
        ln -s "/Library/Wineskin/${X11VERSION}X11.bundle/X11" "$X11INSTALLPATH" > /dev/null 2>&1
      fi
      #final test to see if the symlink exists, if not error message... X11 will fail.
      if [ ! -h "$X11INSTALLPATH" ]
      then
        echo "Wineskin: X11 is not running right, possibly not an admin account?"
        $OSASCRIPTRUNLINE -e "tell application \"System Events\" to activate" -e "tell application \"System Events\" to display dialog \"ERROR! Xquartz cannot run. Wineskin WS3 engine wrappers must run on an Admin account.  If you are running a normal wrapper and it is failing, please try re-installing any Engine version to fix this issue, or update things to WS4 based engines.\" buttons {\"OK\"} default button \"OK\" with icon 0"
      fi
    fi
  else
    # WS4+ engine, handle making symlinks differently. they are in /tmp so no Admin account needed for the symlink
	# it should be ok to always remap WS4+ to whatever wrapper wants to, since it should be identical for every WS4+, not breaking any already running.
	# no admin problems since its all done in /tmp
	if [ "$THEOSVERSION" == "10.4" ]
	then
	  # give warning that this will crash on 10.4
	  echo "Wineskin: WS4+ engine used on Mac OS X 10.4, will not work."
	  $OSASCRIPTRUNLINE -e "tell application \"System Events\" to activate" -e "tell application \"System Events\" to display dialog \"ERROR! you are running on Mac OS X 10.4 and using a WS4+ based engine, this will not work, you must use an older WS3 based engine, or upgrade to Mac OS X 10.5+\" buttons {\"OK\"} default button \"OK\" with icon 0"
	  ERRORQUITRUNNING="true";
	  break;
	fi
    rm -rf "$X11INSTALLPATH" > /dev/null 2>&1
	mkdir -p "$X11INSTALLPATH/bin" > /dev/null 2>&1
	mkdir -p "$X11INSTALLPATH/share" > /dev/null 2>&1
    ln -s "$WINESKINENGINEFOLD/X11/bin/xkbcomp" "$X11INSTALLPATH/bin/xkbcomp" > /dev/null 2>&1
	ln -s "$WINESKINENGINEFOLD/X11/share/X11" "$X11INSTALLPATH/share/X11" > /dev/null 2>&1
  fi
   # wineserver check to see if this is a multirun customexe
   exec < "$WINESERVERPIDFILE"
   while read LINE
   do
     WINESERVERPIDTOCHECK=$LINE
   done
   if ! kill -0 ${WINESERVERPIDTOCHECK} > /dev/null 2>&1
   then
     # fix resolution
     if [ "$FULLSCREENOPTION" == "true" ]
     then	
       "$WINESKINENGINEFOLD/X11/WSReso" $VDRESOLUTION > /dev/null 2>&1
     fi
     #change Info.plist to have the executable be X11... only really needed for 10.4
     if [ "$THEOSVERSION" == "10.4" ]
     then
       sed -i "" "s/WineskinLauncher/WineskinX11/" "$INFOPLISTFILE"
     fi
     # set up fontpath variable for server depending where X11 fonts are on the system
     # first check for normal location of /usr/X11/lib/X11/fonts
     if [ -d /usr/X11/lib/X11/fonts ]
     then
       WINESKINX11FONTPATHPREFIX="/usr/X11/lib/X11/fonts"
     # if not found yet, check Xquartz install for older versions /usr/X11/share/fonts
     elif [ -d /usr/X11/share/fonts ]
     then
        WINESKINX11FONTPATHPREFIX="/usr/X11/share/fonts"
     # if not found yet check Xquartz newer installs /opt/X11/share/fonts
     elif [ -d /opt/X11/share/fonts ]
     then
	   WINESKINX11FONTPATHPREFIX="/opt/X11/share/fonts"
     # if not found yet check Macports installs /opt/local/share/fonts
     elif [ -d /opt/local/share/fonts ]
     then
        WINESKINX11FONTPATHPREFIX="/opt/local/share/fonts"
     # if not found yet check OSX 10.4 install /usr/X11R6/lib/X11/fonts
     elif [ -d /usr/X11R6/lib/X11/fonts ]
     then
        WINESKINX11FONTPATHPREFIX="/usr/X11R6/lib/X11/fonts"
     # if still not found, forget it... local X11 isn't installed.
     fi
     #set the path after having the right path prefix
     WINESKINX11FONTPATH="-fp $WINESKINX11FONTPATHPREFIX/75dpi,$WINESKINX11FONTPATHPREFIX/100dpi,$WINESKINX11FONTPATHPREFIX/cyrillic,$WINESKINX11FONTPATHPREFIX/encodings,$WINESKINX11FONTPATHPREFIX/misc,$WINESKINX11FONTPATHPREFIX/OTF,$WINESKINX11FONTPATHPREFIX/Speedo,$WINESKINX11FONTPATHPREFIX/TTF,$WINESKINX11FONTPATHPREFIX/Type1,$WINESKINX11FONTPATHPREFIX/util"
     #start the server
     DYLD_FALLBACK_LIBRARY_PATH="$WINESKINENGINEFOLD/X11/lib:$WINESKINENGINEFOLD/Wine/lib:/usr/lib:/usr/libexec:/usr/lib/system:/usr/X11/lib:/usr/X11R6/lib" "$MACOSFOLD/WineskinX11" $DISPLAY -depth $FULLSCREENRESOLUTIONBITDEPTH +xinerama -br $WINESKINX11FONTPATH -xkbdir "$WINESKINENGINEFOLD/X11/share/X11/xkb" > "$LOGFOLDERPATH/LastRunX11.log" 2>&1 &
     export X11APPPID="$!"
     #change Info.plist to have executable to be WineskinLauncher
     if [ "$THEOSVERSION" == "10.4" ]
     then
       sleep 1
       sed -i "" "s/WineskinX11/WineskinLauncher/" "$INFOPLISTFILE"
     fi
   fi
}

#################### Start up quartz-wm
# errors if X11 is not fully loaded...
function StartQuartzWM {
if ! kill -0 ${WINESERVERPIDTOCHECK} > /dev/null 2>&1
then
  "$WINESKINENGINEFOLD/X11/bin/quartz-wm" --prefs-domain "$PREFFILENAME" > /dev/null 2>&1 &
  QUARTZWMPID=$!
  sleep 1 #need time after trying so that quartz-wm will fail and stop running. if done too fast, it thinks its running, but it shuts down after.
  TESTFORCUTOFF=0
  QUARTZWMFAILED="false"
  while ! kill -0 ${QUARTZWMPID} > /dev/null 2>&1
  do
    "$WINESKINENGINEFOLD/X11/bin/quartz-wm" --prefs-domain "$PREFFILENAME" > /dev/null 2>&1 &
    QUARTZWMPID=$!
	sleep 1
	if [ $TESTFORCUTOFF -gt 10 ] #tries for roughly 10 seconds to start it until it fails.
	then
	  QUARTZWMFAILED="true"
	  break
	fi
	((TESTFORCUTOFF++))
  done
  if [ "$QUARTZWMFAILED" == "true" ]
  then
    echo "Wineskin: Rootless enabled, quartz-wm failed to start!!"
  else
    echo "Wineskin: Rootless enabled, quartz-wm started"
  fi
fi
}

###################### Run Wine!!!
function StartWine {
if [ "$NONSTANDARDRUN" != "true" ]
then
  GIANTLOOPCOUNT=1
  ####
  while [ $GIANTLOOPCOUNT -le 10 ]
  do
  ####
  # make wineserver FIRSTPIDFILE
  echo "00000" > "$FIRSTPIDFILE"
  getpidof wineserver >> "$FIRSTPIDFILE"
  i=1
  exec < "$FIRSTPIDFILE"
  while read LINE
  do
    PIDONECHECK[$i]=$LINE
    pidonetotal=$i
    ((i++))
  done
  # start wineserver
  cd "$WINESKINENGINEFOLD/Wine/bin"
  DYLD_FALLBACK_LIBRARY_PATH="$WINESKINENGINEFOLD/X11/lib:$WINESKINENGINEFOLD/Wine/lib:/usr/lib:/usr/libexec:/usr/lib/system:/usr/X11/lib:/usr/X11R6/lib" ./wineserver > "/dev/null" 2>&1
  sleep 0.5
  #do the loop compare now
  TRYTHREETIMES=1
  while [ $TRYTHREETIMES -le 4 ]
  do
    if [ $TRYTHREETIMES -gt 1 ]
	then
	  sleep 1
	fi
	# make wineserver SECONDPIDFILE
    echo "00000" > "$SECONDPIDFILE"
    getpidof wineserver >> "$SECONDPIDFILE"
    i=1
	c=1
    exec < "$SECONDPIDFILE"
    while read LINE
    do
      PIDTWOCHECK[$i]=$LINE
      pidtwototal=$i
      ((i++))
    done
    while [ $c -le $pidtwototal ]
    do
      ANEQUALOCCURED="no"
      f=1
      while [ $f -le $pidonetotal ]
      do
        if [ $PIDTWOCHECK[$c] == $PIDONECHECK[$f] ]
        then
          ANEQUALOCCURED="yes"
        fi
        ((f++))
      done
      if [ $ANEQUALOCCURED == "no" ]
      then
        WINESERVERFINISHED="yes"
        THEPIDTORETURN="${PIDTWOCHECK[$c]}"
        break
      fi
      ((c++))
    done
	if [ "$WINESERVERFINISHED" == "yes" ]
	then
	  break
	fi
	((TRYTHREETIMES++))
  done
  if [ "$THEPIDTORETURN" == "" ]
  then
    #wineserver failed, check PID file value see if it is running, if is, set to THEPIDTORETURN
	if kill -0 ${WINESERVERPIDTOCHECK} > /dev/null 2>&1
	then
	  THEPIDTORETURN=$WINESERVERPIDTOCHECK
	fi
  fi
  #need to write wineserver PID to a file, for multiple .exes using the same wineserver
  if [ "$THEPIDTORETURN" != "" ]
  then
    echo "$THEPIDTORETURN" > "$WINESERVERPIDFILE"
	echo "$THEPIDTORETURN"
	break
  else
	((GIANTLOOPCOUNT++))
	sleep 1
  fi
  ####
  done
  ####
  #need to change $DISPLAY to display used last time
  if [ "$THEPIDTORETURN" == "$WINESERVERPIDTOCHECK" ]
  then
	exec < "$DISPLAYNUMBERFILE"
    while read LINE
    do
      export DISPLAY=$LINE
    done
  fi
  #write out display for whatever runs next
  echo $DISPLAY > "$DISPLAYNUMBERFILE"
  #set desktop name for VD
  THEDESKTOPNAME="${X11APPNAME%.app}"
  THEDESKTOPNAME="${THEDESKTOPNAME// /_}"
  cd "$WINERUNLOCATION"
  if [ "$DEBUGENABLED" == "yes" ]
  then
    WINELOGFILELINE="$LOGFOLDERPATH/LastRunWine.log"
	export WINEDEBUG=err+all,fixme+all,trace+x11settings
  else
    echo "" > "$LOGFOLDERPATH/LastRunWine.log"
    WINELOGFILELINE="/dev/null"
	export WINEDEBUG=err-all,warn-all,fixme-all,trace+x11settings
  fi
  #make sure correct Wineserver is still running before launching wine app
  if kill -0 ${THEPIDTORETURN} > /dev/null 2>&1
  then
    if [ "$FULLSCREENOPTION" == "true" ]
    then	
      DYLD_FALLBACK_LIBRARY_PATH="$WINESKINENGINEFOLD/X11/lib:$WINESKINENGINEFOLD/Wine/lib:/usr/lib:/usr/libexec:/usr/lib/system:/usr/X11/lib:/usr/X11R6/lib" wine explorer /desktop=$THEDESKTOPNAME,${VDRESOLUTION/ /x}$STARTTOGGLE "$WINERUNFILE"$WSSPACE"$WSGAMEEXEFLAGS" > "$LOGFOLDERPATH/LastRunWine.log" 2>&1 &
    elif [ "$VDRESOLUTION" != "novd" ]
    then
      DYLD_FALLBACK_LIBRARY_PATH="$WINESKINENGINEFOLD/X11/lib:$WINESKINENGINEFOLD/Wine/lib:/usr/lib:/usr/libexec:/usr/lib/system:/usr/X11/lib:/usr/X11R6/lib" wine explorer /desktop=$THEDESKTOPNAME,${VDRESOLUTION/ /x}$STARTTOGGLE "$WINERUNFILE"$WSSPACE"$WSGAMEEXEFLAGS" > "$WINELOGFILELINE" 2>&1 &
    else
      DYLD_FALLBACK_LIBRARY_PATH="$WINESKINENGINEFOLD/X11/lib:$WINESKINENGINEFOLD/Wine/lib:/usr/lib:/usr/libexec:/usr/lib/system:/usr/X11/lib:/usr/X11R6/lib" wine$STARTTOGGLE "$WINERUNFILE"$WSSPACE"$WSGAMEEXEFLAGS" > "$WINELOGFILELINE" 2>&1 &
    fi
  fi
else
  if [ "$TOOLTORUN" == "wineprefixcreate" ]
  then
	cd "$WINEPREFIX/../../WineskinSettings.app/Contents/Resources"
	DYLD_FALLBACK_LIBRARY_PATH="$WINESKINENGINEFOLD/X11/lib:$WINESKINENGINEFOLD/Wine/lib:/usr/lib:/usr/libexec:/usr/lib/system:/usr/X11/lib:/usr/X11R6/lib" WINEDLLOVERRIDES="mshtml=" wine wineboot.exe > /dev/null 2>&1
	cd -
	sleep 3
	# need to change all current user name entires in system and user to use the Public folder
	sed -i "" "s/$USER/Public/" "$WINEPREFIX/system.reg"
	sed -i "" "s/$USER/Public/" "$WINEPREFIX/user.reg"
	sed -i "" "s/$USER/Public/" "$WINEPREFIX/userdef.reg"
    DYLD_FALLBACK_LIBRARY_PATH="$WINESKINENGINEFOLD/X11/lib:$WINESKINENGINEFOLD/Wine/lib:/usr/lib:/usr/libexec:/usr/lib/system:/usr/X11/lib:/usr/X11R6/lib" WINEDLLOVERRIDES="mshtml=" wine "$WINEPREFIX/drive_c/windows/regedit.exe" "$MACOSFOLD/../../WineskinSettings.app/Contents/Resources/remakedefaults.reg" > /dev/null 2>&1
  elif [ "$TOOLTORUN" == "winetricks" ]
  then
    cd "$MACOSFOLD/../../"
    export PATH="$PWD/WineskinSettings.app/Contents/Resources/Winetricks:$PATH"
    DYLD_FALLBACK_LIBRARY_PATH="$WINESKINENGINEFOLD/X11/lib:$WINESKINENGINEFOLD/Wine/lib:/usr/lib:/usr/libexec:/usr/lib/system:/usr/X11/lib:/usr/X11R6/lib" winetricks "$CMDLINEVAR2" > "$LOGFOLDERPATH/Winetricks.log" 2>&1
	if [ "$CMDLINEVAR2" == "gecko" -o "$CMDLINEVAR2" == "gecko-dbg" ]
	then
	  #need to make sure that mshtml is re-enabled in the registry.
	  #it is disabled by default to get rid of Gecko pop up messages
	  GECKOTEMPFILE="$RESOFOLD/geckotempfile.reg"
	  echo "REGEDIT4" > "$GECKOTEMPFILE"
	  echo "" >> "$GECKOTEMPFILE"
	  echo "[HKEY_CURRENT_USER\Software\Wine\DllOverrides]" >> "$GECKOTEMPFILE"
	  echo "\"mshtml\"=\"native,builtin\"" >> "$GECKOTEMPFILE"
	  DYLD_FALLBACK_LIBRARY_PATH="$WINESKINENGINEFOLD/X11/lib:$WINESKINENGINEFOLD/Wine/lib:/usr/lib:/usr/libexec:/usr/lib/system:/usr/X11/lib:/usr/X11R6/lib" wine "$WINEPREFIX/drive_c/windows/regedit.exe" "$GECKOTEMPFILE" > /dev/null 2>&1	  
	  rm "$GECKOTEMPFILE"
	  rm "$WINEPREFIX/.update-timestamp"
	fi
  fi
fi
}

function RunEngineChecker {
ENGINEREQUIRED="$(readlink "$WINESKINENGINEFOLD")"
ENGINEREQUIRED="${ENGINEREQUIRED%.bundle}"
ENGINEREQUIRED="${ENGINEREQUIRED#/Library/Wineskin/}"
if [ "$ENGINEREQUIRED" == "" ]
then
  # readlink failed, it is a WineskinSC wrapper
  SELFCONTAINED="true"
  LOGFOLDERPATH="$RESOFOLD/Logs"
else
  # readlink worked, it is a Wineskin normal wrapper
  SELFCONTAINED="false"
  LOGFOLDERPATH="$HOME/Wineskin/Logs"
  if [ ! -f "$WINESKINENGINEFOLD/Wine/bin/wine" ]
  then
    #engine not installed
    RunWineskin="no"
    RunWineskinNoMessage="Someone tried to run a Wineskin wrapper without the proper engine ($ENGINEREQUIRED) installed, Run Denied!"
    TEMPVAR=$($OSASCRIPTRUNLINE -e "tell application \"System Events\" to activate" -e "tell application \"System Events\" to display dialog \"ERROR! Cannot run! $ENGINEREQUIRED Wineskin Engine is not installed!\" buttons {\"OK\",\"Visit the Wineskin Engine Download Page\"} default button \"OK\" with icon 0")
    if [ "$TEMPVAR" == "button returned:Visit the Wineskin Engine Download Page" ]
    then
      open "http://wineskin.doh123.com/EngineList.html"
    fi
  fi
fi
mkdir "$LOGFOLDERPATH" > /dev/null 2>&1
}


function SleepAndMonitor {
###### Need to pause this program in the background, while monitoring for resolution changes.
echo "Wineskin: sleeping until Wine program finished"
###### Set OLDTIMESTAMP to 0, to force check first time through.
OLDTIMESTAMP="0"
while kill -0 ${WINESERVERPID} > /dev/null 2>&1
do
  if [ "$FULLSCREENOPTION" == "true" ]
  then
    NEWTIMESTAMP=$(stat -f "%m" "$LOGFOLDERPATH/LastRunWine.log")
    if [ $NEWTIMESTAMP -gt $OLDTIMESTAMP ]
    then
      OLDSCREENRESO="$("$WINESKINENGINEFOLD/X11/WSReso")"
      NEWSCREENRESO="$OLDSCREENRESO"
      # log has been changed... read it to look for resolution changes.
      exec < "$LOGFOLDERPATH/LastRunWine.log"
      while read LINE
      do
        # strip off first part of line
        if [ ${#LINE} -gt 54 ]
        then
          FRONTOFLINE="${LINE:0:55}"
          if [ "$FRONTOFLINE" == "trace:x11settings:X11DRV_ChangeDisplaySettingsEx width=" ]
          then
            # parse line for resolution
            NEWSCREENRESO="${LINE#$FRONTOFLINE}"
            NEWSCREENRESO="${NEWSCREENRESO//height=/}"
            NEWSCREENRESO="${NEWSCREENRESO% bpp=*}"
		  fi
		fi
      done
      if [ "$DEBUGENABLED" != "yes" ]
      then
        echo "" > "$LOGFOLDERPATH/LastRunWine.log"
      fi
      OLDTIMESTAMP="$(stat -f "%m" "$LOGFOLDERPATH/LastRunWine.log")"
      # set new resolution
      if [ "$OLDSCREENRESO" != "$NEWSCREENRESO" ]
      then 
        sleep $SLEEPNUMBER
        "$WINESKINENGINEFOLD/X11/WSReso" $NEWSCREENRESO
        echo "Wineskin: adjust resolution to requested (${NEWSCREENRESO/ /x})"
      fi
	fi
  fi
  sleep 1.3
done
}

function CleanUpAndShutDown {
# kill X11
kill -KILL $X11APPPID > /dev/null 2>&1
echo "Wineskin: X11 quit"
# fix $USER back to Wineskin
mv "$WINEPREFIX/drive_c/users/$USER" "$WINEPREFIX/drive_c/users/Wineskin" > /dev/null 2>&1
cd "$WINEPREFIX/drive_c/users/Wineskin" > /dev/null 2>&1
rm "My Documents" > /dev/null 2>&1
rm "Desktop" > /dev/null 2>&1
rm "My Videos" > /dev/null 2>&1
rm "My Music" > /dev/null 2>&1
rm "My Pictures" > /dev/null 2>&1
# remove last Wine log if it still exists, unless in debug mode
if [ "$DEBUGENABLED" != "yes" ]
then
  rm "$LOGFOLDERPATH/LastRunWine.log" > /dev/null 2>&1
fi
}

function WineskinSettingsTools {
TOOLTORUN=${CMDLINEVAR#$CMDLINEVARCHECK-}
if [ "$TOOLTORUN" == "installer" ]
then
  FORCEINSTALLERTONORMALWINDOWS="$(GetFromInfoPlist "$INFOPLISTFILE" "force Installer to normal windows" "boolean")"
  if [ "$FORCEINSTALLERTONORMALWINDOWS" == "true" ]
  then
    FULLSCREENRESOLUTIONBITDEPTH="24"
    VDRESOLUTION="novd"
    FULLSCREENOPTION="false"
    SLEEPNUMBER="0"
  fi
  WINERUNLOCATION="${CMDLINEVAR2%/*}"
  WINERUNFILE="${CMDLINEVAR2#$WINERUNLOCATION/}"
  STARTTOGGLE=" start /unix"
else
  FULLSCREENRESOLUTIONBITDEPTH="24"
  VDRESOLUTION="novd"
  FULLSCREENOPTION="false"
  SLEEPNUMBER="0"
  WSGAMEEXE="/../WineskinEngine.bundle/Wine/lib/wine/${TOOLTORUN}.exe.so"
  WSGAMEEXEFLAGS=""
  if [ "$TOOLTORUN" == "wineprefixcreate" -o "$TOOLTORUN" == "winetricks" ]
  then
    NONSTANDARDRUN="true"
  fi
fi
}

##############################################
############### MAIN APP #####################
######### clean up for not being in debug mode
######### set needed variables
CMDLINEVAR="$1"
CMDLINEVAR2="$2"
MACOSFOLD="$(dirname "$0")"
RESOFOLD="${MACOSFOLD%/*S}/Resources"
WINESKINENGINEFOLD="$RESOFOLD/WineskinEngine.bundle"
INFOPLISTFILE="${MACOSFOLD%/*S}/Info.plist"
TEMPINFOPLISTFILE="${MACOSFOLD%/*S}/tempInfo.plist"
export WINEPREFIX="$RESOFOLD"
export PATH="$WINESKINENGINEFOLD/Wine/bin:$WINESKINENGINEFOLD/X11/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin"
FIRSTPIDFILE="${MACOSFOLD%/*S}/.firstpidfile"
SECONDPIDFILE="${MACOSFOLD%/*S}/.secondpidfile"
WINESERVERPIDFILE="${MACOSFOLD%/*S}/.wineserverpidfile"
DISPLAYNUMBERFILE="${MACOSFOLD%/*S}/.currentuseddisplay"
THEOSVERSION="$(/usr/bin/sw_vers | grep 'ProductVersion:' | grep -o '[0-9]*\.[3-9]')"

########  set maxfiles higher.. very important for some games
launchctl limit maxfiles 2048

######## Get right osascript run command
fixforosascript
####### changes for debugging state
if [ "$CMDLINEVAR" == "debug" ]
then
  $OSASCRIPTRUNLINE -e "tell application \"System Events\" to activate" -e "tell application \"System Events\" to display dialog \"DEBUG MODE ENABLED!\" buttons {\"OK\"} default button \"OK\""
  DEBUGENABLED="yes"
fi
echo "Wineskin: Starting up..."
RunWineskin="yes"
######### check for engine
RunEngineChecker
if [ $RunWineskin == "no" ]
then
 # log already run error on console
 echo "$RunWineskinNoMessage"
else
  ######### Read Info.plist for all info needed from it
  # check if custom EXE, have to read some out of different info.plist
  if [ "$CMDLINEVAR" == "CustomEXE" ]
  then
    CEXEINFOPLISTFILE="$MACOSFOLD/../../$CMDLINEVAR2/Contents"
	cd "$CEXEINFOPLISTFILE"
	CEXEINFOPLISTFILE="$(echo "$PWD")/Info.plist.cexe"
	WSGAMEEXE="$(GetFromInfoPlist "$CEXEINFOPLISTFILE" "Program Name and Path" "string")"
	WSGAMEEXEFLAGS="$(GetFromInfoPlist "$CEXEINFOPLISTFILE" "Program Flags" "string")"
	FULLSCREENOPTION="$(GetFromInfoPlist "$CEXEINFOPLISTFILE" "Fullscreen" "boolean")"
	VDRESOLUTIONTEMP="$(GetFromInfoPlist "$CEXEINFOPLISTFILE" "Resolution" "string")"
	RUNWITHSTARTEXE="$(GetFromInfoPlist "$CEXEINFOPLISTFILE" "use start.exe" "boolean")"
  else
    WSGAMEEXE="$(GetFromInfoPlist "$INFOPLISTFILE" "Program Name and Path" "string")"
    WSGAMEEXEFLAGS="$(GetFromInfoPlist "$INFOPLISTFILE" "Program Flags" "string")"
    FULLSCREENOPTION="$(GetFromInfoPlist "$INFOPLISTFILE" "Fullscreen" "boolean")"
    VDRESOLUTIONTEMP="$(GetFromInfoPlist "$INFOPLISTFILE" "Resolution" "string")"
	RUNWITHSTARTEXE="$(GetFromInfoPlist "$INFOPLISTFILE" "use start.exe" "boolean")"
  fi
  PREFFILENAME="$(GetFromInfoPlist "$INFOPLISTFILE" "CFBundleIdentifier" "string")"
  VDRESOLUTION="${VDRESOLUTIONTEMP%x*}"
  FULLSCREENRESOLUTIONBITDEPTH="${VDRESOLUTIONTEMP#$VDRESOLUTION}"
  FULLSCREENRESOLUTIONBITDEPTH="${FULLSCREENRESOLUTIONBITDEPTH/x/}"
  SLEEPNUMBER="$FULLSCREENRESOLUTIONBITDEPTH"
  FULLSCREENRESOLUTIONBITDEPTH="${FULLSCREENRESOLUTIONBITDEPTH%sleep*}"
  SLEEPNUMBER="${SLEEPNUMBER#$FULLSCREENRESOLUTIONBITDEPTH}"
  SLEEPNUMBER="${SLEEPNUMBER#sleep}"
  if [ "$FULLSCREENRESOLUTIONBITDEPTH" == "" ]
  then
    FULLSCREENRESOLUTIONBITDEPTH="24"
  fi
  CURRENTSCREENRESOLUTION="$("$WINESKINENGINEFOLD/X11/WSReso")"
  if [ "$VDRESOLUTION" == "Current Resolution" ]
  then
    VDRESOLUTION="${CURRENTSCREENRESOLUTION// /x}"
  fi
  ###if VDreso is greater than Current reso, need to down the VD to current size
  #do X and Y separate
  if [ "$VDRESOLUTION" != "novd" ]
  then
    if [ ${VDRESOLUTION%x*} -gt ${CURRENTSCREENRESOLUTION% *} ]
    then
      VDRESOLUTION="${CURRENTSCREENRESOLUTION% *}x${VDRESOLUTION#${VDRESOLUTION%x*}x}"
    fi
    if [ ${VDRESOLUTION#${VDRESOLUTION%x*}x} -gt ${CURRENTSCREENRESOLUTION#${CURRENTSCREENRESOLUTION% *} } ]
    then
      VDRESOLUTION="${VDRESOLUTION%x*}x${CURRENTSCREENRESOLUTION#${CURRENTSCREENRESOLUTION% *} }"
    fi
  fi
  # check if using start or not and set STARTTOGGLE correctly
  if [ "$RUNWITHSTARTEXE" == "true" ]
  then
    STARTTOGGLE=" start /unix"
  fi
  #### set X11 app name, not truly an app name anymore, but still used for VD name
  X11APPNAME="${PREFFILENAME%.Wineskin.prefs}"
  ###### check command line variable for WineskinSettings.app runs
  CMDLINEVARCHECK=${CMDLINEVAR%-*}
  if [ "$CMDLINEVARCHECK" == "WSS" ]
  then
    DEBUGENABLED="yes"
    WineskinSettingsTools
  fi
  #finish setting variables
  if [ "$TOOLTORUN" != "installer" ]
  then
    WINERUNLOCATION="${WSGAMEEXE%/*}"
    WINERUNFILE="${WSGAMEEXE#$WINERUNLOCATION/}"
    WINERUNLOCATION="$WINEPREFIX/drive_c$WINERUNLOCATION"
  fi
  if [ "$WSGAMEEXEFLAGS" != "" ]
  then
    #if there are flags, this just adds a space for proper command line syntax
    WSSPACE=" "
  fi

  ######### test for WSGAMEEXE in wrapper
  if [ ! -f "$WINEPREFIX/drive_c/$WSGAMEEXE" -a "$CMDLINEVARCHECK" != "WSS" ]
  then
    $OSASCRIPTRUNLINE -e "tell application \"System Events\" to activate" -e "tell application \"System Events\" to display dialog \"ERROR! Set EXE not found. Running WineskinSetting.app instead.\" buttons {\"OK\"} default button \"OK\" with icon 0"
    cd "$MACOSFOLD/../../"
    open WineskinSettings.app
  else
  ######### set display number for X
  SetDisplay
 
  ######## Set to right X11 plist for fullscreen
  WSX11PREFSPLIST="$RESOFOLD/WSX11Prefs.plist"
  PLISTLINENUMBER=$(grep -n "rootless" "$WSX11PREFSPLIST" | cut -d: -f1)
  ((PLISTLINENUMBER++))
  if [ "$FULLSCREENOPTION" == "true" ]
  then
    #edit WSX11Prefs.plist to set rootless to false
    sed -i "" "${PLISTLINENUMBER}s/true/false/" "$WSX11PREFSPLIST"
  else
	#edit WSX11Prefs.plist to set rootless to true
	sed -i "" "${PLISTLINENUMBER}s/false/true/" "$WSX11PREFSPLIST"
  fi
  ######### start X11
  echo "Wineskin: starting X11"
  StartX11
  ######### check if we need to stop running
  if [ "$ERRORQUITRUNNING" == "true" ]
  then
    break;
  fi
  ######### make sure user has folder links
  SetUserFolders
  #### start quartz window manager, if rootless
  if [ "$FULLSCREENOPTION" != "true" ]
  then
    StartQuartzWM
  fi
  if [ "$DEBUGENABLED" != "yes" ]
  then
    rm "$LOGFOLDERPATH/LastRunX11.log" > /dev/null 2>&1
  fi
  ######### Start Wine
  echo "Wineskin: starting program in Wine..."
  WINESERVERPID="$(StartWine)"
  echo "Wineskin: Wineserver on PID $WINESERVERPID"
  ####### tell app to become active... sometimes it gets stuck in the back.
  cd "$MACOSFOLD/../../"
  THEAPPNAME="$PWD"
  if kill -0 ${X11APPPID} > /dev/null 2>&1
  then
    sleep 0.5
	# on 10.4 we need to change the info.plist back to X11 like when launching
	if [ "$THEOSVERSION" == "10.4" ]
    then
      sed -i "" "s/WineskinLauncher/WineskinX11/" "$INFOPLISTFILE"
    fi
	open "$THEAPPNAME" > /dev/null 2>&1
    if [ "$THEOSVERSION" == "10.4" ]
    then
      sleep 1
      sed -i "" "s/WineskinX11/WineskinLauncher/" "$INFOPLISTFILE"
    fi
  fi
  #######Sleep in the background while monitoring Wineserver and res changes
  SleepAndMonitor
  ####### Wine program is now done, need to clean up and shut down.
  echo "Wineskin: Shutting down..."
  if [ "$FULLSCREENOPTION" == "true" ]
  then
    echo "Wineskin: adjust resolution to original (${CURRENTSCREENRESOLUTION/ /x})"
    "$WINESKINENGINEFOLD/X11/WSReso" $CURRENTSCREENRESOLUTION  > /dev/null 2>&1
  fi
  CleanUpAndShutDown > /dev/null 2>&1
  echo "Wineskin: finished shutting down"
  fi ## finish EXE exists check
fi # finish already running check