@echo off

:: Force the current directory to be the directory of this script.  Necessary
:: when "Run As administrator" is used.
cd %~dp0

set token=
set nossl=0
set conda_flag=
set sdkver=1.41.0

:Parse_cmdline
if "%1" == "" goto Start
if "%1" == "/?" goto Help
if "%1" == "?" goto Help
if "%1" == "/ni" (
   set ni=true
   set token=%2
   shift
)
if "%1" == "/nossl" set nossl=1
if "%1" == "/no_ssl" set nossl=1
if "%1" == "/debug" set conda_flag=%conda_flag% -v
shift
goto Parse_cmdline


:Help
echo Install the TripleBlind SDK in a Conda environment.  Miniconda will be
echo installed if not found.
echo.
echo INSTALL.BAT [/ni [sdktoken]] [/no_ssl]
echo.
echo   /ni      Non-interactive.  Optionally provide an SDK token
echo   /no_ssl  Bypass SSL validation
echo   /debug   Show extra info during conda downloads.  Use twice for more.
goto Exit


:Start
echo.
echo                                 [36m**
echo                                [36m****
echo                                 [36m**
echo.
echo                            [34m**        [94m**
echo                           [34m****      [94m****
echo                            [34m**        [94m**
echo [0m
echo This script will prepare your system to use the TripleBlind SDK.
echo.

:: Verify that conda exists
where conda > nul 2> nul
if %ERRORLEVEL% EQU 0 goto Conda_Exists
if "%ni%" == "true" goto Conda_Install
echo Anaconda was not found.  It is highly recommended that you use a virtual
echo environment, and Anaconda provides that plus a package management system.
echo This script can download the latest version of Miniconda and install it.
echo [31mCareful![0m If you have already installed Anaconda, you should cancel and open the
echo 'Anaconda Prompt (Miniconda3)' from your Windows menu, then resume the setup.
echo.
echo If you do not wish to use Anaconda, you can cancel this installation.  You will
echo need to manually install the tripleblind.whl files and dependencies.
echo.
choice /C YN /M "Press 'Y' to download and install Miniconda, 'N' to cancel this setup."
if %ERRORLEVEL% NEQ 1 goto Exit
echo.

:Conda_Install
echo Downloading Miniconda...

:: NOTE: The screen will clear here, then start the download
bitsadmin.exe /transfer "DownloadMiniconda" https://repo.anaconda.com/miniconda/Miniconda3-py39_4.12.0-Windows-x86_64.exe "%CD%\Miniconda3-py39_4.12.0-Windows-x86_64.exe"
if ERRORLEVEL 1 (
    echo [31mError %ERRORLEVEL% while downloading Miniconda installer.[0m
    echo Unable to continue.
    goto Exit
)

echo Installing Miniconda for current user...
start /wait "" "%CD%\Miniconda3-py39_4.12.0-Windows-x86_64.exe" /InstallationType=JustMe /RegisterPython=0 /S /D=%UserProfile%\Miniconda3
if ERRORLEVEL 1 (
    echo [31mError %ERRORLEVEL% while installing Miniconda.[0m
    echo Unable to continue.
    goto Exit
)

echo Registering...
call "%UserProfile%\Miniconda3\condabin\conda.bat" init --all

:: Launch script in a fresh environment (will jump to :Conda_Exists), allow this process to end
start "" /d "%CD%" /i install.bat %*

:: This will close the initial window the user launched (either by double-clicking or running the script)
exit



:Conda_Exists

rem This flag is " " by default. Passed in to conda download commands.
set ssl_flag=
if %nossl% EQU 1 set ssl_flag=--insecure

echo Found the 'conda' command.  Looking for an existing 'tripleblind' environment.
call conda activate base

conda env list | find "tripleblind"
if errorlevel 1 goto Create_Env
if "%ni%" == "true" goto Delete_Existing_Env
echo.
echo An existing 'tripleblind' environment was found.  Starting from a
echo clean environment is generally safest and fastest.  However, this will
echo remove any extra packages you might have installed manually using pip or
echo conda commands.  You will need to reinstall any such packages after
echo this update.
echo.
choice /C YU /M "Press 'Y' to create a clean env, 'U' to upgrade the existing env."
if %ERRORLEVEL% EQU 2 goto Update_Env

:Delete_Existing_Env
echo Deleting existing 'tripleblind' env...
call conda env remove --name tripleblind


:Create_Env
echo Creating new 'tripleblind' environment
call conda create %conda_flag% %ssl_flag% --name tripleblind python=3.10 -y
if ERRORLEVEL 1 (
    echo [31mERROR %errorlevel% when creating 'tripleblind' conda environment.[0m
    echo Unable to continue with installation.
)
call conda activate tripleblind
if ERRORLEVEL 1 (
    echo [31mERROR %errorlevel% when activating 'tripleblind' conda environment.[0m
    echo Unable to continue with installation.
)

:Update_Env
echo Installing required packages

call conda activate tripleblind
if %nossl%==1 (
    call conda env config vars set PYTHONUTF8=1 > nul
    call conda env config vars set PYTHONIOENCODING=utf-8 > nul

    rem TODO: Build this from the api-sdk/environment.yaml's dependencies: section
    call conda install -y %conda_flag% --insecure pip pyjwt==2.4.0 requests libarchive dateparser humanize numpy==1.23.5 pandas==1.5.3 scikit-learn==1.3.0 jupyterlab=4 ipywidgets matplotlib scipy>=1.8.1
    if ERRORLEVEL 1 echo [31mError %ERRORLEVEL% when installing required dependencies.

    rem TODO: Build this from the api-sdk/environment.yaml's PIP section instead of explicitly
    rem       Exclude snowflake-* when building.
    pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org aiohttp>=3.10.11 chevron==0.14.0 torch==2.3.1 torchvision==0.18.1 onnx==1.18.0 jupyter-lsp>=2.2.0 sqlalchemy==1.4.52 xgboost==1.7.6 tensorflow==2.17.1 setuptools>=65.5.1 schema pydicom kaggle dataclasses-json==0.5.7 snowflake-connector-python==3.12.3 snowflake-sqlalchemy==1.5.3 nest-asyncio pymongo==4.6.3 dnspython==2.2.1 certifi==2023.7.22 Faker==10.0.0 pyyaml==6.0.1 factory-boy==3.3.0 importlib-metadata>=4.4.0 websocket-client==1.2.1 boto3>=1.24 botocore>=1.27 azure-storage-file-datalake==12.9.0 pillow==10.2.0 safetensors==0.3.3 transformers==4.36.0 pip-system-certs
    pip install preprocessor-%sdkver%-py3-none-any.whl
    pip install tripleblind-%sdkver%-py3-none-any.whl
    pip install tb_shared_objects-%sdkver%-py3-none-any.whl
) else (
    rem We now ship two environment files to support windows/unix installation separately
    call conda env update %conda_flag% --name tripleblind -f environment-win.yaml
)

if ERRORLEVEL 1 (
    echo [31mError %ERRORLEVEL% when installing required dependencies.
    echo TripleBlind may not work.[0m
)
echo Installation complete.

:: Check if user token is set
if "%ni%" == "true" goto skipToken
findstr /c:"sdkuser_token: \"\"" tripleblind.yaml

if "%token%" NEQ "" goto setToken
if %errorlevel% EQU 1 goto skipToken
echo.
echo In order to associate the SDK with your user account,
echo you must use your personalized `tripleblind.yaml` file.
echo.
echo To collect your tripleblind.yaml file:
echo   - Browse to http://tripleblind.app and log in
echo   - Click on the profile icon in the upper-right corner and select My Settings
echo   - In the Authentication tab, click `Download tripleblind.yaml`
echo   - Place the downloaded file into your SDK folder (replace the existing file)'
echo Alternatively, provide just your Authentication Token below.
echo.

set /P token= If you have set up your yaml file, press Enter. Or, provide your token:
if "%token%" EQU "" goto skipToken
:setToken
rem Intentionally using single quotes here (see MakeReplace function)
call :FindReplace "sdkuser_token: ''" "sdkuser_token: '%token%'" tripleblind.yaml
:skipToken

if "%ni%" == "true" goto Exit
echo ***********************************************************************
echo Installation successful!  You are ready to use the TripleBlind SDK.  Be
echo sure to use the 'tripleblind' conda environment whenever working with it.
echo     [42mconda activate tripleblind[0m
echo.
choice /C YX /M "Click 'Y' view documentation, 'X' just exit the installer."
if %ERRORLEVEL% EQU 1 start "" README.html
goto Exit


rem =================================
rem Helper subroutines

rem :FindReplace <findstr> <replstr> <file>
:FindReplace
set tmp="%temp%\tmp.txt"
If not exist "%temp%\_.vbs" call :MakeReplace
for /f "tokens=*" %%a in ('dir "%3" /s /b /a-d /on') do (
    echo(&Echo Replacing "%~1" with "%~2" in file %%~nxa
    <%%a cscript //nologo %temp%\_.vbs "%~1" "%~2">%tmp%
    if exist %tmp% move /Y %tmp% "%%~dpnxa">nul
)
del "%temp%\_.vbs"
exit /b

:MakeReplace
rem Due to a quirk in Windows command parsing, it cannot handle double-quotes
rem This converts single quotes to double quotes in the from/to arguments
>%temp%\_.vbs echo with Wscript
>>%temp%\_.vbs echo set args=.arguments
>>%temp%\_.vbs echo .StdOut.Write _
>>%temp%\_.vbs echo Replace(.StdIn.ReadAll, Replace(args(0), "'", chr(34)), Replace(args(1), "'", chr(34)),1,-1,1)
>>%temp%\_.vbs echo end with
exit /b

:Exit
