@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "archive=%~dp0FeeLink_2.26.zip"
set "programs=%LOCALAPPDATA%\Programs"
set "destination=%programs%\FeeLink"
set "expected=e5e3f0dd934ef37606d0c61949eaf5783d30eb7534298ba54e714a16c19e862e"
set "noLaunch="
set "lockHeld="
if /i "%~1"=="--no-launch" set "noLaunch=1"

if exist "%destination%" (
    call :checkRelease "%destination%"
    if errorlevel 1 (
        echo Existing FeeLink folder is a different or incomplete build:
        echo "%destination%"
        goto :failed
    )
    echo FeeLink 2.26 is already installed.
    goto :ready
)

if not exist "%archive%" (
    echo Place FeeLink_2.26.zip next to this installer.
    goto :failed
)
echo Checking the FeeLink 2.26 ZIP...
"%SystemRoot%\System32\certutil.exe" -hashfile "%archive%" SHA256 | "%SystemRoot%\System32\findstr.exe" /I /X /C:"%expected%" >nul
if errorlevel 1 (
    echo The ZIP could not be verified. Check the file or ask your IT administrator.
    goto :failed
)
if not exist "%programs%\." mkdir "%programs%"
set "lock=%programs%\.FeeLink-install.lock"
mkdir "%lock%" 2>nul
if errorlevel 1 (
    echo Another FeeLink installation is running, or the Programs folder is not writable.
    goto :failed
)
set "lockHeld=1"
set "stage=%programs%\.FeeLink-install-%RANDOM%-%RANDOM%"
mkdir "%stage%" 2>nul
if errorlevel 1 goto :failed
echo Extracting FeeLink 2.26...
"%SystemRoot%\System32\tar.exe" -xf "%archive%" -C "%stage%" --strip-components 1
if errorlevel 1 goto :partial
call :checkRelease "%stage%"
if errorlevel 1 goto :partial
if exist "%destination%" goto :partial
ren "%stage%" FeeLink
if errorlevel 1 goto :partial

:ready
if defined lockHeld rd "%lock%"
echo FeeLink 2.26: "%destination%\feelink.exe"
if not defined noLaunch start "" /D "%destination%" "%destination%\feelink.exe"
exit /b 0

:checkRelease
if not exist "%~1\feelink.exe" exit /b 1
if not exist "%~1\build_info.json" exit /b 1
"%SystemRoot%\System32\findstr.exe" /C:"2026110820" "%~1\build_info.json" >nul
exit /b %errorlevel%

:partial
echo Installation did not finish. Temporary files are in "%stage%".

:failed
if defined lockHeld rd "%lock%"
if not defined noLaunch pause
exit /b 1
