@echo off
setlocal EnableExtensions EnableDelayedExpansion

set UPDATE_DIR=%~dp0updates
if not exist "%UPDATE_DIR%" mkdir "%UPDATE_DIR%"

set TMP_OUT=%TEMP%\update_check_%RANDOM%.txt
set TMP_OUT_2=%TEMP%\update_check_%RANDOM%.txt

python check_new_version.py > "%TMP_OUT%"
set EXITCODE=%ERRORLEVEL%

if %EXITCODE%==20 (
    echo Fehler beim Update-Check
    goto :END
)

if %EXITCODE%==0 (
    echo Keine Updates verfuegbar.
    goto :END
)

echo.
type "%TMP_OUT%"

choice /c jn /m "Wollen Sie die Updates-Packages herunterladen?"

if errorlevel 2 goto :END


if exist "%TMP_OUT%" (
    
    
    findstr /b "PYTHON_DOWNLOAD=" "%TMP_OUT%" >nul
    if not errorlevel 1 (
        for /f "tokens=1,* delims==" %%a in (
            'findstr /b "PYTHON_DOWNLOAD=" "%TMP_OUT%"'
        ) do (
            echo Downloading Python update from PYTHON_DOWNLOAD
            powershell -NoProfile -Command ^
              "Invoke-WebRequest '%%b' -OutFile '%UPDATE_DIR%\python-embed.zip'"
        )
    )

    findstr /b "CAESIUM_DOWNLOAD=" "%TMP_OUT_2%" >nul
    if not errorlevel 1 (
        for /f "tokens=1,* delims==" %%a in (
            'findstr /b "CAESIUM_DOWNLOAD=" "%TMP_OUT_2%"'
        ) do (
            echo Downloading caesiumclt update from CAESIUM_DOWNLOAD

            powershell -NoProfile -Command ^
              "Invoke-WebRequest '%%b' -OutFile '%UPDATE_DIR%\caesiumclt.zip'"
        )
    )
)

:END
del "%TMP_OUT%" >nul 2>&1
del "%TMP_OUT_2%" >nul 2>&1
endlocal