@echo off
setlocal

if "%~1" == "/?" goto :showUsage
if "%~1" == "?" goto :showUsage
if "%~1" == "-?" goto :showUsage
if "%~1" == "\?" goto :showUsage
if NOT "%~3" == "" goto :showUsage
goto :checkParams

:showUsage
echo Usage:
echo   %~n0
echo     Check installed WinAgent package:
echo      for 32-bit OS used sce_winagent32_sha256sums.txt
echo      for 64-bit OS used sce_winagent32_sha256sums.txt
echo   %~n0 {file with WinAgent sha256 sums} [WinAgent installed path]
echo Usage in scripts:
echo      call check_sha256sums.cmd [file_path] [WA_path] || goto :error
exit /B 1

:checkParams
set "ChkSumFile=%~dp0sce_winagent64_sha256sums.txt"
set "WinAgentDir=%windir%\SysWOW64\TimeControlSvc\"
if NOT EXIST %WinAgentDir% (
    set "WinAgentDir=%windir%\System32\TimeControlSvc\"
    set "ChkSumFile=%~dp0sce_winagent32_sha256sums.txt"
)

if NOT "%~1" == "" (
    set "ChkSumFile=%~f1"
)

if NOT "%~2" == "" (
    for %%I in ("%2\") do set "WinAgentDir=%%~fI"
)

echo File with sha256 sums: %ChkSumFile%
echo Check files in %WinAgentDir% ...

if NOT EXIST "%ChkSumFile%" (
    echo File with sha256 sums does not exist!
    exit /B 1
)

if NOT EXIST "%WinAgentDir%" (
    echo Check directory does not exist!
    exit /B 1
)

pushd "%WinAgentDir%" || goto :error
powershell "exit (Get-Content -Path '%ChkSumFile%' | %% {$Hash, $_, $File = $_.Split(' ', 3); if($Hash) { if(Test-Path -Path $File -PathType leaf) { $CurHash=((CertUtil -v -hashfile $File SHA256)[1] -replace ' ','').ToUpper(); if ($CurHash -ne $Hash) { Write-Host $File' FAILED'`r`n'Origin  hash: '$Hash`r`n'Current hash: '$CurHash`r`n; [PSCustomObject]@{Path=$File; OrigHash=$Hash} } else { Write-Host $File' OK'`r`n`t$Hash`r`n; } } else {Write-Host $File' DOES NOT EXIST'; [PSCustomObject]@{Path=$File; OrigHash=$Hash} } } } | Measure-Object).Count"
set FAILED_FILES=%errorlevel%
echo Files that failed verification: %FAILED_FILES%
echo The files were checked in the %WinAgentDir%
popd || goto :error
exit /B %FAILED_FILES%

:error
    echo Error in [%0 %*]
    echo exit with code [%errorlevel%]
    exit /B %errorlevel%
