@echo off
chcp 65001

set vscodeVerRequierd=1.31.1
set lispExtId=IJCAD.lispDebugger
set lispExtPkg=lispDebugger-
set isUseVsCodeMarket=0
set installPath=%2
set isCheckExiston=%1

for /f "usebackq tokens=1" %%i in (`call code --version`) do (
    set vscodeVer=%%i
    goto:break
)
:break
if not defined vscodeVer (
    >&2 echo "The vscode call failed. Please make sure vscode is installed correctly"
    goto:vscodeNotExist
)

call:verCheck %vscodeVer% %vscodeVerRequierd%

if %errorlevel% == -1 (
    >&2 echo "Unable to install extension %lispExtId% as it is not compatible with VS code %vscodeVerRequierd%"
    goto:installFailed
)
call:funGetExtVer
if defined lispExtVer (
    goto:extensionExists
) else (
        if %isCheckExiston% == 1 (
            exit /b 0
        )

        if not defined isGetExtList (
        >&2 echo "Get Extensions list failed. Please make sure vscode is installed correctly"
        goto:vscodeNotExist
    )
)
if %isUseVsCodeMarket%==1 (
    call code --install-extension %lispExtId%||( call:funLocalInstall )
) else ( 
    call:funLocalInstall
)
call:funGetExtVer
if not defined lispExtVer (
    goto :installFailed
)

:installFinish
echo "install finish"
exit /b 0

:installFailed
echo "install Failed"
exit /b 1

:extensionExists
echo "extension exists"
exit /b 2

:vscodeNotExist
echo "vscode not exist"
exit /b 3

@REM ---------------------------

:funLocalInstall
if not exist %installPath% (
    >&2 echo "The local installation path does not exist"
    goto:eof
)
for /r %installPath% %%i in (%lispExtPkg%*.vsix) do (
    set localVsix=%%i
)
if not defined localVsix (
    >&2 echo "The extension package cannot be found"
    goto:eof
)
call  code --install-extension "%localVsix%"
goto:eof

:funGetExtVer
call code --list-extensions --show-versions>nul&&( set isGetExtList=1 )||( goto:eof )
for /f "usebackq delims=@ tokens=1,2" %%i in (`code --list-extensions --show-versions`) do (
    if %%i==%lispExtId% (
        set lispExtVer=%%j
    )
)
goto:eof

:verCheck curVer requierdVer
set v1=%~1
set v2=%~2
:loop
call :parseNode "%v1%" n1 v1
call :parseNode "%v2%" n2 v2
if %n1% gtr %n2% ( exit /b 1 )
if %n1% lss %n2% ( exit /b -1 )
if not defined v1 if not defined v2 ( exit /b 1 )
if not defined v1 ( exit  /b -1 )
if not defined v2 ( exit  /b 1 )
goto :loop
goto:eof

:parseNode version nodeVer remainderVer
for /f "tokens=1* delims=." %%i in ("%~1") do (
    set "%~2=%%i"
    set "%~3=%%j"
)
goto:eof