@echo off

:ValidateArgs
if [%1] == [] goto :Usage


:LocalConfig
setlocal
set "AppNamePart=%~1"
set "PostKillCommand=%~2"
set "MsgPrelude=Process with name containing"
set "KillSignalSent=0"
set "DetectPeriod=1"
if %DetectPeriod% EQU 1 (
    set "DetectPeriodUnit=second"
) else (
    set "DetectPeriodUnit=seconds"
)


:ProcessDetection
tasklist /fi "ImageName eq %AppNamePart%*" /fo csv 2>NUL | find /i "%AppNamePart%" >NUL
if errorlevel 1 (
    echo %MsgPrelude% "%AppNamePart%" detected as NOT running.
    goto PostTermination
) else (
    echo %MsgPrelude% "%AppNamePart%" detected as running.
)


:ProcessTermination
if %KillSignalSent% EQU 0 (
    echo Sending kill signal for processes containing "%AppNamePart%".
    taskkill /f /fi "IMAGENAME eq %AppNamePart%*"
    set "KillSignalSent=1"
)
set /a "PingCount=%DetectPeriod%+1"
echo Waiting %DetectPeriod% %DetectPeriodUnit%...
ping -n %PingCount% /w 1000 127.0.0.1 >NUL
goto ProcessDetection


:PostTermination
if not [%1] == [] (
    echo Running command: "%PostKillCommand%"...
    %PostKillCommand%
    echo Done.
)
goto Cleanup


:Usage
echo %~n0 processname [postkillcmd]


:Cleanup
endlocal
