@echo off
title Cortana STOP - free GPU for gaming
echo ============================================
echo   Cortana STOP: kiosk :8443 + brain :8081
echo   Frees GPU0 (TTS) + GPU1 (model ~13.5 GB) VRAM
echo ============================================
echo.

REM --- brain :8081 (owner process, plain kill works) ---
for /f "tokens=5" %%A in ('%SystemRoot%\System32\netstat.exe -ano ^| %SystemRoot%\System32\findstr.exe "LISTENING" ^| %SystemRoot%\System32\findstr.exe ":8081 "') do (
  echo   stopping brain :8081  PID %%A
%SystemRoot%\System32\taskkill.exe /F /PID %%A >nul 2>&1
)

REM --- kiosk :8443 (SYSTEM task since 09-06: plain kill fails -> elevated schtasks /End) ---
for /f "tokens=5" %%A in ('%SystemRoot%\System32\netstat.exe -ano ^| %SystemRoot%\System32\findstr.exe "LISTENING" ^| %SystemRoot%\System32\findstr.exe ":8443 "') do (
  echo   stopping kiosk :8443  PID %%A
%SystemRoot%\System32\taskkill.exe /F /PID %%A >nul 2>&1
)
%SystemRoot%\System32\netstat.exe -ano | %SystemRoot%\System32\findstr.exe "LISTENING" | %SystemRoot%\System32\findstr.exe /C:":8443 " >nul 2>&1
if errorlevel 1 goto PORTSCLEAR
echo   kiosk is SYSTEM-owned - ending scheduled task (UAC prompt)...
powershell.exe -NoProfile -Command "Start-Process schtasks.exe -ArgumentList '/End','/TN','Cortana_Kiosk' -Verb RunAs -Wait"
:PORTSCLEAR

echo.
echo Waiting for ports to release (VRAM frees with the process)...
set /a N=0
:WAIT
set /a N+=1
set FREE=1
%SystemRoot%\System32\netstat.exe -ano | %SystemRoot%\System32\findstr.exe "LISTENING" | %SystemRoot%\System32\findstr.exe /C:":8443 " >nul 2>&1 && set FREE=0
%SystemRoot%\System32\netstat.exe -ano | %SystemRoot%\System32\findstr.exe "LISTENING" | %SystemRoot%\System32\findstr.exe /C:":8081 " >nul 2>&1 && set FREE=0
if "%FREE%"=="1" goto FREED
if %N% GEQ 40 goto FREED
%SystemRoot%\System32\timeout.exe /t 1 /nobreak >nul
goto WAIT
:FREED
echo.
echo   Ports 8443 + 8081 released.
echo   NOTE: Cortana_Kiosk task will restart her at the next boot (or run Cortana-RESTORE).
if not defined NOPAUSE pause
