@echo off
setlocal EnableExtensions EnableDelayedExpansion
rem Kriya One starter for Windows, for cmd.exe: no PowerShell needed (docs/kriya-one/INSTALL-ONE.md).
rem   install.cmd [the install.sh options, e.g. --name NAME --memory 6g --yes]
rem It picks the route itself and says which and why; it never asks "Docker or WSL?":
rem   1. Docker Desktop answers: install.ps1 with PowerShell (else install.sh in your WSL distro, through Docker
rem      Desktop's WSL integration).
rem   2. A WSL Linux distro is here: install.sh inside it (Docker Engine or rootless Docker there: free, no Windows
rem      administrator; only your Linux password, shown first, when that distro needs one).
rem   3. No WSL yet: the one administrator step. It writes kriya-admin-steps.cmd (commented, safe to run again),
rem      shows it, then (a) you or your IT run it as administrator and run this again later, or (b) it asks Windows
rem      for administrator rights (a UAC prompt) for just that script, here. --yes: (a). --with-admin: (b).
rem Resumable: what it did is in %LOCALAPPDATA%\Kriya\install-state.txt, but every run checks the machine again.
rem Downloads: KRIYA_ONE_DOWNLOAD (default https://getkriya.in), each file checked against its line in SHA256SUMS.

set "SELF=%~f0"
set "KBASE=%KRIYA_ONE_DOWNLOAD%"
if not defined KBASE set "KBASE=https://getkriya.in"
if "%KBASE:~-1%"=="/" set "KBASE=%KBASE:~0,-1%"
if not defined LOCALAPPDATA set "LOCALAPPDATA=%USERPROFILE%\AppData\Local"
set "KDIR=%LOCALAPPDATA%\Kriya"
set "STATE=%KDIR%\install-state.txt"
set "ADMIN=%KDIR%\kriya-admin-steps.cmd"
set "RESULT=%KDIR%\kriya-admin-steps.result"
if not exist "%KDIR%\" mkdir "%KDIR%" || (echo kriya-one: can't make %KDIR% & exit /b 1)

rem The options: passed on to install.sh as they are (--with-admin becomes --with-sudo there); for install.ps1,
rem --foo-bar becomes -foobar (its parameters, case-insensitive). --yes and --with-admin/--with-sudo are read here.
set "YES=0"
set "WITHADMIN=0"
set "SHARGS="
set "PSARGS="
for %%A in (%*) do (
  set "T=%%~A"
  if /i "!T!"=="--yes" set "YES=1"
  if /i "!T!"=="-y" set "YES=1"
  if /i "!T!"=="--with-sudo" set "WITHADMIN=1"
  if /i "!T!"=="--with-admin" set "WITHADMIN=1"
  if /i "!T!"=="--with-admin" (set "SHARGS=!SHARGS! --with-sudo") else (set "SHARGS=!SHARGS! %%A")
  if /i not "!T!"=="--with-admin" if /i not "!T!"=="--with-sudo" (
    if "!T:~0,2!"=="--" (set "P=!T:~2!" & set "P=-!P:-=!" & set "PSARGS=!PSARGS! !P!") else (set "PSARGS=!PSARGS! %%A")
  )
)
if "%KRIYA_ONE_YES%"=="1" set "YES=1"

:detect
rem ---------------------------------------------------------------- 1. Docker Desktop
set "DESKTOP=0"
where docker.exe >nul 2>&1 && docker.exe info >nul 2>&1 && set "DESKTOP=1"
call :find_distro
if "%DESKTOP%"=="1" goto route_desktop
if defined DISTRO goto route_wsl
goto route_nowsl

:route_desktop
call :state_set route desktop
where powershell.exe >nul 2>&1 || goto desktop_wsl
echo Kriya One: Docker Desktop found, using it (install.ps1 with Windows PowerShell).
call :fetch install.ps1 || exit /b 1
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%KDIR%\install.ps1" %PSARGS%
exit /b %errorlevel%
:desktop_wsl
if not defined DISTRO (
  echo kriya-one: Docker Desktop is running, but there is no PowerShell and no WSL Linux distro to run the installer in.
  echo   Turn on a distro in Docker Desktop: Settings, Resources, WSL integration; or install PowerShell; then run this again.
  exit /b 1
)
echo Kriya One: Docker Desktop found, using it through your WSL %DISTRO% (its WSL integration; there is no PowerShell here).
goto run_in_wsl

rem ---------------------------------------------------------------- 2. WSL, no Docker Desktop
:route_wsl
call :state_set route wsl
echo Kriya One: Using Docker inside your WSL %DISTRO%: free, no Windows admin needed.
echo   (The installer inside %DISTRO% says what that Linux needs; if anything needs its root, it shows the commands first.)
:run_in_wsl
call :fetch install.sh || exit /b 1
set "WP="
for /f "usebackq delims=" %%P in (`wsl.exe -d "%DISTRO%" -e wslpath -a "%KDIR%\install.sh"`) do set "WP=%%P"
if not defined WP (echo kriya-one: couldn't find %KDIR%\install.sh from inside %DISTRO% ^(wslpath^) & exit /b 1)
wsl.exe -d "%DISTRO%" -e sh "%WP%" %SHARGS%
exit /b %errorlevel%

rem ---------------------------------------------------------------- 3. No WSL distro
:route_nowsl
wsl.exe --status >nul 2>&1 && goto need_distro
call :state_get reboot-pending
if "%SV%"=="1" (
  echo Kriya One: the administrator steps ran and asked for a restart, and WSL doesn't answer yet.
  echo   Restart Windows, then run this again. If you did restart, the steps below show what is still missing.
  echo.
)
call :write_admin
echo Kriya One needs WSL ^(Windows Subsystem for Linux^): free, from Microsoft. Turning it on is the one step that
echo needs a Windows administrator. Everything it would run is in this file:
echo   %ADMIN%
echo ---------------------------------------------------------------- (begin)
type "%ADMIN%"
echo ---------------------------------------------------------------- (end)
set "PICK=a"
if "%WITHADMIN%"=="1" set "PICK=b"
if "%YES%"=="1" if "%WITHADMIN%"=="0" set "PICK=a"
if "%YES%"=="0" if "%WITHADMIN%"=="0" (
  echo   a. Run it yourself, or give it to your IT: right-click it, Run as administrator. Then run this installer again.
  echo   b. Continue here: Windows asks for administrator rights ^(a UAC prompt^) for just the file above, then this goes on.
  set "ANS="
  set /p "ANS=a or b [a]: "
  if /i "!ANS!"=="b" set "PICK=b"
)
if /i "%PICK%"=="b" goto elevate
:admin_yourself
call :state_set admin-steps-written "%DATE% %TIME%"
echo.
echo Next: run %ADMIN% as administrator ^(right-click, Run as administrator; or give it to your IT^), restart Windows if
echo it says so, then run this installer again ^(no admin^): it checks again and continues from where it left off.
exit /b 3

:elevate
rem The commands were shown above; only that file runs as administrator.
call :state_set admin-steps-written "%DATE% %TIME%"
if exist "%RESULT%" del "%RESULT%" >nul 2>&1
set "ADMINQ=%ADMIN:'=''%"
where powershell.exe >nul 2>&1 && (
  echo Asking Windows for administrator rights for %ADMIN% ^(a UAC prompt^)...
  powershell.exe -NoProfile -Command "Start-Process -Verb RunAs -Wait -FilePath '%ADMINQ%'" || (echo kriya-one: not elevated ^(the prompt was declined?^) & goto admin_yourself)
  goto after_admin
)
where cscript.exe >nul 2>&1 || goto admin_yourself
rem No PowerShell: Windows Script Host's Shell.Application ShellExecute "runas" (the same UAC prompt; VBScript is
rem deprecated by Microsoft and may be missing on newer Windows, then it falls back to a.).
set "VBS=%TEMP%\kriya-elevate-%RANDOM%.vbs"
> "%VBS%" echo Set s = CreateObject^("Shell.Application"^)
>> "%VBS%" echo s.ShellExecute "cmd.exe", "/c """ ^& WScript.Arguments^(0^) ^& """", "", "runas", 1
echo Asking Windows for administrator rights for %ADMIN% ^(a UAC prompt^)...
cscript.exe //nologo "%VBS%" "%ADMIN%" || (del "%VBS%" >nul 2>&1 & goto admin_yourself)
del "%VBS%" >nul 2>&1
echo When the administrator window has finished, press Enter here.
pause >nul
:after_admin
set "RB=0"
if exist "%RESULT%" for /f "usebackq tokens=1,2 delims==" %%a in ("%RESULT%") do if "%%a"=="reboot" set "RB=%%b"
if not exist "%RESULT%" (
  echo kriya-one: the administrator steps didn't finish ^(no %RESULT%^). Run %ADMIN% as administrator yourself, then this again.
  exit /b 3
)
if "%RB%"=="1" (
  call :state_set reboot-pending 1
  echo Kriya One: WSL is turned on. Windows needs a restart: restart, then run this installer again ^(no admin^).
  exit /b 3
)
goto detect

:need_distro
rem WSL works, no Linux distro yet: Ubuntu, for this Windows user (no administrator needed).
call :state_set reboot-pending 0
echo Kriya One: WSL is ready, with no Linux distro yet. Next: Ubuntu, free, for your Windows user ^(no admin^):
echo   wsl.exe --install -d Ubuntu
echo   It opens Ubuntu once and asks you for a new Linux user name and password ^(your own, for that Linux only^).
echo   Then type exit, and Kriya One continues.
if "%YES%"=="1" (
  echo --yes: not done now ^(it needs you to choose that Linux user^). Run the line above, then this installer again.
  exit /b 3
)
wsl.exe --install -d Ubuntu || (echo kriya-one: wsl --install -d Ubuntu failed ^(above^) & exit /b 1)
call :find_distro
if not defined DISTRO (
  echo Ubuntu is installed. Open Ubuntu from the Start menu once to finish it, then run this installer again.
  exit /b 3
)
goto detect

rem ---------------------------------------------------------------- helpers

:find_distro
rem DISTRO: the default WSL distro (its own name, from inside it: plain text, not wsl -l's UTF-16), else the first
rem listed one; never Docker Desktop's own (docker-desktop, docker-desktop-data). Each one checked by running it.
set "DISTRO="
where wsl.exe >nul 2>&1 || exit /b 0
for /f "usebackq delims=" %%D in (`wsl.exe -e sh -c "echo $WSL_DISTRO_NAME" 2^>nul`) do if not defined DISTRO set "DISTRO=%%D"
if defined DISTRO if /i "!DISTRO:~0,14!"=="docker-desktop" set "DISTRO="
if defined DISTRO wsl.exe -d "!DISTRO!" -e true >nul 2>&1 || set "DISTRO="
if defined DISTRO exit /b 0
set "WSL_UTF8=1"
for /f "usebackq delims=" %%D in (`wsl.exe --list --quiet 2^>nul`) do (
  set "C=%%D"
  if not defined DISTRO if not "!C!"=="" if /i not "!C:~0,14!"=="docker-desktop" (
    wsl.exe -d "!C!" -e true >nul 2>&1 && set "DISTRO=!C!"
  )
)
exit /b 0

:fetch
rem fetch FILE: %KBASE%/FILE into %KDIR%, kept only when its SHA-256 (certutil) is FILE's line in SHA256SUMS.
where curl.exe >nul 2>&1 || (echo kriya-one: curl.exe isn't here ^(Windows 10 1803 or newer has it^) & exit /b 1)
curl.exe -fsSL -m 120 -o "%KDIR%\%~1" "%KBASE%/%~1" || (echo kriya-one: couldn't download %KBASE%/%~1 & exit /b 1)
curl.exe -fsSL -m 60 -o "%KDIR%\SHA256SUMS" "%KBASE%/SHA256SUMS" || (echo kriya-one: couldn't download %KBASE%/SHA256SUMS & exit /b 1)
set "WANT="
for /f "usebackq tokens=1,2" %%a in ("%KDIR%\SHA256SUMS") do (
  if "%%b"=="%~1" set "WANT=%%a"
  if "%%b"=="*%~1" set "WANT=%%a"
)
set "GOT="
for /f "skip=1 delims=" %%h in ('certutil -hashfile "%KDIR%\%~1" SHA256') do if not defined GOT set "GOT=%%h"
if defined GOT set "GOT=!GOT: =!"
if not defined WANT (del "%KDIR%\%~1" >nul 2>&1 & echo kriya-one: %~1 isn't in %KBASE%/SHA256SUMS: not used & exit /b 1)
if /i not "!GOT!"=="!WANT!" (del "%KDIR%\%~1" >nul 2>&1 & echo kriya-one: %KBASE%/%~1 doesn't match its checksum in SHA256SUMS: not used & exit /b 1)
exit /b 0

:state_set
rem state_set KEY VALUE: KEY=VALUE in install-state.txt (the other keys kept).
set "NEWSTATE=%STATE%.new"
if exist "%NEWSTATE%" del "%NEWSTATE%" >nul 2>&1
if exist "%STATE%" for /f "usebackq tokens=1* delims==" %%a in ("%STATE%") do if /i not "%%a"=="%~1" >> "%NEWSTATE%" echo %%a=%%b
>> "%NEWSTATE%" echo %~1=%~2
move /y "%NEWSTATE%" "%STATE%" >nul
exit /b 0

:state_get
rem state_get KEY: SV is its value in install-state.txt (empty: none).
set "SV="
if exist "%STATE%" for /f "usebackq tokens=1* delims==" %%a in ("%STATE%") do if /i "%%a"=="%~1" set "SV=%%b"
exit /b 0

:write_admin
rem The administrator steps: the ::ADMIN: lines at the end of this file, as they are, plus a dated header.
> "%ADMIN%" echo @echo off
>> "%ADMIN%" echo rem Written by the Kriya One installer ^(install.cmd^) on %DATE% %TIME%.
for /f "usebackq delims=" %%L in (`findstr /b /c:"::ADMIN:" "%SELF%"`) do (
  set "L=%%L"
  >> "%ADMIN%" echo(!L:~8!
)
exit /b 0

rem ---------------------------------------------------------------- the administrator steps (kriya-admin-steps.cmd)
rem Never run from here: :write_admin copies them out. No "!" in them (delayed expansion when copying).
::ADMIN:rem Kriya One: the Windows administrator steps for WSL (Windows Subsystem for Linux), free, from Microsoft.
::ADMIN:rem Run it as administrator: right-click it, Run as administrator (or give it to your IT). It is safe to run
::ADMIN:rem again: every step checks first and skips what is done. It changes nothing else and asks for no password.
::ADMIN:rem After it: restart Windows if it says so, then the user runs the Kriya One installer again, without admin.
::ADMIN:setlocal EnableExtensions
::ADMIN:set "REBOOT=0"
::ADMIN:rem 0. Administrator rights: "net session" only works as administrator.
::ADMIN:net session >nul 2>&1 || (echo This needs administrator rights: right-click it, Run as administrator. & exit /b 1)
::ADMIN:rem 1. WSL answers already (wsl --status): nothing to do.
::ADMIN:wsl.exe --status >nul 2>&1 && (echo WSL is ready already: nothing to do. & goto done)
::ADMIN:rem 2. The Windows feature "Virtual Machine Platform": the small virtual machine WSL 2 runs Linux in.
::ADMIN:dism.exe /online /English /get-featureinfo /featurename:VirtualMachinePlatform | find "State : Enabled" >nul || (dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart & set "REBOOT=1")
::ADMIN:rem 3. The Windows feature "Windows Subsystem for Linux" itself.
::ADMIN:dism.exe /online /English /get-featureinfo /featurename:Microsoft-Windows-Subsystem-Linux | find "State : Enabled" >nul || (dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart & set "REBOOT=1")
::ADMIN:rem 4. The current WSL from Microsoft (wsl --update), only when this one is the old built-in one (no wsl --version).
::ADMIN:wsl.exe --version >nul 2>&1 || wsl.exe --update
::ADMIN:rem The Linux distro (Ubuntu) is not installed here: the user's own rerun of the installer installs it for them.
::ADMIN::done
::ADMIN:rem What happened, for the installer: reboot=1 when a feature was just turned on (Windows needs a restart).
::ADMIN:> "%~dp0kriya-admin-steps.result" echo reboot=%REBOOT%
::ADMIN:if "%REBOOT%"=="1" (echo Done. Restart Windows, then run the Kriya One installer again, without admin.) else (echo Done. Run the Kriya One installer again, without admin.)
::ADMIN:exit /b 0
