@echo off
title Stop Paychek Safeguard
setlocal EnableExtensions
cd /d "%~dp0"

set "ROOT=%~dp0"
if "%ROOT:~-1%"=="\" set "ROOT=%ROOT:~0,-1%"
set "PIDFILE=%ROOT%\runtime\safeguard.pid"

if exist "%PIDFILE%" (
  set /p PAYCHEK_PID=<"%PIDFILE%"
  if defined PAYCHEK_PID (
    taskkill /PID %PAYCHEK_PID% /F >nul 2>&1
  )
  del "%PIDFILE%" >nul 2>&1
)

REM Kill python / pythonw processes running desktop_launcher (hidden mode uses pythonw).
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference='SilentlyContinue';" ^
  "Get-CimInstance Win32_Process |" ^
  " Where-Object { $_.Name -match '^(python|pythonw)\.exe$' -and $_.CommandLine -and ($_.CommandLine -like '*desktop_launcher*') } |" ^
  " ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }" >nul 2>&1

REM Local Safeguard port (8080) if still listening.
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference='SilentlyContinue';" ^
  "Get-NetTCPConnection -LocalPort 8080 -State Listen |" ^
  " ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }" >nul 2>&1

echo Paychek Safeguard stopped.
timeout /t 2 >nul
exit /b 0
