@echo off
setlocal enabledelayedexpansion

REM trim the MSI and upgrade log files in case they get too big
powershell.exe -command "$logFilePath = 'C:\temp\filewaveclient.log'; if ((Get-Item $logFilePath).Length -gt 10MB) { [System.IO.File]::WriteAllBytes($logFilePath, [System.IO.File]::ReadAllBytes($logFilePath)[-10MB..-1]) }"
powershell.exe -command "$logFilePath = 'C:\temp\upgradeclient.log'; if ((Get-Item $logFilePath).Length -gt 10MB) { [System.IO.File]::WriteAllBytes($logFilePath, [System.IO.File]::ReadAllBytes($logFilePath)[-10MB..-1]) }"

call :WriteOut "Waiting to start the upgrade process"
REM Wait 2 minutes to start
timeout 120

REM In case of previous customised setup could fail if this file is not present
REM older versions (32b)
mkdir "c:\Program Files (x86)\FileWave"
type nul > "C:\Program Files (x86)\FileWave\customise.bat"
REM new versions (64b)
mkdir "c:\Program Files\FileWave"
mkdir "c:\Program Files\FileWave\client"
type nul > "C:\Program Files\FileWave\client\customise.bat"

set /a count=0
taskkill /F /IM fwGUI.exe > NUL
taskkill /F /IM filewavekiosk.exe > NUL

REM Changing fwclient service so it does not attempt to restart when we stop it
REM Particularly important if service does not stop gracefully
sc failure FileWaveWinClient actions=none reset=0
call :WriteOut "Disable service auto restart, exit code %ERRORLEVEL%"

:stopservice
set /a count+=1
if %count% EQU 40  (
    call :WriteOut "Tried 40 times to stop the service - killing and moving on."
    GOTO stopprocess
)

sc stop FileWaveWinClient
call :WriteOut "Attempted to stop FileWave Client, exit code %ERRORLEVEL%"
timeout /t 2 /nobreak > NUL
sc query filewavewinclient | FIND "STOPPED" > NUL

if %ERRORLEVEL% EQU 1060 (
    call :WriteOut "exit code is 1060 - this means service is not there anymore. We should not try to stop it."
    GOTO stopprocess
)
IF errorlevel 1 GOTO stopservice

:stopprocess
set process_name=fwcld.exe
set timeout=30
call :WriteOut "Waiting for %process_name% to stop..."

:LOOP
tasklist | find /i "%process_name%" > NUL
if errorlevel 1 (
    call :WriteOut "process %process_name% has stopped..."
    GOTO :END
) else (
    timeout /t 1 > NUL
    set /a timeout-=1
    if !timeout! leq 0 (
        call :WriteOut "Timeout reached.%process_name% did not stop within 30 seconds."
        GOTO :END
    ) else (
        call :WriteOut "Still waiting for %process_name% to stop..."
        GOTO :LOOP
    )
)
:END

tasklist | find /i "fwcld.exe" > NUL
if not errorlevel 1 (
    taskkill /F /IM fwcld.exe > NUL
    call :WriteOut "Attempted to kill fwcld.exe, exit code %ERRORLEVEL%"
)

tasklist | find /i "fwzmqbroker.exe" > NUL
if not errorlevel 1 (
    taskkill /F /IM fwzmqbroker.exe > NUL
    call :WriteOut "Attempted to kill fwzmqbroker.exe, exit code %ERRORLEVEL%"
)

REM backup current client configuration
reg export /y hklm\SOFTWARE\WOW6432Node\FileWave\WinClient c:\temp\fwclient.reg
call :WriteOut "Attempted to export client configuration, exit code %ERRORLEVEL%"

call :WriteOut "Delete PID file"
:deletingpid
set /a count+=1
if %count% EQU 80 goto exit /B 3
timeout /t 2 /nobreak > NUL
del /f %ProgramData%\FileWave\FWClient\fwcld.pid > NUL
IF exist %ProgramData%\FileWave\FWClient\fwcld.pid GOTO deletingpid


call :WriteOut "Try to install now new client..."
set /a count=0

:installclient
timeout /t 2 /nobreak > NUL
set /a count+=1
REM switchin this to 5 retries and NOT trapping 1603
if %count% EQU 5  (
    call :WriteOut "Tried 5 times to install the new MSI - considering upgrade as a failure."
)
else (
    call :WriteOut "Installing the new FileWave Client..."
    start /wait msiexec /qn /norestart /l*v+ FileWaveClient.log /i C:\temp\FileWaveClient.msi
    call :WriteOut "Done Installing the new FileWave Client, exit code %ERRORLEVEL%"
    if %ERRORLEVEL% EQU 1638 GOTO alreadyinstalled
    if %ERRORLEVEL% NEQ 0 GOTO installclient
)

:alreadyinstalled
:: in case msiexec went wrong, start the service again - for example to recover from trying to upgrade package with the same version
call :WriteOut "Start service (even in case installation failed)..."
sc start FileWaveWinClient
call :WriteOut "Exit 0 - Upgrade done"

REM In case client configuration was wiped out (rare case), restore from backup
reg query HKEY_LOCAL_MACHINE\Software\wow6432node\filewave\winclient /v server | find /i "no.server.set"
if %ERRORLEVEL% equ 1 (
    call :WriteOut "The server address is correct"
) else (
    call :WriteOut "Fixing server address"
    REM Hard killing fwcld.exe since it isn't right and service stop might be delayed
    taskkill /F /IM fwcld.exe
    reg import c:\temp\fwclient.reg
	GOTO alreadyinstalled
)

exit /b 0

::----------------------------------------------------------------------------------------
:WriteOut <Message>
Set "Message=%~1"
echo "%DATE% %TIME% == %Message%" >> upgradeClient.log
exit /b
::----------------------------------------------------------------------------------------
