@echo off

setlocal enabledelayedexpansion

pushd "%CD%"
CD /D "%~dp0"
set GSDLLANG=en

:: This script's contents were created in Windows codepage 850 (Western European).
:: When this script is run in non-English locales like the Chinese locale, the 
:: character content/encoding of this script can get wrongly interpreted by the
:: different encoding of the locale. And then the GS environment gets set wrongly
:: or incompletely in those cases.
:: So we force this script to be run and interpreted in codepage 850.
:: However, the Russian display strings in this script were desgined to work in the
:: default Russian Windows codepage 866. Whereas, codepage 850 works for this
:: script's remaining English, French, Spanish display strings. So:
if ("!GSDLLANG!" == "ru") (
	chcp 866
) else (
	chcp 850
)

echo.
echo.
echo  ####                        #
echo ##                           #
echo #     ###  ##   ##  ### ### ###  ##  ###  ##
echo #   # #   #### #### # # ##   #  #  # # # ####
echo ##  # #   #    #    # #   #  #  #  # # # #
echo  #### #    ###  ### # # ###  ##  ##  # #  ###
echo (C) 2008, New Zealand Digital Library Project
echo.
echo.
echo.

if "!GSDLHOME!" == "" goto start
if "!GSDLHOME!" == "!CD!" if not "!GSDLOS!" == "" (
	echo Your environment is already set up for Greenstone
	goto done
)

:start
if "!OS!" == "Windows_NT" goto WinNT
if "!OS!" == "" goto Win95
if "!GSDLLANG!" == "en" echo Setup failed - your PATH has not been set
if "!GSDLLANG!" == "es" echo No se pudo realizar la configuraciвn - no se ha establecido la RUTA.
if "!GSDLLANG!" == "fr" echo EchВc de l'installation - votre variable PATH n'a pas ВtВ ajustВe
if "!GSDLLANG!" == "ru" echo Установка не удалась - ПУТЬ не был установлен
goto End

:WinNT
set GSDLHOME=%CD%
set GSDLOS=windows

REM Override Imagemagick and Ghostscript paths to the bundled applications shipped with greenstone if they exists otherwise use default environment variables.
if exist "!GSDLHOME!\bin\windows\ghostscript\bin\gsdll32.dll" set GS_DLL=!GSDLHOME!\bin\windows\ghostscript\bin\gsdll32.dll
if exist "!GSDLHOME!\bin\windows\ghostscript\lib\*.*" set GS_LIB=!GSDLHOME!\bin\windows\ghostscript\lib
if exist "!GSDLHOME!\bin\windows\ghostscript\bin\*.*" set PATH=!GSDLHOME!\bin\windows\ghostscript\bin;!PATH!
:: ImageMagick environment vars are now set in bin\script\gs-magick.pl
::if exist "!GSDLHOME!\bin\windows\imagemagick\*.*" set PATH=!GSDLHOME!\bin\windows\imagemagick;!PATH!

if "!GS_CP_SET!" == "yes" goto Success

set PATH=!GSDLHOME!\bin\windows;!GSDLHOME!\bin\script;!PATH!

:: PERLPATH is our crucial custom env var that should be set to the bin folder containing the perl executable
:: STRAWBERRY_PERLHOME is our new custom env var that's the strawberry perl dir containing perl, c (and more) subdirs.
:: When setting the perl environment, to run strawberry perl it needs c\bin, perl\bin and perl\site\bin added to PATH
:: per the README. Note how strawberry-perl\c is at the same level as strawberry-perl\perl.
:: We previously worked with a customised strawberry perl for 32 bit (v5.22.3.1, Portable, Without USE_64_BIT_INT) that
:: was structured in a particular way: .dll, .bat and config files in its c\bin were merged with its perl\bin folder
:: And its site\bin and site\lib folders were empty, unlike now where we make and provide strawberry-perl-with-cpan
:: still 32 bit Windows compatible (5.32.1.1, Portable, still Without USE_64_BIT_INT). Back then we could get away with
:: just perl\bin on the PATH. But since the new perl's site folder has contents so it doesnt' help much to merge c\bin
:: with perl\bin now (so we just provide the containing strawberry-perl folder in full), the new version of perl we 
:: provide (perl-with-cpan) needs perl\bin, perl\site\bin and c\bin to be on the PATH.
:: When set up so, running perl -V shows its perl\lib, perl\site\lib and perl\vendor\lib are in at-INC.
:: The new version is dealt with in the outer if block below, the old Greenstone version is handled by the else block.
if exist "!GSDLHOME!\bin\windows\strawberry-perl\perl\bin" (
	set STRAWBERRY_PERLHOME=!GSDLHOME!\bin\windows\strawberry-perl
	set PERLPATH=!STRAWBERRY_PERLHOME!\perl\bin
	set PATH=!PERLPATH!;!STRAWBERRY_PERLHOME!\perl\site\bin;!STRAWBERRY_PERLHOME!\c\bin;!PATH!	
) else (
	if exist "!GSDLHOME!\bin\windows\perl\bin" (
		set PERLPATH=!GSDLHOME!\bin\windows\perl\bin
		set PATH=!PERLPATH!;!PATH!		
	)
)

set GS_CP_SET=yes
goto Success

:Win95
if "%1" == "SetEnv" goto Win95Env
REM We'll invoke a second copy of the command processor to make
REM sure there's enough environment space
COMMAND /E:2048 /K %0 SetEnv
goto End

:Win95Env
set GSDLHOME=%CD%
set GSDLOS=windows

REM Override Imagemagick and Ghostscript paths to the bundled applications shipped with greenstone if they exists otherwise use default environment variables.
if exist "!GSDLHOME!\bin\windows\ghostscript\bin\gsdll32.dll" set GS_DLL="!GSDLHOME!\bin\windows\ghostscript\bin\gsdll32.dll"
if exist "!GSDLHOME!\bin\windows\ghostscript\lib\*.*" set GS_LIB="!GSDLHOME!\bin\windows\ghostscript\lib"
if exist "!GSDLHOME!\bin\windows\ghostscript\bin\*.*" set PATH="!GSDLHOME!\bin\windows\ghostscript\bin";"!PATH!"
:: ImageMagick environment vars are now set in bin\script\gs-magick.pl
::if exist "!GSDLHOME!\bin\windows\imagemagick\*.*" set PATH="!GSDLHOME!\bin\windows\imagemagick";"!PATH!"

if "!GS_CP_SET!" == "yes" goto Success
set PATH=!GSDLHOME!\bin\windows;!GSDLHOME!\bin\script;!PATH!
if exist "!GSDLHOME!\bin\windows\perl\bin" (
	set PERLPATH=!GSDLHOME!\bin\windows\perl\bin
	set PATH=!PERLPATH!;!PATH!
)
set GS_CP_SET=yes
goto Success


:Success
if "!GSDLLANG!" == "en" echo.
if "!GSDLLANG!" == "en" echo Your environment has successfully been set up to run Greenstone.
if "!GSDLLANG!" == "en" echo Note that these settings will only have effect within this MS-DOS
if "!GSDLLANG!" == "en" echo session. You will therefore need to rerun setup.bat if you want
if "!GSDLLANG!" == "en" echo to run Greenstone programs from a different MS-DOS session.
if "!GSDLLANG!" == "en" echo.

if "!GSDLLANG!" == "es" echo.
if "!GSDLLANG!" == "es" echo Su ambiente ha sido configurado para correr los programas Greenstone.
if "!GSDLLANG!" == "es" echo Recuerde que estos ajustes гnicamente tendrаn efecto dentro de esta sesiвn
if "!GSDLLANG!" == "es" echo MS-DOS. Por lo tanto deberа ejecutar nuevamente setup.bat si desea
if "!GSDLLANG!" == "es" echo correr los programas de Greenstone desde una sesiвn MS-DOS diferente.
if "!GSDLLANG!" == "es" echo.

if "!GSDLLANG!" == "fr" echo.
if "!GSDLLANG!" == "fr" echo Votre environnement a ВtВ configuВre avec succКs pour exВcuter Greenstone
if "!GSDLLANG!" == "fr" echo Notez que ces paramКtrages n'auront d'effet que dans cette session MS-DOS.
if "!GSDLLANG!" == "fr" echo Vous devrez par consВquent rВexВcuter setup.bat si vous voulez faire
if "!GSDLLANG!" == "fr" echo lancer des programmes Greenstone dans une autre session MS-DOS.
if "!GSDLLANG!" == "fr" echo.

if "!GSDLLANG!" == "ru" echo.
if "!GSDLLANG!" == "ru" echo Ваше окружение было успешно настроено, чтобы установить Greenstone Обратите
if "!GSDLLANG!" == "ru" echo внимание, что эти назначения будут только иметь эффект в пределах этого MS DOS
if "!GSDLLANG!" == "ru" echo сессия. Вы будете поэтому должны повторно управлять setup.bat, если Вы хотите
if "!GSDLLANG!" == "ru" echo управлять программами Зелёных изверженных пород от различной сессии MS DOS.
if "!GSDLLANG!" == "ru" echo.

:End
endlocal & set PATH=%PATH%& set GSDLHOME=%GSDLHOME%& set GSDLOS=%GSDLOS%& set PERLPATH=%PERLPATH%

set savedir=%CD%
cd "%GSDLHOME%"
if exist ext (	
    for /D %%e IN ("ext/*") do call :addexts %%e
)
cd "%savedir%"
set savedir=
goto :doneexts

:addexts
set folder=%1
cd "ext\%folder%"		
if EXIST setup.bat call setup.bat
cd ..\..
goto :eof

:doneexts


if exist "%GSDLHOME%\local\setup.bat" (
    echo.
    echo Running %GSDLHOME%\local\setup.bat
    cd "%GSDLHOME%\local"
    call setup.bat 
    cd "%GSDLHOME%"
)

setlocal enabledelayedexpansion

if exist "%GSDLHOME%\local" (
  set PATH=!GSDLHOME!\local\bin;!PATH!
)

if exist "%GSDLHOME%\apache-httpd" (
  echo +Adding in executable path for apache-httpd
  set PATH=!GSDLHOME!\apache-httpd\!GSDLOS!\bin;!PATH!
  set PATH=!GSDLHOME!\apache-httpd\!GSDLOS!\lib;!PATH!
)

:: test writability of GSDLHOME
@call "!GSDLHOME!\bin\script\checkwritability.bat"

::::::::::::::::::::::::::::::
if "!GSDL3SRCHOME!" == "" (goto javacheck) else (goto done)

:javacheck
:: Only for GS2: work out java, and if the bundled jre is found, then set Java env vars with it
:: Then the same java will be consistently available for all aspects of GS2 (server or GLI, and any subshells these launch)
echo.
set MINIMUM_JAVA_VERSION=1.5.0_00
echo GS2 installation: Checking for Java of version !MINIMUM_JAVA_VERSION! or above

set BUNDLED_JRE=!GSDLHOME!\packages\jre
if exist "!BUNDLED_JRE!" (
	set HINT=!BUNDLED_JRE!
) else (
	echo No bundled JRE
	set HINT=
)

set SEARCH4J_EXECUTABLE=!GSDLHOME!\bin\!GSDLOS!\search4j.exe
if not exist "!SEARCH4J_EXECUTABLE!" (
	echo Can't check for java, no Search4j	
	if not exist "!BUNDLED_JRE!" echo Ensure Java environment variables are set ^(either JAVA_HOME or JRE_HOME and on PATH^) & goto done
	:: else use Bundled JRE
	echo Will use the bundled JRE and unset any JAVA_HOME to prevent conflicts
	set JAVA_HOME=
	set JRE_HOME=!BUNDLED_JRE!
	set PATH=!BUNDLED_JRE!\bin;!PATH!
	goto done
)

:: Need the call stmt, the usebackq with backticks around the full command, AND the double quotes around filepaths to properly handle spaces in the filepaths
for /f "usebackq tokens=*" %%r in (`call "!GSDLHOME!\bin\!GSDLOS!\search4j.exe" -p "!HINT!" -m !MINIMUM_JAVA_VERSION!`) do set GS_JAVA_HOME=%%r


if "!GS_JAVA_HOME!" == "" (
	if not exist "!BUNDLED_JRE!" echo There's no bundled JRE.
	echo setup.bat: Could not find Java in the environment or installation.	
	echo Set JAVA_HOME or JRE_HOME, and put it on the PATH, if working with Java tools like Lucene.
	goto done
)

:: found java, now GS_JAVA_HOME env vars set, set JAVA_HOME else JRE_HOME

if "!GS_JAVA_HOME!" == "!BUNDLED_JRE!" (	
	:: since our bundled JRE was selected by search4j and we'll be using that, clearing any existing JAVA_HOME to prevent version conflicts	
	echo Found a bundled JRE. Setting up GS2's Java environment to use this ^(and unsetting any JAVA_HOME to prevent version conflicts^)
	set JAVA_HOME=
	set JRE_HOME=!BUNDLED_JRE!
	set PATH=!BUNDLED_JRE!\bin;!PATH!
	goto done
)

:: Otherwise, the java that search4j found is not the bundled jre. In that case
:: if JAVA_HOME or JRE_HOME is already set to the Java found, then PATH presumably would already be set too.
if "!JAVA_HOME!" == "!GS_JAVA_HOME!" (
	echo Looks like the Java environment is already set up with a JAVA_HOME
	::echo Looks like the Java environment is already set up with a JAVA_HOME, unsetting any JRE_HOME	
	goto done
)
if "!JRE_HOME!" == "!GS_JAVA_HOME!" (
	echo Looks like the Java environment is already set up with a JRE_HOME, unsetting any JAVA_HOME to prevent java version conflicts
	set JAVA_HOME=
	goto done
)

:: if Java env vars not already set, then set them to the GS_JAVA_HOME found
echo Found a Java on the system. Setting up GS2's Java environment to use this
::echo Found a Java on the system. Setting up GS2's Java environment to use this: !GS_JAVA_HOME!
set PATH=!GS_JAVA_HOME!\bin;!PATH!
:: extract the last 4 chars from folder name. Could be \jre or jre\ or otherwise
set javafoldername=!GS_JAVA_HOME:~-4!
:: now can test if the foldername contains jre or otherwise, and based on that set either JAVA_HOME or JRE_HOME
:: https://stackoverflow.com/questions/7005951/batch-file-find-if-substring-is-in-string-not-in-a-file
:: https://ss64.com/nt/syntax-substring.html
if /i "x!javafoldername:jre=!" == "x!javafoldername!" (
	echo Setting JAVA_HOME, and unsetting any JRE_HOME to prevent version conflicts
	set JAVA_HOME=!GS_JAVA_HOME!
	set JRE_HOME=
) else (
	echo Setting JRE_HOME, and unsetting any JAVA_HOME to prevent version conflicts
	set JRE_HOME=!GS_JAVA_HOME!
	set JAVA_HOME=
)

::::::::::::::::::::::::::::::

:done

:: COMMENTING OUT THE 2 LINES DETERMINING AND SETTING THE BITNESS (32/64) ON WIN MACHINES
:: AS IT MAY BE USEFUL IN FUTURE AND IT TOOK ME SOME TIME TO GET THESE LINES WORKING RIGHT
:: To know bitness (32 vs 64) of a Windows machine, the cmd is "SET Processor"
::   and look through the lines of output for the line PROCESSOR_ARCHITECTURE=x86
::   or PROCESSOR_ARCHITECTURE=x64. See techgenix.com/aquicktiptocheckoperatingsystemarchitecture/
:: The following runs the cmd "set Processor". Then, among the multiline output, it finds the line
::   containing "PROCESSOR_ARCHITECTURE", splits this line on the delimiter "=" and stores the 2nd token in %%G
::   Based on the example "_ping_cmd" at https://ss64.com/nt/for_cmd.html
:: REM for /f "tokens=2 delims==" %%G in ('set Processor ^|find "PROCESSOR_ARCHITECTURE"') do set BITNESS=%%G
:: Easier way to above: %PROCESSOR_ARCHITECTURE% already contains a value of amd64/x64 or x86. So don't need to run the "set Processor"
:: command and hunt for PROCESSOR_ARCHITECTURE line. See https://superuser.com/questions/321988/how-do-i-determine-if-my-windows-is-32-bit-or-64-bit-using-a-command
REM set BITNESS=%PROCESSOR_ARCHITECTURE%
::   BITNESS will now be "x86" for 32 bit or something like "amd64" or "x64" for 64 bit
:: From https://ss64.com/nt/syntax-substring.html
::   "To do a string comparison, remove the SearchString and compare the result with the original
::   variable before removal. If both strings are the same, then SearchString was not found:"
REM if /i "%BITNESS:64=%" == "%BITNESS%" (set BITNESS=32) else (set BITNESS=64)


popd
endlocal & set PATH=%PATH%& set GSDLHOME=%GSDLHOME%& set GSDLOS=%GSDLOS%& set JRE_HOME=%JRE_HOME%& set JAVA_HOME=%JAVA_HOME%& set PERLPATH=%PERLPATH%
REM      & set BITNESS=%BITNESS%

if not "%JAVA_HOME%" == "" echo JAVA_HOME: %JAVA_HOME%
if not "%JRE_HOME%" == "" echo JRE_HOME: %JRE_HOME%
:: if GS3, then we'll do some more checking such as bundled JRE if the bitness is right
if "%GSDL3SRCHOME%" == "" if "%JAVA_HOME%" == "" if "%JRE_HOME%" == "" echo Warning: Neither JAVA_HOME nor JRE_HOME set. Ensure one is set and on PATH.
::if not "%GSDL3SRCHOME%" == "" if "%JAVA_HOME%" == "" if "%JRE_HOME%" == "" echo Neither JAVA_HOME nor JRE_HOME set. Will shortly check for bundled JRE of correct bitness.

:: Perl >= v5.18.* randomises map iteration order within a process
set PERL_PERTURB_KEYS=0
set PERL_HASH_SEED=0

set GSWGETRC=%GSDLHOME%\bin\%GSDLOS%\wgetrc

:: On other locales, like Chinese locales, for XMLParsers to read (XML) files
:: in UTF-8 encoding (instead of defaulting to encoding GBK when on Chinese locale),
:: need to pass -Dfile.encoding=UTF-8 to the JVM. Can have this passed to the JVM by
:: setting the JAVA_TOOL_OPTIONS environment variable to this here.
:: For example, the example at https://www.mkyong.com/java/how-to-read-utf-8-xml-file-in-java-sax-parser/
:: doesn't work in a Chinese locale until the program is run with 
:: java -Dfile.encoding=UTF-8 <ReadXMLUTF8FileSAX>, so for GS3 this will be passed in to tomcat
:: in build.xml
::
:: https://stackoverflow.com/questions/37071353/how-to-check-if-a-variable-exists-in-a-batch-file
rem if "x%JAVA_TOOL_OPTIONS%"=="x" ( 
rem   set JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8  
rem ) else (
rem   set JAVA_TOOL_OPTIONS=%JAVA_TOOL_OPTIONS% -Dfile.encoding=UTF-8
rem )
