@echo off
setlocal
fltmc >nul 2>&1
if errorlevel 1 (
  powershell.exe -NoProfile -WindowStyle Hidden -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
  exit /b
)
set "AMAGING_PORTABLE_SRC=%~dp0"
set "AMAGING_HOST_DEST=%ProgramFiles%\Amaging Remote Portable Host"
set "AMAGING_CERT_THUMBPRINT=A609D87FF28A26550D3ABE86C80BA0CF1DC646EB"

rem Refuse damaged/replaced release files before granting them SYSTEM rights.
powershell.exe -NoProfile -Command "$expected=$env:AMAGING_CERT_THUMBPRINT; $cert=New-Object Security.Cryptography.X509Certificates.X509Certificate2((Join-Path $env:AMAGING_PORTABLE_SRC 'AmagingRemote.cer')); if($cert.Thumbprint -ne $expected){exit 40}"
if errorlevel 1 goto :verify_failed
certutil.exe -addstore Root "%AMAGING_PORTABLE_SRC%AmagingRemote.cer" >nul
powershell.exe -NoProfile -Command "$expected=$env:AMAGING_CERT_THUMBPRINT; foreach($name in @('amaging-host.exe','amaging-input.exe','amaging-capture.exe')){$sig=Get-AuthenticodeSignature -LiteralPath (Join-Path $env:AMAGING_PORTABLE_SRC $name); if($sig.Status -ne 'Valid' -or $sig.SignerCertificate.Thumbprint -ne $expected){exit 41}}"
if errorlevel 1 goto :verify_failed

rem A LocalSystem service must never execute from the user-writable portable
rem extraction folder. Copy the signed sibling set into protected Program Files.
net.exe stop AmagingHostService >nul 2>&1
taskkill.exe /F /IM amaging-host.exe >nul 2>&1
if not exist "%AMAGING_HOST_DEST%" mkdir "%AMAGING_HOST_DEST%"
copy /y "%AMAGING_PORTABLE_SRC%amaging-host.exe" "%AMAGING_HOST_DEST%\amaging-host.exe" >nul
if errorlevel 1 goto :copy_failed
copy /y "%AMAGING_PORTABLE_SRC%amaging-input.exe" "%AMAGING_HOST_DEST%\amaging-input.exe" >nul
if errorlevel 1 goto :copy_failed
copy /y "%AMAGING_PORTABLE_SRC%amaging-capture.exe" "%AMAGING_HOST_DEST%\amaging-capture.exe" >nul
if errorlevel 1 goto :copy_failed
icacls.exe "%AMAGING_HOST_DEST%" /inheritance:e >nul

"%AMAGING_HOST_DEST%\amaging-host.exe" install
sc.exe config AmagingHostService binPath= "\"%AMAGING_HOST_DEST%\amaging-host.exe\"" start= auto
sc.exe failure AmagingHostService reset= 86400 actions= restart/1000/restart/3000/restart/10000
sc.exe failureflag AmagingHostService 1
sc.exe sdset AmagingHostService "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWRPWPLORC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"
netsh.exe advfirewall firewall delete rule name="Amaging Remote Host" >nul 2>&1
netsh.exe advfirewall firewall add rule name="Amaging Remote Host" dir=in action=allow program="%AMAGING_HOST_DEST%\amaging-host.exe" profile=any enable=yes
net.exe start AmagingHostService
echo.
echo Amaging Remote host service is installed in protected Program Files and running.
pause
exit /b 0

:verify_failed
echo.
echo ERROR: Release signature verification failed. The host service was not installed.
pause
exit /b 41

:copy_failed
echo.
echo ERROR: Could not copy the signed host files into protected Program Files.
pause
exit /b 42
