@echo off
cls
set CUR_DIR=%cd%

echo Verifying running as administrative user
net session >nul 2>&1
if NOT %errorLevel% == 0 (
   echo Administrator privileges are required to update the Wowza Streaming Engine,  Please retry with Administrator privileges
   goto end
)

set WSERUNNING="false"

for /F "tokens=* skip=1" %%a in (
 	'wmic process where "commandline like '%%Wowza%%'" get commandline'
) do set CMDLINE="%%a" & call :checkcmdline

if exist cmdline.txt del cmdline.txt

if not %WSERUNNING%=="false" goto end

set INSTALL_DIR=%WMSAPP_HOME%

if defined INSTALL_DIR goto install

echo Locating Wowza Streaming Engine installation directory
pushd %cd%
cd ..\..
set INSTALL_DIR=%cd%

REM This handles the case where the install is the root of the drive where we end up with "x:\"
REM the trailing slash creates problems
IF %INSTALL_DIR:~-1%==\ SET INSTALL_DIR=%INSTALL_DIR%.

for /D %%d in (bin,conf,lib,manager) DO ( if NOT EXIST "%%d" goto NOT_INSTALL_DIR )
popd

:install
echo Installing to %INSTALL_DIR%
windows\bin\java -m log4jupdater/com.wowza.solutions.log4jupdater.Log4jUpdater "%INSTALL_DIR%"
echo Update Complete. Please restart services.
goto end

:checkcmdline
echo %CMDLINE% > cmdline.txt
FIND /C /I "wms-bootstrap.jar" cmdline.txt >NUL
if %errorlevel% == 1 goto SERVER_NOT_RUNNING
goto SERVER_IS_RUNNING

:SERVER_NOT_RUNNING
FIND /C /I "wms-winstone" cmdline.txt >NUL
if %errorlevel% == 1 goto MANAGER_NOT_RUNNING
goto MANAGER_IS_RUNNING

:MANAGER_NOT_RUNNING
goto end

:SERVER_IS_RUNNING
echo Wowza Streaming Engine appears to be running.  Please stop it before continuing.
set WSERUNNING="true"
goto end

:MANAGER_IS_RUNNING
echo Wowza Streaming Engine Manager appears to be running.  Please stop it before continuing.
set WSERUNNING="true"
goto end

:NOT_INSTALL_DIR
popd
echo %INSTALL_DIR% does not appear to be a Wowza Streaming Engine install directory.  No update performed.
echo.
echo WSE Updates should be placed in a sub directory of [INSTALL DIR]\updates directory and then run from the windows sub directory of the update.
echo.
echo An example would be to unzip the update into
echo.
echo   C:\Program Files (x86)\Wowza Media Systems\Wowza Streaming Engine 4.0.0\updates\updatelog4j
echo.
echo and then change directory to
echo.
echo   cd C:\Program Files (x86)\Wowza Media Systems\Wowza Streaming Engine 4.0.0\updates\updatelog4j
echo.
echo and executing
echo.
echo    updatelog4j.bat
echo.
echo from there.

:end