@echo off
title Stop Node
cd /d "%~dp0"
for /f "usebackq delims=" %%V in ("bin\version.txt") do set "NODE_VERSION=%%V"
title AI-Network Stop - %NODE_VERSION%

if not exist ".tmp\active_session.txt" (
    echo [info] No active node session found online! Skipping shutdown...
    goto RunUpdater
)

:: Read the active session name
set /p SESSION_NAME=<".tmp\active_session.txt"
set SESSION_NAME=%SESSION_NAME: =%

if not exist ".tmp\%SESSION_NAME%" (
    echo Error: Session folder .tmp\%SESSION_NAME% is already gone.
    echo.
    pause
    exit /b
)

:: Navigate to the active session folder and stop processes
cd /d ".tmp\%SESSION_NAME%"
powershell -ExecutionPolicy Bypass -File "stop-node.ps1"

cd /d "%~dp0"
echo.
echo Cleaning up session temporary files...

:: Close the monitor script by finding the one running out of this folder (if any)
powershell -Command "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'monitor-node.ps1' -and $_.CommandLine -match '%SESSION_NAME%' } | Invoke-CimMethod -MethodName Terminate" >nul 2>&1

:: Attempt to gracefully clean directory
ping 127.0.0.1 -n 2 >nul
rmdir /s /q ".tmp\%SESSION_NAME%"
del /q ".tmp\active_session.txt"
echo.
echo Session successfully destroyed!

:RunUpdater
echo.
echo Checking for updates...
:: By fundamentally launching the new PowerShell window out of %TEMP%, it fully releases any CWD file locks on the installation directory!
start "AI-Network Updater" /D "%TEMP%" powershell -NoExit -Command "irm https://download.zxiaoming.com/proxy-node-win64/node-win64_install.ps1 | iex"

exit
